@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
|
@@ -171,7 +171,7 @@ ${tc(t)}`).digest("hex")}var fe=A(()=>{"use strict"});import jr from"path";funct
|
|
|
171
171
|
# 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
|
|
172
172
|
# 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
|
|
173
173
|
# 可选值:true | false`,"classic.document_evidence":`# 文档编辑对已记录检查证据的影响:neutral 在只有文档文件变化时保持 build 和 verify 证据有效,strict 重新绑定工作区的全部文件。
|
|
174
|
-
# 可选值:neutral | strict`}}});import{constants as cc,promises as ui}from"fs";function ef(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Ug(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Ia(e){return{dev:e.dev,ino:e.ino,birthtime:ef(e)}}function lc(e,t){let r=Ia(e),i=Ia(t);return wt(r,i)?Z(r,i):Z(r,i)&&ef(e)===ef(t)&&Ug(e)===Ug(t)&&e.size===t.size}async function en(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 ui.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new bt("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new bt("too-large",`${i} exceeds ${t} bytes`);let o=await ui.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:Ia(a)});let s=process.platform==="win32"?cc.O_RDONLY:cc.O_RDONLY|cc.O_NOFOLLOW|cc.O_NONBLOCK,c;try{c=await ui.open(e,s)}catch(l){throw l.code==="ELOOP"?new bt("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,f]=await Promise.all([c.stat({bigint:n}),ui.lstat(e,{bigint:n}),ui.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||f!==o||!lc(a,l)||!lc(a,u))throw new bt("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:f,identity:Ia(l)}),await r.hooks?.afterOpen?.();let d=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-p,{bytesRead:y}=await c.read(m,0,Math.min(m.length,w),null);if(y===0)break;if(p+=y,p>t)throw new bt("too-large",`${i} exceeds ${t} bytes`);d.push(Buffer.from(m.subarray(0,y)))}await r.hooks?.beforeFinalCheck?.();let[h,g,v]=await Promise.all([c.stat({bigint:n}),ui.lstat(e,{bigint:n}),ui.realpath(e)]);if(!g.isFile()||g.isSymbolicLink()||v!==o||!lc(a,h)||!lc(a,g))throw new bt("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:v,identity:Ia(h)}),{bytes:Buffer.concat(d,p),stat:h,realPath:v}}finally{await c.close()}}var bt,Ta=A(()=>{"use strict";Ea();bt=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as uc}from"fs";import Or from"path";function rP(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function tf(e,t){let r=Or.relative(e,t);return r===""||!Or.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Or.sep}`)}async function Kg(e,t){let r=Or.resolve(e),i=await uc.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return uc.realpath(r)}async function Yg(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Or.join(n,r[a]);let o;try{o=await uc.lstat(n)}catch(u){if(rP(u))return{exists:!1,kind:"missing"};throw u}let s=Or.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 uc.realpath(n);if(!tf(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 tn(e,t,r){let i=ac(t,r.label),n=Or.resolve(e),a=await Kg(n,r.label),o=i.split("/"),s=Or.resolve(n,...o);if(!tf(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Yg(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function sr(e,t,r,i){let n=await tn(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 Kg(n.projectRoot,i.label);return en(n.target,r,{...i,verify:async(o,s)=>{if(!tf(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Yg(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var Hr=A(()=>{"use strict";Ta();$r()});import{createHash as iP}from"crypto";function rf(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function nP(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function dc(e,t={}){return(await $a(e,t)).document}async function Xg(e){try{return(await sr(e,ja,Pa,{label:ja})).bytes}catch(t){if(nP(t))return null;throw t}}function Qg(e){return e?{exists:!0,sha256:iP("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function fc(e){return Qg(await Xg(e))}async function $a(e,t={}){let r=await Xg(e);return{document:r?Zi(r.toString("utf8"),t):null,identity:Qg(r)}}async function nf(e){return(await dc(e))?.config??null}var ja,rn=A(()=>{"use strict";$r();Hr();ja=".comet/config.yaml"});import{promises as of}from"node:fs";async function sf(e,t){let r;for(let i=0;i<=af.length;i+=1)try{return await e()}catch(n){r=n;let a=n.code;if(i===af.length||!aP.has(a??""))throw n;await new Promise(o=>setTimeout(o,af[i]))}throw r}async function cf(e,t){await sf(()=>of.rename(e,t),`rename ${t}`)}async function lf(e){await sf(()=>of.unlink(e),`unlink ${e}`)}async function uf(e,t){await sf(()=>of.link(e,t),`link ${t}`)}var aP,af,df=A(()=>{"use strict";aP=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),af=[50,100,200]});var nn=A(()=>{"use strict";df();Ea()});var
|
|
174
|
+
# 可选值:neutral | strict`}}});import{constants as cc,promises as ui}from"fs";function ef(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Ug(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Ia(e){return{dev:e.dev,ino:e.ino,birthtime:ef(e)}}function lc(e,t){let r=Ia(e),i=Ia(t);return wt(r,i)?Z(r,i):Z(r,i)&&ef(e)===ef(t)&&Ug(e)===Ug(t)&&e.size===t.size}async function en(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 ui.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new bt("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new bt("too-large",`${i} exceeds ${t} bytes`);let o=await ui.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:Ia(a)});let s=process.platform==="win32"?cc.O_RDONLY:cc.O_RDONLY|cc.O_NOFOLLOW|cc.O_NONBLOCK,c;try{c=await ui.open(e,s)}catch(l){throw l.code==="ELOOP"?new bt("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,f]=await Promise.all([c.stat({bigint:n}),ui.lstat(e,{bigint:n}),ui.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||f!==o||!lc(a,l)||!lc(a,u))throw new bt("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:f,identity:Ia(l)}),await r.hooks?.afterOpen?.();let d=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-p,{bytesRead:y}=await c.read(m,0,Math.min(m.length,w),null);if(y===0)break;if(p+=y,p>t)throw new bt("too-large",`${i} exceeds ${t} bytes`);d.push(Buffer.from(m.subarray(0,y)))}await r.hooks?.beforeFinalCheck?.();let[h,g,v]=await Promise.all([c.stat({bigint:n}),ui.lstat(e,{bigint:n}),ui.realpath(e)]);if(!g.isFile()||g.isSymbolicLink()||v!==o||!lc(a,h)||!lc(a,g))throw new bt("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:v,identity:Ia(h)}),{bytes:Buffer.concat(d,p),stat:h,realPath:v}}finally{await c.close()}}var bt,Ta=A(()=>{"use strict";Ea();bt=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as uc}from"fs";import Or from"path";function rP(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function tf(e,t){let r=Or.relative(e,t);return r===""||!Or.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Or.sep}`)}async function Kg(e,t){let r=Or.resolve(e),i=await uc.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return uc.realpath(r)}async function Yg(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Or.join(n,r[a]);let o;try{o=await uc.lstat(n)}catch(u){if(rP(u))return{exists:!1,kind:"missing"};throw u}let s=Or.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 uc.realpath(n);if(!tf(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 tn(e,t,r){let i=ac(t,r.label),n=Or.resolve(e),a=await Kg(n,r.label),o=i.split("/"),s=Or.resolve(n,...o);if(!tf(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Yg(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function sr(e,t,r,i){let n=await tn(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 Kg(n.projectRoot,i.label);return en(n.target,r,{...i,verify:async(o,s)=>{if(!tf(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Yg(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var Hr=A(()=>{"use strict";Ta();$r()});import{createHash as iP}from"crypto";function rf(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function nP(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function dc(e,t={}){return(await $a(e,t)).document}async function Xg(e){try{return(await sr(e,ja,Pa,{label:ja})).bytes}catch(t){if(nP(t))return null;throw t}}function Qg(e){return e?{exists:!0,sha256:iP("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function fc(e){return Qg(await Xg(e))}async function $a(e,t={}){let r=await Xg(e);return{document:r?Zi(r.toString("utf8"),t):null,identity:Qg(r)}}async function nf(e){return(await dc(e))?.config??null}var ja,rn=A(()=>{"use strict";$r();Hr();ja=".comet/config.yaml"});import{promises as of}from"node:fs";async function sf(e,t){let r;for(let i=0;i<=af.length;i+=1)try{return await e()}catch(n){r=n;let a=n.code;if(i===af.length||!aP.has(a??""))throw n;await new Promise(o=>setTimeout(o,af[i]))}throw r}async function cf(e,t){await sf(()=>of.rename(e,t),`rename ${t}`)}async function lf(e){await sf(()=>of.unlink(e),`unlink ${e}`)}async function uf(e,t){await sf(()=>of.link(e,t),`link ${t}`)}var aP,af,df=A(()=>{"use strict";aP=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),af=[50,100,200]});var nn=A(()=>{"use strict";df();Ea()});var TD,ff=A(()=>{"use strict";nn();rn();Hr();TD=16*1024});async function pf(e,t){if(!t)return;let r=await fc(e);if(!rf(r,t))throw new Error("Project config changed before commit; rerun the operation")}var hf=A(()=>{"use strict";nn();$r();rn();Hr();ff()});import{randomUUID as lP}from"crypto";import{promises as Pe}from"fs";import kt from"path";function pc(e,t){let r=kt.relative(e,t);return r===""||!kt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${kt.sep}`)}function uP(e,t){return Z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function hc(e,t){return Z({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function dP(e,t){return hc(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Zg(e){let t=await Pe.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await Pe.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function an(e){for(let t of e){let r=await Pe.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!uP(t,r)||await Pe.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function fP(e,t,r){let[i,n]=await Promise.all([Pe.lstat(e),Pe.realpath(e),r?an(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!hc(i,t)||r&&!pc(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function pP(e,t){let r=kt.resolve(e),i=kt.resolve(t);if(!pc(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Zg(r)],a=kt.relative(r,i).split(kt.sep).filter(Boolean),o=r;for(let s of a){await an(n),o=kt.join(o,s);try{await Pe.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Zg(o);if(!pc(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await an(n),n}async function hP(e){let t;try{t=await Pe.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 mP(e,t,r={}){let i=kt.dirname(e),n=r.containedRoot?await pP(r.containedRoot,i):null;n||await Pe.mkdir(i,{recursive:!0});let a=kt.join(i,`.${kt.basename(e)}.${lP()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await Pe.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([Pe.lstat(a),Pe.realpath(a)]);if(await an(n),!l.isFile()||l.isSymbolicLink()||!hc(s,l)||!pc(n[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!hc(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await fP(a,c,n),await r.beforeCommit?.(),n){await an(n);let l=await Pe.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!dP(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await uf(a,e),await lf(a)):await cf(a,e),await hP(i)}catch(l){if(await o?.close(),!n)await Pe.rm(a,{force:!0});else try{await an(n),await Pe.rm(a,{force:!0})}catch{}throw l}}async function at(e,t,r={}){await mP(e,t,r)}async function we(e,t,r={}){await at(e,JSON.stringify(t,null,2)+`
|
|
175
175
|
`,r)}var ne=A(()=>{"use strict";df();Dt()});import{existsSync as ew,promises as di}from"fs";import U from"path";import vP from"os";async function mf(e){try{return await di.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function wP(e){try{let t=await di.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function sn(e,t){let r=U.relative(e,t);return r===""||!U.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${U.sep}`)}async function on(e){let t=[],r=e;for(;!await mf(r);){let n=U.dirname(r);if(n===r)break;t.push(U.basename(r)),r=n}let i=await di.realpath(r);return U.resolve(i,...t.reverse())}async function vf(e){try{return(await di.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function mc(e){let t=U.resolve(e);try{(await di.stat(t)).isDirectory()||(t=U.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=U.resolve(vP.homedir());for(;;){if(!(t===i&&r!==i)){let o=U.join(t,...Ha.split("/")),s=t===r||await wP(o);if(await mf(o)&&s)return t}if(await mf(U.join(t,".git")))return t;let a=U.dirname(t);if(a===t)return r;t=a}}function vc(e){return li(e)}async function yP(e,t){let r=vc(t),i=U.resolve(e,...r.split("/")),n=await di.realpath(e),a=await on(i);if(!sn(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Dr(e,t){let r=vc(t),i=await yP(e,r),n=U.join(i,"comet");if(await vf(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([on(i),on(n)]);if(!sn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=U.resolve(e),c=U.join(s,".comet","runtime","native");if(await vf(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([di.realpath(s),on(c)]);if(!sn(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:U.join(e,...Ha.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:U.join(n,"specs"),changesDir:U.join(n,"changes"),archiveDir:U.join(n,"archive"),runtimeDir:c,changesRuntimeDir:U.join(c,"changes"),locksDir:U.join(c,"locks"),transactionsDir:U.join(c,"transactions")}}function tw(e){if(!gP.test(e))throw new Error(`Invalid Native change name: ${e}`)}function pe(e,t){tw(t);let r=U.join(e.changesRuntimeDir,t);if(!be(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function gf(e,t){tw(t);let r=U.join(e.changesDir,t,"runtime");if(!be(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function ot(e,t){let r=pe(e,t);if(ew(r))return r;let i=gf(e,t);return ew(i)?i:r}function wf(e,t){if(!t.startsWith("runtime/")||U.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=U.resolve(e,...t.slice(8).split("/"));if(!be(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function qe(e,t){let r=U.resolve(t);if(be(e.runtimeDir,r))return e.runtimeDir;if(be(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function be(e,t){return sn(U.resolve(e),U.resolve(t))}async function z(e,t){let r=U.resolve(e),i=U.resolve(t);if(!sn(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await vf(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([on(r),on(i)]);if(!sn(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var Ha,gP,te=A(()=>{"use strict";$r();Ha=".comet/config.yaml",gP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import NP from"path";function bP(e="docs",t="en"){return sc(e,t)}async function _e(e){let t=(await dc(e))?.config??null;return t?.native?t:null}async function wc(e){let t=await _e(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 yc(e,t,r={}){let i=await $a(e,{allowPartialProject:!0}),n=Aa(i.document?.value??{},t),a=NP.join(e,...Ha.split("/"));await at(a,_a(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await pf(e,i.identity)}})}async function rw(e){let t=await mc(e.startPath),r=await _e(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Ha} 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?vc(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??bP(i??"docs"),a=await Dr(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var gc,st=A(()=>{"use strict";$r();rn();hf();ne();te();gc=oc});function bc(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var fi,Da,Nc,cn=A(()=>{"use strict";fi="comet.native.v4",Da="comet.native.local-execution.v4",Nc=["multi-session","single-session"]});var kf={};du(kf,{NativePortableStateVersionConflictError:()=>Ba,appendNativePortableHistory:()=>ye,compareAndSwapNativePortableState:()=>dn,createNativePortableState:()=>nw,parseNativePortableState:()=>B,readNativePortableState:()=>lt,writeNativePortableState:()=>La});import{promises as kP}from"node:fs";function Ae(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ie(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 ke(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function Nf(e,t){return e===null?null:ke(e,t)}function bf(e,t){let r=ke(e,t);if(!CP.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function ln(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ae(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 PP(e,t){return e===null?null:ae(e,t,Number.MIN_SAFE_INTEGER)}function he(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Bt(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function xc(e,t){return Bt(e,t,(r,i)=>ke(r,`${t}[${i}]`))}function pi(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function un(e,t){let r=ke(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Sc(e,t,r=!1){let i=ke(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function ct(e,t){let r=Ae(e,t);return Ie(r,new Set(["text","truncated"]),t),{text:ke(r.text,`${t}.text`,{empty:!0}),truncated:ln(r.truncated,`${t}.truncated`)}}function _P(e,t){let r=`Native spec_changes[${t}]`,i=Ae(e,r);Ie(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=ke(i.capability,`${r}.capability`);if(!EP.test(n))throw new Error(`${r}.capability is invalid`);let a=he(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Sc(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:Sc(i.delta_source,`${r}.delta_source`),c=i.base_hash===void 0?void 0:i.base_hash===null?null:bf(i.base_hash,`${r}.base_hash`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);if(s!==void 0&&a==="remove")throw new Error(`${r} remove cannot contain delta_source`);if(s!==void 0&&c==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(c!==void 0&&s===void 0&&a!=="remove")throw new Error(`${r} base_hash requires delta_source for non-remove specs`);return{capability:n,operation:a,source:o,...s===void 0?{}:{delta_source:s},...c===void 0?{}:{base_hash:c}}}function AP(e){let t="Native workspace",r=Ae(e,t);Ie(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=he(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=Nf(r.change_branch,`${t}.change_branch`),a=Nf(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:he(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function IP(e){let t="Native loop",r=Ae(e,t);Ie(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=xc(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);pi(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:he(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:he(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:ae(r.goal_cycle,`${t}.goal_cycle`,1),iteration:ae(r.iteration,`${t}.iteration`),attempt:ae(r.attempt,`${t}.attempt`),retry_epoch:ae(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:ae(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:ae(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:ae(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:Nf(r.next_action,`${t}.next_action`)}}function TP(e,t){let r=`Native acceptance[${t}]`,i=Ae(e,r);Ie(i,new Set(["id","source","text","result","reason"]),r);let n=ke(i.id,`${r}.id`);if(!xP.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Sc(i.source,`${r}.source`),text:ke(i.text,`${r}.text`),result:he(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:ct(i.reason,`${r}.reason`)}}function jP(e,t){let r=`Native builder_handoff.checks[${t}]`,i=Ae(e,r);return Ie(i,new Set(["name","result","note"]),r),{name:ct(i.name,`${r}.name`),result:he(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:ct(i.note,`${r}.note`)}}function $P(e){let t="Native builder_handoff",r=Ae(e,t);Ie(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=xc(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);pi(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:Ae(r.review,`${t}.review`);return n&&Ie(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:ke(r.candidate_id,`${t}.candidate_id`),identity_provider:ke(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:ke(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:ae(r.iteration,`${t}.iteration`,1),summary:ct(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Bt(r.checks,`${t}.checks`,jP),checks_truncated:ln(r.checks_truncated,`${t}.checks_truncated`),known_limits:Bt(r.known_limits,`${t}.known_limits`,(a,o)=>ct(a,`${t}.known_limits[${o}]`)),known_limits_truncated:ln(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:he(n.status,["passed"],`${t}.review.status`),summary:ct(n.summary,`${t}.review.summary`),reviewer_execution_ref:ke(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:un(r.submitted_at,`${t}.submitted_at`)}}function OP(e,t){let r=`Native blockers[${t}]`,i=Ae(e,r);Ie(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=xc(i.acceptance_ids,`${r}.acceptance_ids`);return pi(n,`${r}.acceptance_ids`),{owner:he(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:ct(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:he(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function HP(e,t){let r=`Native verification.checks[${t}]`,i=Ae(e,r);return Ie(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:ke(i.id,`${r}.id`),name:ct(i.name,`${r}.name`),argv_display:Bt(i.argv_display,`${r}.argv_display`,(n,a)=>ct(n,`${r}.argv_display[${a}]`)),argv_truncated:ln(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Sc(i.cwd_ref,`${r}.cwd_ref`,!0),status:he(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:PP(i.exit_code,`${r}.exit_code`),duration_ms:ae(i.duration_ms,`${r}.duration_ms`)}}function DP(e){let t="Native verification",r=Ae(e,t);Ie(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Bt(r.checks,`${t}.checks`,HP);pi(i.map(a=>a.id),`${t}.checks IDs`);let n=ke(r.identity_provider,`${t}.identity_provider`);return{candidate_id:ke(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:ke(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:ae(r.iteration,`${t}.iteration`,1),attempt:ae(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":he(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:he(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:ct(r.summary,`${t}.summary`),risks:Bt(r.risks,`${t}.risks`,(a,o)=>ct(a,`${t}.risks[${o}]`)),risks_truncated:ln(r.risks_truncated,`${t}.risks_truncated`),completed_at:un(r.completed_at,`${t}.completed_at`)}}function iw(e,t){let r=`Native history[${t}]`,i=Ae(e,r);Ie(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=xc(i.unresolved_ids,`${r}.unresolved_ids`);return pi(n,`${r}.unresolved_ids`),{goal_cycle:ae(i.goal_cycle,`${r}.goal_cycle`,1),iteration:ae(i.iteration,`${r}.iteration`),attempt:ae(i.attempt,`${r}.attempt`),outcome:he(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:ct(i.summary,`${r}.summary`),completed_at:un(i.completed_at,`${r}.completed_at`)}}function BP(e){let t="Native history_overflow.outcome_counts",r=Ae(e,t),i=["pass","fail","blocked","execution-error","recovery"];return Ie(r,new Set(i),t),{pass:ae(r.pass,`${t}.pass`),fail:ae(r.fail,`${t}.fail`),blocked:ae(r.blocked,`${t}.blocked`),"execution-error":ae(r["execution-error"],`${t}.execution-error`),recovery:ae(r.recovery,`${t}.recovery`)}}function LP(e){let t="Native history_overflow",r=Ae(e,t);Ie(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=ae(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:un(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:un(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=BP(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function qP(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function FP(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function B(e){let t=Ae(e,"Native portable state");if(Ie(t,RP,"Native portable state"),t.schema!==fi)throw new Error(`Native portable state schema must be ${fi}`);let r=ke(t.name,"Native state name");if(!SP.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Bt(t.spec_changes,"Native spec_changes",_P);pi(i.map(s=>s.capability),"Native spec change capabilities");let n=Bt(t.acceptance,"Native acceptance",TP);pi(n.map(s=>s.id),"Native acceptance IDs");let a=Bt(t.history,"Native history",iw);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:fi,name:r,language:he(t.language,["en","zh-CN"],"Native state language"),phase:he(t.phase,["shape","build","verify","archive"],"Native state phase"),status:he(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:ae(t.state_version,"Native state_version",1),brief:"brief.md",...t.document_constraints_version===void 0?{}:t.document_constraints_version===1?{document_constraints_version:1}:(()=>{throw new Error("Native document_constraints_version must be 1")})(),...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:bf(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:bf(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:he(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:AP(t.workspace),loop:IP(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:$P(t.builder_handoff),blockers:Bt(t.blockers,"Native blockers",OP),verification:t.verification===null?null:DP(t.verification),history:a,history_overflow:LP(t.history_overflow),verification_result:he(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:he(t.verification_report,["verification.md"],"Native verification_report"),archived:ln(t.archived,"Native archived"),created_at:un(t.created_at,"Native created_at")};return qP(o),FP(o),o}function nw(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return B({schema:fi,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:bc(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function ye(e,t){let r=B(e),i=iw(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return B({...r,history:n,history_overflow:a})}function VP(e,t){let r=(0,Ec.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function lt(e){let t=await kP.readFile(e,"utf8");return B(VP(t,"Native portable state"))}async function La(e,t,r={}){let i=B(t);await at(e,(0,Ec.stringify)(i),r)}async function MP(e,t){let r=kc.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);kc.set(e,a),await r;try{return await t()}finally{i(),kc.get(e)===a&&kc.delete(e)}}async function dn(e){return MP(e.file,async()=>{let t=ae(e.expectedStateVersion,"Native expected state version",1),r=B(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await lt(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new Ba(t,i.state_version);return await La(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await lt(e.file);if(n.state_version!==t)throw new Ba(t,n.state_version)}}),r})}var Ec,SP,EP,xP,CP,RP,Ba,kc,ut=A(()=>{"use strict";Ec=br(rr(),1);ne();cn();SP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,EP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xP=/^A[1-9][0-9]*$/u,CP=/^[a-f0-9]{64}$/u,RP=new Set(["schema","name","language","phase","status","state_version","brief","document_constraints_version","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),Ba=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};kc=new Map});import{promises as WP}from"node:fs";import zP from"node:path";function Rc(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Cc(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function ow(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function XP(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function sw(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function dw(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===Ef&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),f=e.acceptance_index[l];u&&f&&(f.source!==u.source||f.text!==u.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return i.uncovered=o.filter(l=>!cw(e.children,l)),lw(i)?i:null}if(e.schema===hi&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!cw(e.children,a)),lw(i)?i:null}return null}function cw(e,t){return e.some(r=>r.covers.includes(t))}function lw(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function dt(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function QP(e){let t=Rc(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=Rc(n,`Native children acceptance_index.${i}`);if(Cc(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function ZP(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let f=e[l];if(f.source!==u.source||f.text!==u.text){let d=["source","text"].filter(p=>f[p]!==u[p]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${d.join(", ")} exactly from the current acceptance catalog`)}}}function fw(e,t,r={}){let i=(0,uw.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Rc(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==hi&&a!==Br)throw Cc(n,aw,"Native children contract"),new Error(`Native children schema must be ${hi} or ${Br}`);let o=a===hi?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Cc(n,o==="indexed-v2"?GP:aw,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((d,p)=>{let m=Rc(d,`Native child ${p}`);if(Cc(m,o==="indexed-v2"?YP:o==="summary-v2"?KP:UP,`Native ${s} child fields (child ${p})`),typeof m.name!="string"||!JP.test(m.name))throw new Error(`Native child ${p} name is invalid`);let h=o==="summary-v2";if(h){if(typeof m.summary!="string"||m.summary.trim().length===0)throw new Error(`Native child ${m.name} summary must be a non-empty string`);if(m.summary.length>2e3)throw new Error(`Native child ${m.name} summary exceeds 2000 characters`)}return{name:m.name,summary:h?m.summary:null,depends_on:ow(m.depends_on,`Native child ${m.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?ow(m.covers,`Native child ${m.name} covers`):[]}}),l=c.map(({name:d})=>d);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let d of c){let p=d.depends_on.filter(m=>!u.has(m));if(p.length>0)throw new Error(`Native child ${d.name} depends on unknown child: ${p.join(", ")}`)}XP(c);let f=r.policy==="advisory";if(a===Ef){if(o==="indexed-v2"){let d=QP(n.acceptance_index);f||ZP(d,t,r);let p=Object.keys(d);return f||sw(c,p,p),{schema:Br,acceptance_index:d,children:c}}return{schema:Br,children:c}}return t&&!f&&sw(c,t),{schema:hi,children:c}}async function Fe(e){let t=zP.join(e.changeDir,Sf);try{await WP.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await Q({root:e.changeDir,ref:Sf}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=fw(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?dw(a,e.acceptanceIds,e.validation??{}):null}}var uw,Sf,hi,Br,Ef,JP,aw,GP,UP,KP,YP,Pc=A(()=>{"use strict";uw=br(rr(),1);nt();Sf="children.yaml",hi="comet.native.children.v1",Br="comet.native.children.v2",Ef=Br,JP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,aw=new Set(["schema","children"]),GP=new Set(["schema","acceptance_index","children"]),UP=new Set(["name","depends_on","covers"]),KP=new Set(["name","summary","depends_on"]),YP=new Set(["name","depends_on","covers"])});function ee(e,t,r,i=""){let n=Object.keys(e),a=t.filter(s=>!Object.hasOwn(e,s)),o=n.filter(s=>!t.includes(s));if(a.length||o.length)throw new qa({code:"invalid-fields",path:i,context:r,missingFields:a,unknownFields:o,expectedFields:[...t]})}var qa,_c=A(()=>{"use strict";qa=class extends Error{issues;constructor(t){let r=[t.missingFields.length?`missing: ${t.missingFields.join(", ")}`:"",t.unknownFields.length?`unknown: ${t.unknownFields.join(", ")}`:""].filter(Boolean).join("; ");super(`${t.context} fields are invalid at ${t.path||"/"} (${r})`),this.name="NativeInputValidationError",this.issues=[t]}}});function xf(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function Cf(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){xf(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:Ne,executionRef:xf(t.executionRef,"Native execution ref"),[pw]:!0});return e.add(r),r},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:xf(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[hw]:!0})}})}function Ac(e){return typeof e=="object"&&e!==null&&e[hw]===!0}function mw(e){return typeof e=="object"&&e!==null&&e[pw]===!0}var pw,hw,Ne,mi=A(()=>{"use strict";pw=Symbol("comet.native.trusted-execution-identity"),hw=Symbol("comet.native.trusted-verifier-envelope"),Ne="skill-coordinated"});function Ic(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Fa(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function vi(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function Tc(e,t="/acceptance"){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((r,i)=>{let n=Ic(r,`Native Verifier acceptance ${i}`);ee(n,["id","result","reason"],`Native Verifier acceptance ${i}`,`${t}/${i}`);let a=vi(n.id,`Native Verifier acceptance ${i} ID`);if(!["passed","failed","blocked"].includes(String(n.result)))throw new Error(`Native Verifier acceptance ${a} result is invalid`);return{id:a,result:n.result,reason:vi(n.reason,`Native Verifier acceptance ${a} reason`)}})}function e_(e,t){let r=Ic(e,"Native Verifier final result");if(ee(r,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result",t),!["pass","fail","blocked"].includes(String(r.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(r.risks)||!r.risks.every(i=>typeof i=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:Fa(r.iteration,"Native Verifier iteration"),attempt:Fa(r.attempt,"Native Verifier attempt"),verdict:r.verdict,acceptance:Tc(r.acceptance,`${t}/acceptance`),risks:r.risks,summary:vi(r.summary,"Native Verifier summary")}}function t_(e,t,r){let i=Ic(e,`Native Verifier check request ${t}`);if(ee(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`,`${r}/${t}`),!Array.isArray(i.argv)||!i.argv.every(a=>typeof a=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let n=Fa(i.timeoutMs,`Native Verifier check request ${t} timeout`);if(n<1)throw new Error("Native Verifier check timeout must be positive");return{id:vi(i.id,`Native Verifier check request ${t} ID`),name:vi(i.name,`Native Verifier check request ${t} name`),executable:vi(i.executable,`Native Verifier check request ${t} executable`),argv:i.argv,cwdRef:vi(i.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:n,repeatable:i.repeatable}}function Va(e,t=""){let r=Ic(e,"Native Verifier response");if(r.kind==="final-result")return ee(r,["kind","result"],"Native Verifier response",t),{kind:"final-result",result:e_(r.result,`${t}/result`)};if(r.kind==="request-checks"){if(ee(r,["kind","iteration","attempt","checks"],"Native Verifier response",t),!Array.isArray(r.checks)||r.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:Fa(r.iteration,"Native Verifier iteration"),attempt:Fa(r.attempt,"Native Verifier attempt"),checks:r.checks.map((i,n)=>t_(i,n,`${t}/checks`))}}throw new Error("Native Verifier response kind is invalid")}function vw(e){if(!Ac(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:r}=e;if(t.candidateId!==r.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==r.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===r.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let i=Va(t.payload),n=i.kind==="final-result"?i.result.iteration:i.iteration,a=i.kind==="final-result"?i.result.attempt:i.attempt;if(n!==r.iteration||a!==r.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");if(i.kind==="request-checks")return i;let o=Rf(i.result,r);return{...i,result:{...i.result,acceptance:o}}}function Rf(e,t){Tc(e.acceptance);let r=[...t.acceptanceIds],i=new Set(t.knownAcceptanceIds??r),n=new Set(t.previouslyPassedAcceptanceIds??[]),a=r.filter(h=>!i.has(h)),o=[...n].filter(h=>!i.has(h));if(a.length>0||o.length>0)throw new Error("Native Verifier acceptance binding is internally inconsistent");let s=new Set(r),c=e.acceptance.map(({id:h})=>h),l=c.filter((h,g)=>c.indexOf(h)!==g),u=c.filter(h=>!i.has(h)),f=r.filter(h=>!c.includes(h)),d=e.acceptance.filter(({id:h,result:g})=>s.has(h)||!i.has(h)?!1:!n.has(h)||g!=="passed").map(({id:h,result:g})=>`${h}=${g}`);if(l.length>0||u.length>0||f.length>0||d.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(l)].join(", ")||"none"}; unknown: ${u.join(", ")||"none"}; missing: ${f.join(", ")||"none"}; out-of-scope: ${d.join(", ")||"none"}). Return each required scope ID exactly once and no other acceptance IDs.`);let p=e.acceptance.filter(({id:h})=>s.has(h));if(!t.requiredChecksPassed&&e.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let m=p.map(({result:h})=>h);if(e.verdict==="pass"&&m.some(h=>h!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(e.verdict==="fail"&&!m.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(e.verdict==="blocked"&&!m.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return p}var Ma=A(()=>{"use strict";_c();mi()});function ft(e,t){if(!r_.test(e))throw new Error(`${t} must be a Git commit`)}function Ve(e){return structuredClone(e)}function Ue(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function i_(e,t){if(!Pf(t.dependsOn,e.children)){let r=t.dependsOn.filter(i=>e.children.find(({name:n})=>n===i)?.status!=="integrated");throw new Error(`Native Supervisor child ${t.name} dependency ${r[0]??"?"} is not integrated`)}}function Pf(e,t){let r=new Map(t.map(({name:i,status:n})=>[i,n]));return e.every(i=>r.get(i)==="integrated")}function gw(e){let t=new Set(e.children.map(({name:i})=>i)),r=[];for(;t.size>0;){let i=e.children.find(n=>t.has(n.name)&&n.dependsOn.every(a=>!t.has(a)));if(!i)throw new Error("Native Supervisor Child dependencies contain a cycle");r.push(i),t.delete(i.name)}return r}function Ja(e){ft(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:Wa(e.contract,i.name),contractHash:T("comet.native.supervisor-contract.v1",e.contract),builderFailureCount:0}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:za,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function Wa(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}function _f(e){let t=Ve(e.state),r=new Map(e.contract.children.map(n=>[n.name,n])),i=new Map(t.children.map(n=>[n.name,n]));for(let n of t.children){let a=r.get(n.name);if(!a){if(n.status!=="archived")throw new Error(`Native Supervisor child ${n.name} cannot be removed before Archive`);continue}if((n.status==="integrated"||n.status==="archived")&&(a.summary!==n.summary||a.depends_on.join("\0")!==n.dependsOn.join("\0")))throw new Error(`Native Supervisor integrated child ${n.name} history is immutable`);n.summary=a.summary,n.dependsOn=[...a.depends_on];let o=Wa(e.contract,n.name),s=T("comet.native.supervisor-contract.v1",e.contract);n.contractHash&&n.contractHash!==s&&n.status!=="integrated"&&n.status!=="archived"&&(n.task=null,n.verifiedCommit=null,n.verification=null,n.checks=[],n.candidateCommit?(n.status="needs-reverify",n.blocker="Confirmed Supervisor contract changed; verify the current acceptance scope again."):Pf(n.dependsOn,t.children)?(n.status="ready",n.blocker="Confirmed Supervisor contract changed; verify the current acceptance scope again."):(n.status="pending",n.blocker=null)),n.acceptanceScope=o,n.contractHash=s,n.builderFailureCount??=0}for(let n of e.contract.children)i.has(n.name)||t.children.push({name:n.name,summary:n.summary,dependsOn:[...n.depends_on],status:n.depends_on.every(a=>t.children.some(({name:o,status:s})=>o===a&&s==="integrated"))?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:Wa(e.contract,n.name),contractHash:T("comet.native.supervisor-contract.v1",e.contract),builderFailureCount:0});return t.stateVersion+=1,t}function Lr(e,t,r){let i={child:e.child,runId:e.runId},n=(e.checkExecution?.checkStates??[]).filter(({status:o})=>o==="interrupted").map(({id:o})=>o),a=e.role==="builder"?[{kind:"supervisor-builder-result",...i,candidateCommit:"<candidate-commit>"},{kind:"supervisor-builder-failure",...i,reason:"<failure-reason>"}]:[{kind:"supervisor-checks",...i,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],materials:[],...n.length>0?{retry_check_ids:n}:{}},{kind:"supervisor-verifier-result",...i,verdict:"blocked",evidence:{summary:"<verification-summary>",checks:[],acceptance:(e.acceptance??[]).map(({id:o})=>({id:o,result:"blocked",reason:"<evidence>"})),receiptRef:e.checkExecution?.receiptRef??null}}];return{...e,controlProjectRoot:r,returnAction:{cwd:r,commandArgs:["comet","native","next",t,"--runner-input","<temporary-json-file>","--json"],inputOptions:a.map(o=>({name:o.kind,exclusiveGroup:"runner-input",template:o}))}}}function Ga(e,t){if(!t.projectRoot.trim()||!t.runId.trim())throw new Error("Native Supervisor task projectRoot and runId are required");let r=Ve(e),i=r.children.find(({name:o})=>o===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.task)throw new Error(`Native Supervisor child ${t.child} already has an active task`);let n;if(t.role==="builder"){if(i.status!=="ready")throw new Error(`Native Supervisor child ${t.child} is not ready for a Builder task`);i_(r,i),n=r.integration.headCommit,i.status="active"}else{if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for a Verifier task`);n=i.candidateCommit}let a={...t,baseCommit:n,acceptance:i.acceptanceScope??[{id:`child:${i.name}`,source:"children.yaml",text:i.summary??i.name}],contractHash:i.contractHash,verificationBoundary:"child-scope-parent-reverifies-all",checksReason:"not-run"};return i.projectRoot=t.projectRoot,i.task=a,i.blocker=null,Ue(r,{kind:"task-dispatched",child:i.name,runId:a.runId,summary:`${a.role} task dispatched`}),r.stateVersion+=1,{state:r,task:a}}function ww(e,t){let r=e.children.find(({name:i})=>i===t.child);if(!r?.task||r.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return structuredClone(r.task)}function Af(e,t){let r=ww(e,t),i=Ve(e);return Ue(i,{kind:"task-reconnected",child:t.child,runId:t.runId,summary:"existing task reconnected"}),i.stateVersion+=1,{state:i,task:r}}function jc(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor cancellation reason is required");let r=Ve(e),i=r.children.find(({name:a})=>a===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);let n=i.task.role;return n==="builder"?(i.builderFailureCount=(i.builderFailureCount??0)+1,i.status=i.builderFailureCount>=cr?"blocked":"ready",i.candidateCommit=null):i.status="needs-reverify",i.task=null,i.blocker=n==="builder"&&(i.builderFailureCount??0)>=cr?`Builder failed ${i.builderFailureCount} times; explicit Builder retry is required. Last failure: ${t.reason}`:t.reason,Ue(r,{kind:"task-cancelled",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function Ua(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor blocker reason is required");let r=Ve(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.blocker=t.reason,Ue(r,{kind:"task-blocked",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function If(e,t){ft(t.candidateCommit,"Native Supervisor candidate commit");let r=Ve(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="builder"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Builder result runId is not current for ${t.child}`);if(i.status!=="active")throw new Error(`Native Supervisor child ${t.child} is not active for Builder result`);return i.candidateCommit=t.candidateCommit,i.builderFailureCount=0,i.task=null,i.blocker=null,Ue(r,{kind:"builder-result",child:i.name,runId:t.runId,summary:"Builder candidate recorded"}),r.stateVersion+=1,r}function Tf(e,t){if(t.evidence.summary.trim().length===0)throw new Error("Native Supervisor verification summary must not be empty");if(t.verdict==="pass"&&t.evidence.checks.length===0)throw new Error("Native Supervisor verification pass requires at least one check");let r=Ve(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="verifier"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Verifier result runId is not current for ${t.child}`);if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for Verifier result`);return Rf({verdict:t.verdict,acceptance:t.evidence.acceptance??[]},{acceptanceIds:i.task.acceptance?.map(({id:n})=>n)??i.acceptanceScope?.map(({id:n})=>n)??[`child:${i.name}`],requiredChecksPassed:t.evidence.checks.length>0}),i.verification={...structuredClone(t.evidence)},i.task=null,t.verdict==="pass"?(i.status="verified",i.verifiedCommit=i.candidateCommit,i.blocker=null):(t.verdict==="fail"?(i.status="ready",i.candidateCommit=null,i.verifiedCommit=null,i.verification=null,i.checks=[]):i.status="needs-reverify",i.blocker=t.evidence.summary),Ue(r,{kind:"verifier-result",child:i.name,runId:t.runId,summary:t.evidence.summary}),r.stateVersion+=1,r}function jf(e,t){if(!Number.isSafeInteger(t.expectedStateVersion)||t.expectedStateVersion<1)throw new Error("Native Supervisor Builder retry state version is invalid");if(e.stateVersion!==t.expectedStateVersion)throw new Error("Native Supervisor Builder retry input is stale");let r=Ve(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.status!=="blocked"||i.task!==null||(i.builderFailureCount??0)<cr)throw new Error(`Native Supervisor child ${t.child} is not waiting for an explicit Builder retry`);if(!Pf(i.dependsOn,r.children))throw new Error(`Native Supervisor child ${t.child} dependencies are not integrated`);return i.status="ready",i.candidateCommit=null,i.blocker=null,i.builderFailureCount=0,Ue(r,{kind:"task-cancelled",child:i.name,runId:null,summary:"Explicit Builder retry authorized after the failure budget was exhausted"}),r.stateVersion+=1,r}function $c(e,t){ft(t.integrationCommit,"Native Supervisor integration commit");let r=Ve(e),i=r.children.find(({name:n})=>n===t.name);if(!i)throw new Error(`Native Supervisor child ${t.name} does not exist`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${t.name} must be verified before integration`);if(t.checks.length===0||t.checks.some(({status:n})=>n!=="passed"))throw new Error(`Native Supervisor child ${t.name} integration checks are incomplete`);i.status="integrated",i.integrationCommit=t.integrationCommit,i.checks=structuredClone(t.checks),i.blocker=null,r.integration.headCommit=t.integrationCommit,Ue(r,{kind:"child-integrated",child:i.name,runId:null,summary:"Child integrated into the Supervisor branch"});for(let n of r.children)n.status==="pending"&&n.dependsOn.every(a=>r.children.some(({name:o,status:s})=>o===a&&s==="integrated"))&&(n.status="ready");return r.stateVersion+=1,r}function Oc(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:(i.status==="ready"||i.status==="active")&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing",builderFailureCount:i.builderFailureCount??0}));return{contractHash:null,supervisorStateVersion:e.stateVersion,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var r_,za,cr,gi=A(()=>{"use strict";fe();Ma();r_=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;za="comet.native.supervisor.v2",cr=3});import Ka from"node:path";import{promises as Nw}from"node:fs";function $f(e,t){return Ka.join(pe(e,t),"supervisor")}function wi(e,t){return Ka.join($f(e,t),"state.json")}function bw(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==za)throw new Error(`Native Supervisor state schema must be ${za}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if(ft(t.integration.targetCommit,"Native Supervisor target commit"),ft(t.integration.headCommit,"Native Supervisor integration head commit"),t.integration.checkExecution){let n=t.integration.checkExecution;if(!n.operationId||!n.key||!n.child||!["running","completed","interrupted"].includes(n.status)||!Number.isSafeInteger(n.ownerPid)||n.ownerPid<=0)throw new Error("Native Supervisor integration check execution is invalid");ft(n.candidateCommit,"Native Supervisor integration candidate commit"),ft(n.integrationCommit,"Native Supervisor integration check commit"),yw(n.checkStates,"Native Supervisor integration")}if(!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.builderFailureCount!==void 0&&(!Number.isSafeInteger(n.builderFailureCount)||n.builderFailureCount<0))throw new Error(`Native Supervisor child ${n.name} Builder failure count is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&ft(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if(ft(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.checkExecution&&yw(n.task.checkExecution.checkStates,`Native Supervisor child ${n.name}`),n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function O(e,t,r={}){try{let i=await Nw.readFile(wi(e,t),"utf8"),n=JSON.parse(i);if(bw(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativePortableState:s}=await Promise.resolve().then(()=>(ut(),kf)),c=await s(Ka.join(o.changesDir,t,"comet-state.yaml")),l=await Fe({changeDir:Ka.join(o.changesDir,t),acceptanceIds:c.acceptance.map(({id:u})=>u),validation:dt(c)});if(!l)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let u of n.children)l.contract.children.some(({name:f})=>f===u.name)&&(u.acceptanceScope=Wa(l.contract,u.name),u.contractHash=T("comet.native.supervisor-contract.v1",l.contract),u.task&&(u.task.acceptance=structuredClone(u.acceptanceScope),u.task.contractHash=u.contractHash,u.task.verificationBoundary="child-scope-parent-reverifies-all",u.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=e;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(ut(),kf)),s=await o(Ka.join(a.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(n.integration.targetBranch=s.workspace.change_branch)}catch(o){if(o.code!=="ENOENT")throw o}return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Hc(e,t){let r=await n_(e,t);if(r.length>0)throw new Error(`Native Supervisor Git binding cannot change while active child tasks exist: ${r.join(", ")}`)}async function n_(e,t){return(await O(e,t,{diagnostics:!0}))?.children.filter(({task:i})=>i!==null).map(({name:i})=>i)??[]}async function q(e,t){bw(t),await Nw.mkdir(e.changesRuntimeDir,{recursive:!0}),await we(wi(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function yw(e,t){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)throw new Error(`${t} check states are invalid`);let r=new Set;for(let i of e){if(!i||typeof i.id!="string"||!i.id||r.has(i.id)||typeof i.name!="string"||!["planned","running","passed","failed","interrupted"].includes(i.status)||typeof i.repeatable!="boolean"||!Number.isSafeInteger(i.executionCount)||i.executionCount<0||!Array.isArray(i.argvDisplay)||!i.argvDisplay.every(n=>typeof n=="string")||typeof i.cwdRef!="string"||!Number.isSafeInteger(i.durationMs)||i.durationMs<0||i.exitCode!==null&&!Number.isSafeInteger(i.exitCode)||i.signal!==null&&typeof i.signal!="string"||typeof i.timedOut!="boolean"||i.startedAt!==null&&typeof i.startedAt!="string"||i.completedAt!==null&&typeof i.completedAt!="string"||i.logRef!==null&&typeof i.logRef!="string")throw new Error(`${t} check state is invalid`);r.add(i.id)}}var lr=A(()=>{"use strict";ne();fe();Pc();te();gi()});import{spawn as Of}from"node:child_process";import{existsSync as kw}from"node:fs";import yi from"node:path";function Hf(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function l_(e){let t=(Hf(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function u_(e,t,r){let n=yi.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Hf(t,"PATH")??"").split(yi.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=yi.win32.extname(e)?[e]:l_(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?yi.join(s,c):yi.resolve(r,c)))}function fn(e,t,r){return u_(e,t,r).find(i=>kw(i))??e}function d_(e){let t=Hf(e,"SystemRoot");if(t){let r=yi.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(kw(r))return r}return"powershell.exe"}function Ya(e){if(e.some(t=>s_.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function f_(e,t,r){let i=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(c_,"utf16le").toString("base64");return Of(d_(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 Df(e,t,r){let i=r.env??process.env;if(process.platform!=="win32")return Of(e,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=fn(e,i,r.cwd),a=yi.win32.extname(n).toLowerCase();return o_.has(a)&&Ya(t),a_.has(a)?f_(n,t,{cwd:r.cwd,env:i}):Of(n,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}var a_,o_,s_,c_,Dc=A(()=>{"use strict";a_=new Set([".bat",".cmd",".ps1"]),o_=new Set([".bat",".cmd"]),s_=/[&|<>()^%"!\r\n]/u,c_=["$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 p_}from"node:child_process";import Sw from"node:path";function v_(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}function pn(e,t,r={}){let i=r.timeoutMs??h_,n=r.maxBufferBytes??m_;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=Sw.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?fn(e,o,a):e,c=Sw.win32.extname(s).toLowerCase(),l=c===".bat"||c===".cmd";process.platform==="win32"&&l&&Ya(t);try{return p_(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 f=typeof u.stderr=="string"?u.stderr.trim():Buffer.isBuffer(u.stderr)?u.stderr.toString("utf8").trim():"";throw new Bf(e,t,f,{cause:u,timedOut:v_(u)})}}var h_,m_,Bf,Bc=A(()=>{"use strict";Dc();h_=6e4,m_=8*1024*1024,Bf=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 Ew}from"node:fs";import xw from"node:path";function y_(e){let t=qf.get(e);if(!t)return;let r=t.value===null?w_:g_;if(Date.now()-t.at>r){qf.delete(e);return}return t.value}async function Ke(e){if(e===process.pid&&Lf!==null)return Lf;let t=y_(e);if(t!==void 0)return t;let r=await N_(e);return e===process.pid&&r!==null&&(Lf=r),e!==process.pid&&qf.set(e,{value:r,at:Date.now()}),r}async function N_(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([Ew.readFile(`/proc/${e}/stat`,"utf8"),Ew.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 k_(e);if(process.platform==="darwin"){let t=pn("/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 b_(e){let t=e.trim();return/^\d+$/u.test(t)?`win32-ps:${t}`:null}async function k_(e){try{let n=pn(xw.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=xw.win32.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),i=pn(r,["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:8e3,maxBufferBytes:4096}).trim();return b_(i)}function Lc(e){let t=e.indexOf(":");return t===-1?"":e.slice(0,t)}async function hn(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 Ke(e);return r===t?"alive":r===null||Lc(r)!==Lc(t)&&Cw.has(Lc(r))&&Cw.has(Lc(t))?"unknown":"dead"}async function mn(e,t){return await hn(e,t)!=="dead"}var Lf,g_,w_,qf,Cw,Xa=A(()=>{"use strict";Bc();Lf=null,g_=6e4,w_=1e4,qf=new Map;Cw=new Set(["win32-wmic","win32-ps"])});import{spawn as S_}from"node:child_process";import Ff from"node:path";async function Qa(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,i=r&&Ff.win32.isAbsolute(r)?Ff.win32.resolve(r):"C:\\Windows",n=Ff.win32.join(i,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,u=(f,d=!1)=>{s||(s=!0,l&&clearTimeout(l),d&&c?.kill("SIGKILL"),o(f))};try{c=S_(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>u(!1)),c.once("close",f=>u(f===0)),l=setTimeout(()=>u(!1,!0),E_)}catch{u(!1)}});for(let o=0;o<x_;o+=1)if(await a()){e.kill("SIGKILL");return}e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy();return}try{process.kill(-t,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}var E_,x_,Vf=A(()=>{"use strict";E_=1e3,x_=2});function Me(e){return e.replace(C_,"$1 [REDACTED]").replace(R_,"[REDACTED PRIVATE KEY]").replace(P_,"$1[REDACTED]@").replace(__,"[REDACTED TOKEN]").replace(A_,'$1"[REDACTED]"').replace(I_,"$1$2$1$3$4[REDACTED]$4").replace(T_,"$1$2[REDACTED]")}var C_,R_,P_,__,A_,I_,T_,qr=A(()=>{"use strict";C_=/\b(Bearer|Basic)\s+[^\s"']+/giu,R_=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,P_=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,__=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,A_=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,I_=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,T_=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu});import{accessSync as j_,constants as $_,createWriteStream as O_,existsSync as Mf,promises as H_,statSync as D_}from"node:fs";import me from"node:path";function Pw(e,t){let r=me.relative(e,t);return r===""||!me.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${me.sep}`)}function _w(e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(e))throw new Error(`${t} is invalid`);return e}function Za(e,t){if(t.length===0||t.includes("\\")||me.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||me.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=me.resolve(e),i=me.resolve(r,...t.split("/"));if(!Pw(r,i))throw new Error("Native check cwd escaped the project root");let n;try{n=D_(i)}catch(a){throw new Error(`Native check cwd does not exist: ${t}`,{cause:a})}if(!n.isDirectory())throw new Error(`Native check cwd is not a directory: ${t}`);return i}function vn(e){return JSON.stringify([e.executable,e.argv,e.cwdRef.replaceAll("\\","/"),e.timeoutMs,e.repeatable])}function Rw(e,t){return me.isAbsolute(e)||/[\\/]/u.test(e)?[me.resolve(t,e)]:(process.env.PATH??"").split(me.delimiter).map(r=>r.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean).map(r=>me.join(r,e))}function B_(e,t){if(process.platform==="win32"){let i=fn(e,process.env,t),n=me.win32.isAbsolute(i)?i:Rw(e,t).find(a=>Mf(a));if(!n||!Mf(n))throw new Error(`executable is not available: ${e}`);return[".bat",".cmd"].includes(me.win32.extname(n).toLowerCase()),void 0}let r=Rw(e,t).find(i=>Mf(i));if(!r)throw new Error(`executable is not available: ${e}`);try{j_(r,$_.X_OK)}catch(i){throw new Error(`executable is not executable: ${e}`,{cause:i})}}function Ye(e,t){let r=new Set;t.forEach((i,n)=>{if(r.has(i.id))throw new Error(`Native check plan duplicate ID ${i.id} at /checks/${n}/id`);r.add(i.id);let a;try{if(a=to(e,i),process.platform==="win32"){let o=fn(i.executable,process.env,a),s=me.win32.extname(o).toLowerCase();(s===".bat"||s===".cmd")&&Ya(i.argv)}B_(i.executable,a)}catch(o){throw new Error(`Native check ${i.id} is invalid at /checks/${n}: ${o.message}`,{cause:o})}})}function eo(e){let t=!1;return e.map(r=>{if(t)return t=!1,"[REDACTED]";let i=Me(r);return L_.test(r)&&(t=!0),i})}function to(e,t){if(_w(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return Za(e,t.cwdRef)}async function Ni(e){let{plan:t}=e;_w(e.operationId,"Native check operation ID");let r=to(e.projectRoot,t),i=me.join(e.runtimeDir,"logs","checks"),n=me.join(i,`${e.operationId}-${t.id}.log`);if(!Pw(me.resolve(e.runtimeDir),me.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await H_.mkdir(i,{recursive:!0});let a=(e.now??(()=>new Date))(),o=O_(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=Df(t.executable,t.argv,{cwd:r,env:process.env})}catch(g){o.destroy(),c(g);return}let u=!1,f=null,d=null,p=Promise.resolve(),m=!1,h=setTimeout(()=>{u=!0,Qa(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);if(h.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",g=>{f=g,o.write(`
|
|
176
176
|
[comet] failed to start check: ${Me(g.message)}
|
|
177
177
|
`)}),l.once("close",(g,v)=>{m=!0,clearTimeout(h);let w=(e.now??(()=>new Date))();p.then(()=>{if(d!==null){o.destroy(),c(d);return}o.end(()=>{let y=u||f!==null||v!==null;s({id:t.id,name:t.name,argvDisplay:eo(t.argv),cwdRef:t.cwdRef,status:y?"interrupted":g===0?"passed":"failed",exitCode:g,signal:v,timedOut:u,durationMs:Math.max(0,w.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:w.toISOString(),repeatable:t.repeatable,logRef:me.relative(e.runtimeDir,n).split(me.sep).join("/")})})})}),o.once("error",g=>{clearTimeout(h),d??=g,m?p.then(()=>c(d)):Qa(l).catch(()=>l.kill("SIGKILL"))}),l.pid!==void 0&&e.onSpawn){let g=l.pid;p=Promise.resolve().then(()=>e.onSpawn({pid:g})).catch(async v=>{d=v,l.exitCode===null&&l.signalCode===null&&await Qa(l).catch(()=>l.kill("SIGKILL"))})}})}var L_,gn=A(()=>{"use strict";Dc();Vf();qr();L_=/^(?:-p|-u|--(?:[a-z0-9]+[-_])*(?:api[-_]?key|access[-_]?token|auth[-_]?token|client[-_]?secret|secret(?:[-_]?access)?[-_]?key|private[-_]?key|token|password|passwd|secret|authorization|cookie|set[-_]?cookie|user))$/iu});import{AsyncLocalStorage as q_}from"async_hooks";import{randomUUID as Tw}from"crypto";import{promises as pt}from"fs";import jw from"os";import oe from"path";function M_(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function W_(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 $w(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 Fc(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return wt(r,i)?Z(r,i):Z(r,i)&&e.size===t.size}function Vc(e,t){return Fc(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function z_(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&&Vc(e.identity,t.identity)}async function St(e){let t,r;try{let i=await en(e,Aw,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof bt?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${Aw} 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:W_(JSON.parse(t.toString("utf8")),e),identity:$w(r)}}async function J_(e){return(await St(e))?.owner??null}async function zf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==jw.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=await hn(e.owner.pid,e.owner.processIdentity);return{status:t==="alive"?"active":t==="dead"?"stale":"unknown",owner:e.owner,identity:e.identity}}async function G_(e,t){try{await pt.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await pt.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Mc(e,t){let r=await St(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Vc(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await pt.mkdir(t,{recursive:!0});let i=oe.join(t,`${oe.basename(e.file)}.${e.owner.id}.${Tw()}.removed`);try{await pt.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await St(i);if(!n||n.owner.id!==e.owner.id||!Fc(n.identity,e.identity))throw await G_(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await pt.rm(i,{force:!0}),"removed"}async function Ow(e){let t=await Ke(process.pid);return{id:Tw(),pid:process.pid,hostname:jw.hostname(),createdAt:new Date().toISOString(),operation:e,...t===null?{}:{processIdentity:t}}}async function Hw(e,t){let r;try{r=await pt.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await J_(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)+`
|
|
@@ -206,17 +206,17 @@ ${tc(t)}`).digest("hex")}var fe=A(()=>{"use strict"});import jr from"path";funct
|
|
|
206
206
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
207
207
|
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=sy(l,t);else if(r)cy(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let f=sy(l,null);if(f!==null)t=f;else{let d=l.trimStart();if(d.startsWith("<!--")&&!cy(d))r=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(d);p&&n.has(p[1].toLowerCase())&&!d.startsWith("</")&&!d.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(d)&&(i=p[1])}}}if(c===-1)break;o=c+1}}function lo(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function uy(e,t,r,i=[],n="content-hash"){let a=lo(r),o=t.replaceAll("\\","/").trim(),s=i.map(lo);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${T(RA,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function dy(e,t,r="content-hash"){let i=new Set;for(let n of e){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(a)}return e}function PA(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of Zc(e)){n=s+1;let c=o?ly(a):null;c?.level===1&&(Xc(c.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function op(e,t="brief.md",r=el.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=PA(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:f}of Zc(e)){if(f<n.start||f>=n.end)continue;let d=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(d===null)continue;let p=d[1].length;a=a===null?p:Math.min(a,p)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:f}of Zc(e)){if(f<n.start||f>=n.end)continue;let d=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;d&&d[1].length===a?(c(),s=[d[2]]):s!==null&&s.push(l)}return c(),dy(o.map(l=>uy("brief-example",t,l.join(`
|
|
208
208
|
`),[],i)),"Brief",i)}function sp(e,t="spec.md",r=el.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(uy("spec-scenario",t,[o.title,...o.body].join(`
|
|
209
|
-
`),o.context,i)),o=null}};for(let{line:c,body:l}of Zc(e)){let u=l?ly(c):null,f=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(f){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let d=lo(f[1]);if(d.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:d,body:[],context:a.map(p=>p.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),dy(n,"Specification",i)}var RA,gL,el,tl=A(()=>{"use strict";xi();fe();RA="comet.native.acceptance.v1",gL=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),el=Object.freeze({maxCriteria:1024})});import fy from"node:path";function py(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||fy.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||fy.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function AA(e,t){return e.localeCompare(t,"en")}function rl(e){let t=py(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>AA(a.capability,o.capability));if(new Set(r.map(a=>a.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=op(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=py(a.source,`Native spec source for ${a.capability}`);i.push(...sp(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of i){a.text=lo(a.text);let o=a.text;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function hy(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!_A.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function my(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var _A,il=A(()=>{"use strict";tl();_A=/^A[1-9]\d*$/u});function IA(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function J(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(IA(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var Fr=A(()=>{"use strict"});import TA from"node:path";function BA(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function LA(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function qA(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function FA(e){return e.schema===Ft?yn(e):e.schema===qt?Nn(e):Ei(e)}function VA(e){return TA.posix.normalize(e.replaceAll("\\","/"))}function MA(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:VA(t.source)})}function WA(e){return e==="shape"?"shape":"build"}function zA(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function JA(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function vy(e){let t=FA(e.state);hy(e.acceptance);let r=WA(t.phase),i=r==="shape"?0:1,n=LA(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return B({schema:fi,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:MA(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:zA(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:J(JA(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:bc(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function cp(e){let t=BA(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!jA.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==nl)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!OA.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!$A.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!DA.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!HA.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:nl,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:qA(t.createdAt,"Native portable migration transaction createdAt")}}function gy(e){switch(cp(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var nl,jA,$A,OA,HA,DA,lp=A(()=>{"use strict";Yc();il();ut();Fr();cn();no();nl="comet.native.portable-migration.v1",jA=new Set(["schema","id","change","fromSchema","status","createdAt"]),$A=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,OA=/^[a-z0-9][a-z0-9-]{7,127}$/u,HA=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),DA=new Set([Ft,qt,Lt])});import dp from"node:path";function ky(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Sy(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 up(e,t){if(e!==void 0){if(e===null)return null;if(typeof e!="string"||!/^[a-f0-9]{64}$/iu.test(e))throw new Error(`${t} must be a SHA-256 hash or null`);return e.toLowerCase()}}function yy(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function eI(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=ky(e,r);if(Sy(i,ZA,r),typeof i.capability!="string"||!by.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation,a=i.delta_source;if(a!==void 0&&(typeof a!="string"||a.length===0||a.includes("\\")||a.startsWith("/")||/^[A-Za-z]:/u.test(a)||a.split("/").some(d=>d==="."||d==="..")))throw new Error(`${r}.delta_source is invalid`);let o=up(i.base_hash,`${r}.base_hash`),s=yy(i.delta_content,`${r}.delta_content`),c=yy(i.source_content,`${r}.source_content`),l=up(i.expected_target_hash,`${r}.expected_target_hash`),u=up(i.result_hash,`${r}.result_hash`),f=a!==void 0;if(f&&o==null)throw new Error(`${r}.delta_source requires a non-null base_hash`);if(f&&(s==null||c===void 0||c===null||u===void 0||u===null))throw new Error(`${r}.delta_source requires delta_content, source_content, and result_hash`);if(!f&&(s!==void 0||c!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(f){let d=io(s);if(d.capability!==i.capability)throw new Error(`${r}.delta_content capability does not match capability`);if(d.base_hash!==o)throw new Error(`${r}.delta_content base_hash does not match base_hash`);if(ur(i.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(ur(c)!==u)throw new Error(`${r}.source_content does not match result_hash`)}if(n==="remove"){if(i.source!==null||i.content!==null||a!==void 0||s!==void 0||c!==void 0||u!==void 0)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null,...o===void 0?{}:{base_hash:o},...l===void 0?{}:{expected_target_hash:l}}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(d=>d==="."||d===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);if(u!==void 0&&(u===null||ur(i.content)!==u))throw new Error(`${r}.content does not match result_hash`);return{capability:i.capability,operation:n,source:i.source,content:i.content,...a===void 0?{}:{delta_source:a},...o===void 0?{}:{base_hash:o},...s===void 0?{}:{delta_content:s},...c===void 0?{}:{source_content:c},...l===void 0?{}:{expected_target_hash:l},...u===void 0?{}:{result_hash:u}}}function tI(e){let t=ky(e,"Native portable Archive transaction");if(Sy(t,QA,"Native portable Archive transaction"),t.schema!==wy)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!KA.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!by.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!YA.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!XA.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(eI);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:wy,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function al(e){let t=GA.exec(e);if(t)return{kind:"archive",change:t[1]};let r=UA.exec(e);return r?{kind:"migration",change:r[1]}:null}function ol(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=al(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return dp.join(e.transactionsDir,r)}async function fp(e,t){let r=al(t);if(!r)return null;let i=await Q({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=dp.join(e.transactionsDir,t);if(r.kind==="archive"){let s=tI(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=cp(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function sl(e,t){let r=ol(e,t);try{return await fp(e,dp.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function Ey(e){return e.kind==="archive"||e.journal.status!=="committed"}var wy,Ny,GA,UA,KA,YA,XA,QA,ZA,by,cl=A(()=>{"use strict";nt();Zf();lp();wy="comet.native.archive-transaction.v4",Ny="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",GA=new RegExp(`^portable-archive-(${Ny})\\.json$`,"u"),UA=new RegExp(`^portable-migration-(${Ny})\\.json$`,"u"),KA=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,YA=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,XA=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),QA=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),ZA=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),by=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as rI}from"node:crypto";import{constants as ll,promises as Et}from"node:fs";import xt from"node:path";function dl(e,t){let r=xt.relative(e,t);return r===""||!xt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${xt.sep}`)}function iI(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function nI(e,t){return Z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function aI(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ul(e,t){return Z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function pp(e,t){let r=await Et.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Et.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function oI(e,t,r){let i=xt.resolve(e),n=xt.resolve(t);if(!dl(i,n))throw new Error(`${r} is outside its managed root`);let a=[await pp(i,r)],o=i;for(let s of xt.relative(i,n).split(xt.sep).filter(Boolean)){await Ci(a,r),o=xt.join(o,s);let c=await pp(o,r);if(!dl(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Ci(a,r),a}async function Ci(e,t){for(let r of e){let i=await Et.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!nI(r,i)||await Et.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function sI(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(t===null?64*1024:Math.min(64*1024,t+1));for(;;){let o=t===null?a.length:t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,t!==null&&n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function uo(e){let t=e.maxBytes===null?null:iI(e.maxBytes),r=xt.resolve(e.file),i=await oI(e.root,xt.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>pp(xt.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Ci(i,e.label);let a=await Et.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(t!==null&&a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=aI(a),s=await Et.realpath(r);if(!dl(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>dl(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?ll.O_RDONLY:ll.O_RDONLY|ll.O_NOFOLLOW|ll.O_NONBLOCK,l=await Et.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[f,d]=await Promise.all([Et.lstat(r),Et.realpath(r)]);if(await Ci(i,e.label),await Ci(n,e.label),!u.isFile()||!f.isFile()||f.isSymbolicLink()||d!==s||!ul(o,u)||!ul(o,f))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await sI(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,g]=await Promise.all([l.stat(),Et.lstat(r),Et.realpath(r)]);if(await Ci(i,e.label),await Ci(n,e.label),!h.isFile()||h.isSymbolicLink()||g!==s||!ul(o,m)||!ul(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:rI("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}var Mt=A(()=>{"use strict";ne();Dt()});import pr from"path";import{TextDecoder as lI}from"util";function pl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function hl(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 Py(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function hp(e,t){if(typeof e!="string"||e.length===0||pr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function fl(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function xy(e,t){if(hp(e,t),e.includes("\\")||e!==pr.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function mI(e,t){let r=pl(e,`transaction operations[${t}]`);if(hl(r,dI,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);hp(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&hp(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function _y(e){let t=pl(e,"Native Archive transaction journal");if(hl(t,fI,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!Ry.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!Py(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(fl(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=pl(s,`Archive transaction operations[${c}]`);if(hl(l,pI,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);xy(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&xy(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&fl(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(fl(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);fl(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function vI(e){let t=pl(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return _y(t);if(hl(t,uI,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!Ry.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!pr.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!pr.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!Py(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(mI),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function gI(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return pr.join(e.transactionsDir,t)}function Ay(e,t){let r=gI(e,t);return{directory:r,journal:pr.join(r,"transaction.json"),events:pr.join(r,"events.jsonl"),staged:pr.join(r,"staged"),backups:pr.join(r,"backups")}}async function vp(e,t){let r=Ay(e,t);return await Promise.all(Object.values(r).map(i=>z(e.runtimeDir,i))),r}async function gp(e,t,r={}){let i=await vp(e,t),n=await uo({root:e.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(hI.decode(n.bytes)),o=vI(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var uI,dI,fI,pI,Ry,hI,ml=A(()=>{"use strict";ne();te();Mt();uI=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),dI=new Set(["id","type","source","target","staged","backup"]),fI=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),pI=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),Ry=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),hI=new lI("utf-8",{fatal:!0})});import{promises as wI}from"fs";import yI from"path";async function NI(e,t,r){let i;try{i=await wI.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await gp(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(al(n.name))try{let a=await fp(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Ey(a))return!0}catch{return!0}return!1}async function bI(e,t){let r=Date.now()+5e3,i=yI.join(e.locksDir,"root-move.lock");for(;;)try{return await zc(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Lw(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await qw(e,i,o);if(s.status==="removed"||s.status==="missing")continue;throw n}if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function _(e,t,r,i){let n=await bI(e,t);try{if(await wc(e.projectRoot),await NI(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await Jc(n)}catch(a){process.stderr.write(`[comet] warning: could not release Native mutation lock ${n.file} (${a.message}); run comet native doctor --repair if commands start failing
|
|
209
|
+
`),o.context,i)),o=null}};for(let{line:c,body:l}of Zc(e)){let u=l?ly(c):null,f=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(f){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let d=lo(f[1]);if(d.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:d,body:[],context:a.map(p=>p.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),dy(n,"Specification",i)}var RA,wL,el,tl=A(()=>{"use strict";xi();fe();RA="comet.native.acceptance.v1",wL=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),el=Object.freeze({maxCriteria:1024})});import fy from"node:path";function py(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||fy.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||fy.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function AA(e,t){return e.localeCompare(t,"en")}function rl(e){let t=py(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>AA(a.capability,o.capability));if(new Set(r.map(a=>a.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=op(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=py(a.source,`Native spec source for ${a.capability}`);i.push(...sp(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of i){a.text=lo(a.text);let o=a.text;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function hy(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!_A.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function my(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var _A,il=A(()=>{"use strict";tl();_A=/^A[1-9]\d*$/u});function IA(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function J(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(IA(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var Fr=A(()=>{"use strict"});import TA from"node:path";function BA(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function LA(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function qA(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function FA(e){return e.schema===Ft?yn(e):e.schema===qt?Nn(e):Ei(e)}function VA(e){return TA.posix.normalize(e.replaceAll("\\","/"))}function MA(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:VA(t.source)})}function WA(e){return e==="shape"?"shape":"build"}function zA(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function JA(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function vy(e){let t=FA(e.state);hy(e.acceptance);let r=WA(t.phase),i=r==="shape"?0:1,n=LA(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return B({schema:fi,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:MA(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:zA(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:J(JA(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:bc(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function cp(e){let t=BA(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!jA.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==nl)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!OA.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!$A.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!DA.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!HA.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:nl,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:qA(t.createdAt,"Native portable migration transaction createdAt")}}function gy(e){switch(cp(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var nl,jA,$A,OA,HA,DA,lp=A(()=>{"use strict";Yc();il();ut();Fr();cn();no();nl="comet.native.portable-migration.v1",jA=new Set(["schema","id","change","fromSchema","status","createdAt"]),$A=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,OA=/^[a-z0-9][a-z0-9-]{7,127}$/u,HA=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),DA=new Set([Ft,qt,Lt])});import dp from"node:path";function ky(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Sy(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 up(e,t){if(e!==void 0){if(e===null)return null;if(typeof e!="string"||!/^[a-f0-9]{64}$/iu.test(e))throw new Error(`${t} must be a SHA-256 hash or null`);return e.toLowerCase()}}function yy(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function eI(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=ky(e,r);if(Sy(i,ZA,r),typeof i.capability!="string"||!by.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation,a=i.delta_source;if(a!==void 0&&(typeof a!="string"||a.length===0||a.includes("\\")||a.startsWith("/")||/^[A-Za-z]:/u.test(a)||a.split("/").some(d=>d==="."||d==="..")))throw new Error(`${r}.delta_source is invalid`);let o=up(i.base_hash,`${r}.base_hash`),s=yy(i.delta_content,`${r}.delta_content`),c=yy(i.source_content,`${r}.source_content`),l=up(i.expected_target_hash,`${r}.expected_target_hash`),u=up(i.result_hash,`${r}.result_hash`),f=a!==void 0;if(f&&o==null)throw new Error(`${r}.delta_source requires a non-null base_hash`);if(f&&(s==null||c===void 0||c===null||u===void 0||u===null))throw new Error(`${r}.delta_source requires delta_content, source_content, and result_hash`);if(!f&&(s!==void 0||c!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(f){let d=io(s);if(d.capability!==i.capability)throw new Error(`${r}.delta_content capability does not match capability`);if(d.base_hash!==o)throw new Error(`${r}.delta_content base_hash does not match base_hash`);if(ur(i.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(ur(c)!==u)throw new Error(`${r}.source_content does not match result_hash`)}if(n==="remove"){if(i.source!==null||i.content!==null||a!==void 0||s!==void 0||c!==void 0||u!==void 0)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null,...o===void 0?{}:{base_hash:o},...l===void 0?{}:{expected_target_hash:l}}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(d=>d==="."||d===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);if(u!==void 0&&(u===null||ur(i.content)!==u))throw new Error(`${r}.content does not match result_hash`);return{capability:i.capability,operation:n,source:i.source,content:i.content,...a===void 0?{}:{delta_source:a},...o===void 0?{}:{base_hash:o},...s===void 0?{}:{delta_content:s},...c===void 0?{}:{source_content:c},...l===void 0?{}:{expected_target_hash:l},...u===void 0?{}:{result_hash:u}}}function tI(e){let t=ky(e,"Native portable Archive transaction");if(Sy(t,QA,"Native portable Archive transaction"),t.schema!==wy)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!KA.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!by.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!YA.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!XA.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(eI);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:wy,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function al(e){let t=GA.exec(e);if(t)return{kind:"archive",change:t[1]};let r=UA.exec(e);return r?{kind:"migration",change:r[1]}:null}function ol(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=al(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return dp.join(e.transactionsDir,r)}async function fp(e,t){let r=al(t);if(!r)return null;let i=await Q({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=dp.join(e.transactionsDir,t);if(r.kind==="archive"){let s=tI(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=cp(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function sl(e,t){let r=ol(e,t);try{return await fp(e,dp.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function Ey(e){return e.kind==="archive"||e.journal.status!=="committed"}var wy,Ny,GA,UA,KA,YA,XA,QA,ZA,by,cl=A(()=>{"use strict";nt();Zf();lp();wy="comet.native.archive-transaction.v4",Ny="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",GA=new RegExp(`^portable-archive-(${Ny})\\.json$`,"u"),UA=new RegExp(`^portable-migration-(${Ny})\\.json$`,"u"),KA=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,YA=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,XA=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),QA=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),ZA=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),by=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as rI}from"node:crypto";import{constants as ll,promises as Et}from"node:fs";import xt from"node:path";function dl(e,t){let r=xt.relative(e,t);return r===""||!xt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${xt.sep}`)}function iI(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function nI(e,t){return Z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function aI(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ul(e,t){return Z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function pp(e,t){let r=await Et.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Et.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function oI(e,t,r){let i=xt.resolve(e),n=xt.resolve(t);if(!dl(i,n))throw new Error(`${r} is outside its managed root`);let a=[await pp(i,r)],o=i;for(let s of xt.relative(i,n).split(xt.sep).filter(Boolean)){await Ci(a,r),o=xt.join(o,s);let c=await pp(o,r);if(!dl(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Ci(a,r),a}async function Ci(e,t){for(let r of e){let i=await Et.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!nI(r,i)||await Et.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function sI(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(t===null?64*1024:Math.min(64*1024,t+1));for(;;){let o=t===null?a.length:t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,t!==null&&n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function uo(e){let t=e.maxBytes===null?null:iI(e.maxBytes),r=xt.resolve(e.file),i=await oI(e.root,xt.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>pp(xt.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Ci(i,e.label);let a=await Et.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(t!==null&&a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=aI(a),s=await Et.realpath(r);if(!dl(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>dl(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?ll.O_RDONLY:ll.O_RDONLY|ll.O_NOFOLLOW|ll.O_NONBLOCK,l=await Et.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[f,d]=await Promise.all([Et.lstat(r),Et.realpath(r)]);if(await Ci(i,e.label),await Ci(n,e.label),!u.isFile()||!f.isFile()||f.isSymbolicLink()||d!==s||!ul(o,u)||!ul(o,f))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await sI(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,g]=await Promise.all([l.stat(),Et.lstat(r),Et.realpath(r)]);if(await Ci(i,e.label),await Ci(n,e.label),!h.isFile()||h.isSymbolicLink()||g!==s||!ul(o,m)||!ul(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:rI("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}var Mt=A(()=>{"use strict";ne();Dt()});import pr from"path";import{TextDecoder as lI}from"util";function pl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function hl(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 Py(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function hp(e,t){if(typeof e!="string"||e.length===0||pr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function fl(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function xy(e,t){if(hp(e,t),e.includes("\\")||e!==pr.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function mI(e,t){let r=pl(e,`transaction operations[${t}]`);if(hl(r,dI,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);hp(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&hp(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function _y(e){let t=pl(e,"Native Archive transaction journal");if(hl(t,fI,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!Ry.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!Py(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(fl(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=pl(s,`Archive transaction operations[${c}]`);if(hl(l,pI,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);xy(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&xy(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&fl(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(fl(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);fl(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function vI(e){let t=pl(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return _y(t);if(hl(t,uI,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!Ry.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!pr.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!pr.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!Py(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(mI),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function gI(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return pr.join(e.transactionsDir,t)}function Ay(e,t){let r=gI(e,t);return{directory:r,journal:pr.join(r,"transaction.json"),events:pr.join(r,"events.jsonl"),staged:pr.join(r,"staged"),backups:pr.join(r,"backups")}}async function vp(e,t){let r=Ay(e,t);return await Promise.all(Object.values(r).map(i=>z(e.runtimeDir,i))),r}async function gp(e,t,r={}){let i=await vp(e,t),n=await uo({root:e.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(hI.decode(n.bytes)),o=vI(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var uI,dI,fI,pI,Ry,hI,ml=A(()=>{"use strict";ne();te();Mt();uI=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),dI=new Set(["id","type","source","target","staged","backup"]),fI=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),pI=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),Ry=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),hI=new lI("utf-8",{fatal:!0})});import{promises as wI}from"fs";import yI from"path";async function NI(e,t,r){let i;try{i=await wI.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await gp(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(al(n.name))try{let a=await fp(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Ey(a))return!0}catch{return!0}return!1}async function bI(e,t){let r=Date.now()+5e3,i=yI.join(e.locksDir,"root-move.lock");for(;;)try{return await zc(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Lw(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await qw(e,i,o);if(s.status==="removed"||s.status==="missing")continue;throw n}if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function _(e,t,r,i){let n=await bI(e,t);try{if(await wc(e.projectRoot),await NI(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await Jc(n)}catch(a){process.stderr.write(`[comet] warning: could not release Native mutation lock ${n.file} (${a.message}); run comet native doctor --repair if commands start failing
|
|
210
210
|
`)}}}var le=A(()=>{"use strict";st();ro();cl();ml()});import{createHash as kI}from"node:crypto";import{promises as wp}from"node:fs";import Iy from"node:os";import Ct from"node:path";function bn(e){return{id:e.id,name:e.name,status:"planned",repeatable:e.repeatable,executionCount:0,argvDisplay:eo(e.argv),cwdRef:e.cwdRef,exitCode:null,signal:null,timedOut:!1,durationMs:0,startedAt:null,completedAt:null,logRef:null}}function vl(e,t){return{...e,name:t.name,status:t.status,argvDisplay:[...t.argvDisplay],cwdRef:t.cwdRef,exitCode:t.exitCode,signal:t.signal,timedOut:t.timedOut,durationMs:t.durationMs,startedAt:t.startedAt,completedAt:t.completedAt,logRef:t.logRef}}function gl(e){if(e.status!=="passed"&&e.status!=="failed"&&e.status!=="interrupted"||e.startedAt===null||e.completedAt===null||e.logRef===null)throw new Error(`Native Supervisor check ${e.id} has incomplete Runtime evidence`);return{id:e.id,name:e.name,argvDisplay:[...e.argvDisplay],cwdRef:e.cwdRef,status:e.status,exitCode:e.exitCode,signal:e.signal,timedOut:e.timedOut,durationMs:e.durationMs,startedAt:e.startedAt,completedAt:e.completedAt,repeatable:e.repeatable,logRef:e.logRef}}function SI(e,t){let r=Ct.relative(Ct.resolve(e),Ct.resolve(t));return r===""||!Ct.isAbsolute(r)&&!r.startsWith(`..${Ct.sep}`)}function Wt(e,t){try{return I(e,t)}catch(r){return`unavailable:${r instanceof Error?r.message:String(r)}`}}async function Ty(e){let t=Wt(e,["ls-files","--others","--exclude-standard","-z"]);return t===null||t.startsWith("unavailable:")?[{error:t}]:Promise.all(t.split("\0").filter(Boolean).sort().map(async r=>{let i=r.replaceAll("\\","/"),n=Ct.resolve(e,...i.split("/"));if(!SI(e,n))return{path:i,error:"escaped"};try{let a=await wp.lstat(n);if(a.isSymbolicLink())return{path:i,kind:"symlink",target:await wp.readlink(n)};if(!a.isFile())return{path:i,kind:"other",size:a.size};let o=await wp.readFile(n);return{path:i,kind:"file",size:a.size,digest:kI("sha256").update(o).digest("hex")}}catch(a){return{path:i,error:a instanceof Error?a.message:String(a)}}}))}async function EI(e){let t=Wt(e,["ls-files","--stage","-z"]);if(t===null||t.startsWith("unavailable:"))return[{error:t}];let r=t.split("\0").map(i=>/^160000\s+[^\s]+\s+\d+\t(.+)$/u.exec(i)?.[1]).filter(i=>i!==void 0).sort();return Promise.all(r.map(async i=>({path:i.replaceAll("\\","/"),head:Wt(Ct.resolve(e,i),["rev-parse","HEAD"]),status:Wt(Ct.resolve(e,i),["status","--porcelain=v1","-z","--untracked-files=all"]),diff:Wt(Ct.resolve(e,i),["diff","--binary","HEAD","--submodule=diff"]),untracked:await Ty(Ct.resolve(e,i))})))}async function wl(e){let t=Object.entries(process.env).map(([r,i])=>[r,i??null]).sort(([r],[i])=>r.localeCompare(i));return T("comet.native.supervisor-check-input.v2",{kind:e.kind,parent:e.parent,child:e.child,runId:e.runId,projectRoot:Ct.resolve(e.projectRoot),candidateCommit:e.candidateCommit,integrationCommit:e.integrationCommit??null,contractHash:e.contractHash??null,plans:e.plans,materials:e.materials,machineId:Iy.hostname(),runtime:{execPath:process.execPath,version:process.version,platform:process.platform,arch:process.arch,environment:t},git:{head:Wt(e.projectRoot,["rev-parse","HEAD"]),branch:Wt(e.projectRoot,["branch","--show-current"]),status:Wt(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none"]),diff:Wt(e.projectRoot,["diff","--binary","HEAD","--submodule=diff"]),stagedDiff:Wt(e.projectRoot,["diff","--cached","--binary","--submodule=diff"]),submodules:await EI(e.projectRoot),untracked:await Ty(e.projectRoot)}})}function yl(){return Iy.hostname()}var yp=A(()=>{"use strict";rt();gn();fe()});import{createHash as xI}from"node:crypto";import{lstatSync as CI,readFileSync as jy,promises as $y}from"node:fs";import Nl from"node:path";function Dy(e){try{if(I(e,["ls-files","--",bl]))return!1;let t=Nl.join(e,bl),r=CI(t);return!r.isFile()||r.isSymbolicLink()?!1:JSON.parse(jy(Oy(e),"utf8")).hash===Hy(jy(t))}catch{return!1}}async function By(e){let t=Nl.join(e,bl),r;try{r=await $y.readFile(t)}catch(n){if(n.code==="ENOENT")return;throw n}let i=Oy(e);await $y.mkdir(Nl.dirname(i),{recursive:!0}),await we(i,{hash:Hy(r)},{containedRoot:e})}function zt(e,t=[]){return ka(e).every(r=>t.some(i=>r===i||r.startsWith(`${i}/`))||r===bl&&Dy(e))}var bl,Oy,Hy,kn=A(()=>{"use strict";rt();ne();bl=".comet/config.yaml",Oy=e=>Nl.join(e,".comet","runtime","native","workspace-config.json"),Hy=e=>xI("sha256").update(e).digest("hex")});import{createHash as AI}from"crypto";function Xe(e){return AI("sha256").update(e).digest("hex")}var Jt=A(()=>{"use strict"});import Vy from"path";function Sl(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function KI(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function YI(e,t){return Xe(`comet.native.snapshot-policy.v1
|
|
211
|
-
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function bp(e,t,r){let i=new Set(t),n=[...t];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function XI(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function My(e){let t=gc(e,"Native snapshot pattern"),r=[];for(let i=0;i<t.length;i+=1){let n=t[i];n==="*"&&t[i+1]==="*"?(i+=1,t[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?XI(n):void 0;if(a&&!a())return!1;let o=bp(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=r[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=bp(r,c,a),o===null||o.size===0)return!1}return bp(r,o,a)?.has(r.length)??!1}}function QI(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>gc(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>gc(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let i=YI(t,r);if("hash"in e&&e.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:r,hash:i},includeMatchers:t.map(My),excludeMatchers:r.map(My),excludedDirectoryPrefixes:r.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function ht(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function mt(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function En(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Gt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Jy(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let r=Vy.posix.normalize(e);if(r!==e||Vy.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function ZI(e,t){let r=ht(e,`Native snapshot entry ${t}`);mt(r,VI,`Native snapshot entry ${t}`);let i=Jy(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!El.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:Gt(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!UI.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function eT(e,t){let r=ht(e,`Native snapshot omission ${t}`);if(mt(r,MI,`Native snapshot omission ${t}`),!JI.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!GI.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Jy(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:Gt(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function tT(e){let t=ht(e,"Native snapshot omission overflow");if(mt(t,WI,"Native snapshot omission overflow"),typeof t.hash!="string"||!El.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:En(t.count,"Native snapshot omission overflow count")}}function Sn(e,t){let r=ht(e,t);if(mt(r,LI,t),typeof r.hash!="string"||!El.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=Gt(r.recordCount,`${t} recordCount`),n=Gt(r.storedRecordCount,`${t} storedRecordCount`),a=Gt(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function Wy(e){let t=ht(e,"Native Git selection evidence");if(mt(t,BI,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=Sn(t.stageBefore,"Native Git selection stageBefore"),i=Sn(t.combined,"Native Git selection combined"),n=Sn(t.stageAfter,"Native Git selection stageAfter"),a=Sn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Sn(t.finalCombined,"Native Git selection finalCombined"),s=Sn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(f=>f.overflow),l=!Sl(r,n)||!Sl(n,a)||!Sl(i,o)||!Sl(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function zy(e,t){let r=ht(e,t);if(mt(r,FI,t),typeof r.hash!="string"||!El.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=Gt(r.visitedNodeCount,`${t} visitedNodeCount`),n=Gt(r.recordCount,`${t} recordCount`),a=Gt(r.storedRecordCount,`${t} storedRecordCount`),o=Gt(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function rT(e){let t=ht(e,"Native physical selection evidence");if(mt(t,qI,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=zy(t.before,"Native physical selection before"),i=zy(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!KI(r,i);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:r,after:i}}function kp(e){let t=ht(e,"Native content snapshot manifest");if(mt(t,jI,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!zI.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let N=ht(t.capture,"Native content snapshot capture");if(mt(N,HI,"Native content snapshot capture"),N.provider!=="git"&&N.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let x=N.gitSelection===void 0?void 0:Wy(N.gitSelection),k=N.physicalSelection===void 0?void 0:rT(N.physicalSelection),E=null;if(N.projection!==void 0){let C=ht(N.projection,"Native content snapshot projection");if(mt(C,DI,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");E={provider:"git",...C.selection===void 0?{}:{selection:Wy(C.selection)}}}if(N.provider==="git"){if(k||E)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...x?{gitSelection:x}:{}}}else{if(x)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(k&&E)throw new Error("Native physical-tree capture cannot combine selection and projection");r=E?{provider:"physical-tree",projection:E}:{provider:"physical-tree",...k?{physicalSelection:k}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let i=ht(t.limits,"Native content snapshot limits");mt(i,$I,"Native content snapshot limits");let n={maxFiles:En(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:En(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:En(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:En(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:En(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let N=ht(t.policy,"Native snapshot policy");if(mt(N,OI,"Native snapshot policy"),N.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(N.include)||!Array.isArray(N.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=QI({include:N.include,exclude:N.exclude,hash:N.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(ZI),s=t.omitted.map(eT),c=Gt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:tT(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(N=>N.size>n.maxFileBytes)||o.reduce((N,x)=>N+x.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(N=>N.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>TI||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let f=s.filter(N=>N.reason==="git-enumeration-limit"),d=s.filter(N=>N.reason==="git-selection-changed");for(let N of[...f,...d])if(N.path!=="."||N.size!==null||N.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(f.length>1||d.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=r?.provider==="git"?r.gitSelection:r?.projection?.selection,m=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(m!==(f.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(d.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let g=s.filter(N=>N.reason==="physical-enumeration-limit"),v=s.filter(N=>N.reason==="physical-selection-changed");for(let N of[...g,...v])if(N.path!=="."||N.size!==null||N.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(g.length>1||v.length>1)throw new Error("Native physical selection omissions must not be duplicated");let w=r?.physicalSelection,y=w?.status==="overflow"||w?.status==="overflow-and-changed",b=w?.status==="changed"||w?.status==="overflow-and-changed";if(y!==(g.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(b!==(v.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");return{schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}}}var Bq,TI,jI,$I,OI,HI,DI,BI,LI,qI,FI,VI,MI,WI,zI,JI,GI,El,UI,Lq,qq,Fq,Vq,Mq,po=A(()=>{"use strict";ne();st();Jt();Dt();te();Mt();Sa();Bq={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},TI=1e3,jI=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),$I=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),OI=new Set(["schema","include","exclude","hash"]),HI=new Set(["provider","gitSelection","physicalSelection","projection"]),DI=new Set(["provider","selection"]),BI=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),LI=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),qI=new Set(["schema","status","before","after"]),FI=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),VI=new Set(["path","hash","size","type","gitObjectId"]),MI=new Set(["path","size","type","reason"]),WI=new Set(["ref","hash","count"]),zI=new Set(["change-created","legacy-migration","explicit"]),JI=new Set(["file","directory","other"]),GI=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),El=/^[a-f0-9]{64}$/u,UI=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Lq=64*1024,qq=64*1024,Fq={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},Vq={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};Mq=(1n<<256n)-1n});import{createHash as eN}from"node:crypto";import Gy from"path";function Re(e,t){return e<t?-1:e>t?1:0}function Ep(e){if(!Cp.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function cT(e,t){return e===t?0:e===null?-1:t===null?1:Re(e,t)}function Wr(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let r=Gy.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||Gy.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function iN(e,t){return e==="."?e:Wr(e,t)}function xn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function lT(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:Wr(e.path,`${t} path`),hash:e.hash,size:xn(e.size,`${t} size`),type:"file"}}function uT(e,t){return{path:iN(e.path,`${t} path`),size:e.size===null?null:xn(e.size,`${t} size`),type:e.type,reason:e.reason}}function dT(e,t){return Re(e.path,t.path)||Re(e.hash,t.hash)||e.size-t.size}function fT(e,t){return Re(e.path,t.path)||Re(e.reason,t.reason)||Re(e.type,t.type)||(e.size??-1)-(t.size??-1)}function vo(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
211
|
+
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function bp(e,t,r){let i=new Set(t),n=[...t];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function XI(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function My(e){let t=gc(e,"Native snapshot pattern"),r=[];for(let i=0;i<t.length;i+=1){let n=t[i];n==="*"&&t[i+1]==="*"?(i+=1,t[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?XI(n):void 0;if(a&&!a())return!1;let o=bp(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=r[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=bp(r,c,a),o===null||o.size===0)return!1}return bp(r,o,a)?.has(r.length)??!1}}function QI(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>gc(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>gc(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let i=YI(t,r);if("hash"in e&&e.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:r,hash:i},includeMatchers:t.map(My),excludeMatchers:r.map(My),excludedDirectoryPrefixes:r.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function ht(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function mt(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function En(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Gt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Jy(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let r=Vy.posix.normalize(e);if(r!==e||Vy.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function ZI(e,t){let r=ht(e,`Native snapshot entry ${t}`);mt(r,VI,`Native snapshot entry ${t}`);let i=Jy(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!El.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:Gt(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!UI.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function eT(e,t){let r=ht(e,`Native snapshot omission ${t}`);if(mt(r,MI,`Native snapshot omission ${t}`),!JI.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!GI.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Jy(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:Gt(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function tT(e){let t=ht(e,"Native snapshot omission overflow");if(mt(t,WI,"Native snapshot omission overflow"),typeof t.hash!="string"||!El.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:En(t.count,"Native snapshot omission overflow count")}}function Sn(e,t){let r=ht(e,t);if(mt(r,LI,t),typeof r.hash!="string"||!El.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=Gt(r.recordCount,`${t} recordCount`),n=Gt(r.storedRecordCount,`${t} storedRecordCount`),a=Gt(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function Wy(e){let t=ht(e,"Native Git selection evidence");if(mt(t,BI,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=Sn(t.stageBefore,"Native Git selection stageBefore"),i=Sn(t.combined,"Native Git selection combined"),n=Sn(t.stageAfter,"Native Git selection stageAfter"),a=Sn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Sn(t.finalCombined,"Native Git selection finalCombined"),s=Sn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(f=>f.overflow),l=!Sl(r,n)||!Sl(n,a)||!Sl(i,o)||!Sl(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function zy(e,t){let r=ht(e,t);if(mt(r,FI,t),typeof r.hash!="string"||!El.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=Gt(r.visitedNodeCount,`${t} visitedNodeCount`),n=Gt(r.recordCount,`${t} recordCount`),a=Gt(r.storedRecordCount,`${t} storedRecordCount`),o=Gt(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function rT(e){let t=ht(e,"Native physical selection evidence");if(mt(t,qI,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=zy(t.before,"Native physical selection before"),i=zy(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!KI(r,i);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:r,after:i}}function kp(e){let t=ht(e,"Native content snapshot manifest");if(mt(t,jI,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!zI.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let N=ht(t.capture,"Native content snapshot capture");if(mt(N,HI,"Native content snapshot capture"),N.provider!=="git"&&N.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let x=N.gitSelection===void 0?void 0:Wy(N.gitSelection),k=N.physicalSelection===void 0?void 0:rT(N.physicalSelection),E=null;if(N.projection!==void 0){let C=ht(N.projection,"Native content snapshot projection");if(mt(C,DI,"Native content snapshot projection"),C.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");E={provider:"git",...C.selection===void 0?{}:{selection:Wy(C.selection)}}}if(N.provider==="git"){if(k||E)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...x?{gitSelection:x}:{}}}else{if(x)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(k&&E)throw new Error("Native physical-tree capture cannot combine selection and projection");r=E?{provider:"physical-tree",projection:E}:{provider:"physical-tree",...k?{physicalSelection:k}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let i=ht(t.limits,"Native content snapshot limits");mt(i,$I,"Native content snapshot limits");let n={maxFiles:En(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:En(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:En(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:En(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:En(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let N=ht(t.policy,"Native snapshot policy");if(mt(N,OI,"Native snapshot policy"),N.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(N.include)||!Array.isArray(N.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=QI({include:N.include,exclude:N.exclude,hash:N.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(ZI),s=t.omitted.map(eT),c=Gt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:tT(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(N=>N.size>n.maxFileBytes)||o.reduce((N,x)=>N+x.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(N=>N.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>TI||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let f=s.filter(N=>N.reason==="git-enumeration-limit"),d=s.filter(N=>N.reason==="git-selection-changed");for(let N of[...f,...d])if(N.path!=="."||N.size!==null||N.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(f.length>1||d.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=r?.provider==="git"?r.gitSelection:r?.projection?.selection,m=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(m!==(f.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(d.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let g=s.filter(N=>N.reason==="physical-enumeration-limit"),v=s.filter(N=>N.reason==="physical-selection-changed");for(let N of[...g,...v])if(N.path!=="."||N.size!==null||N.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(g.length>1||v.length>1)throw new Error("Native physical selection omissions must not be duplicated");let w=r?.physicalSelection,y=w?.status==="overflow"||w?.status==="overflow-and-changed",b=w?.status==="changed"||w?.status==="overflow-and-changed";if(y!==(g.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(b!==(v.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");return{schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}}}var Lq,TI,jI,$I,OI,HI,DI,BI,LI,qI,FI,VI,MI,WI,zI,JI,GI,El,UI,qq,Fq,Vq,Mq,Wq,po=A(()=>{"use strict";ne();st();Jt();Dt();te();Mt();Sa();Lq={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},TI=1e3,jI=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),$I=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),OI=new Set(["schema","include","exclude","hash"]),HI=new Set(["provider","gitSelection","physicalSelection","projection"]),DI=new Set(["provider","selection"]),BI=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),LI=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),qI=new Set(["schema","status","before","after"]),FI=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),VI=new Set(["path","hash","size","type","gitObjectId"]),MI=new Set(["path","size","type","reason"]),WI=new Set(["ref","hash","count"]),zI=new Set(["change-created","legacy-migration","explicit"]),JI=new Set(["file","directory","other"]),GI=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),El=/^[a-f0-9]{64}$/u,UI=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,qq=64*1024,Fq=64*1024,Vq={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},Mq={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};Wq=(1n<<256n)-1n});import{createHash as eN}from"node:crypto";import Gy from"path";function Re(e,t){return e<t?-1:e>t?1:0}function Ep(e){if(!Cp.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function cT(e,t){return e===t?0:e===null?-1:t===null?1:Re(e,t)}function Wr(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let r=Gy.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||Gy.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function iN(e,t){return e==="."?e:Wr(e,t)}function xn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function lT(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:Wr(e.path,`${t} path`),hash:e.hash,size:xn(e.size,`${t} size`),type:"file"}}function uT(e,t){return{path:iN(e.path,`${t} path`),size:e.size===null?null:xn(e.size,`${t} size`),type:e.type,reason:e.reason}}function dT(e,t){return Re(e.path,t.path)||Re(e.hash,t.hash)||e.size-t.size}function fT(e,t){return Re(e.path,t.path)||Re(e.reason,t.reason)||Re(e.type,t.type)||(e.size??-1)-(t.size??-1)}function vo(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
212
212
|
`,"utf8")}function Mr(e,t,r){let i=`${t}
|
|
213
213
|
${tc(r)}`;e.update(`${Buffer.byteLength(i,"utf8")}:`),e.update(i)}function pT(e){if(vo(e)<=Pi)return e;let t=[...e.entries],r=[...e.omitted],i=e.omittedCount,n=e.omissionOverflow?.count??0,a=eN("sha256");a.update(`${aT}
|
|
214
214
|
`),e.omissionOverflow&&Mr(a,"existing-overflow",e.omissionOverflow);let o=(d,p)=>{p||(i+=1),n+=1,Mr(a,"omission",d)},s=d=>{i+=1,n+=1,Mr(a,"entry",d)},c=()=>{for(let d=r.length-1;d>=0;d-=1){let p=r[d];if(!(p.reason==="git-enumeration-limit"||p.reason==="git-selection-changed"||p.reason==="physical-enumeration-limit"||p.reason==="physical-selection-changed"))return r.splice(d,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(;vo(u)>Pi;){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 m=0;m<p;m+=1){let h=c();if(h===null)break;o(h,!0)}}else if(t.length>0){let p=Math.max(1,Math.ceil(t.length/4));for(let m of t.splice(-p))s(m)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let f=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${f}`,hash:f,count:n}}}function hT(e){let t=kp(e),r=t.entries.map((n,a)=>lT(n,`Snapshot entry ${a}`));if(r.sort(dT),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)=>uT(n,`Snapshot omission ${a}`));return i.sort(fT),pT({schema:tN,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 Cl(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:Wr(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)=>Re(r.path,i.path)||Re(r.kind,i.kind))}function go(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Uy(e){return e?{hash:e.hash,size:e.size}:null}function nN(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:Re(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:Uy(c),after:Uy(l)})}}function mT(e,t){return{...e,attributedTo:t.filter(r=>go(r,e.path))}}function hr(e,t){return{id:`scope:${T(iT,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function vT(e,t){let r=t.omitted.map(i=>hr({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(hr({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&r.push(hr({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 Ky(e,t){return vT(e,{...t,omitted:[]}).filter(r=>r.kind!=="snapshot-omission")}function xp(e,t){return Re(e.kind,t.kind)||Re(e.source,t.source)||cT(e.path,t.path)||Re(e.id,t.id)}function gT(e){return[...new Map(e.map(r=>[r.id,r])).values()].sort(xp)}function aN(e){return[...new Set(e.map((t,r)=>Wr(t,`Git path ${r}`)))].sort(Re)}function Yy(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 wT(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 oN(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=aN(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:Yy(e.baseCommit,"Native external drift base commit"),targetBranch:wT(e.targetBranch,"Native external drift target branch"),targetCommit:Yy(e.targetCommit,"Native external drift target commit"),paths:t}}function yT(e){if(typeof e.contractHash!="string"||!Cp.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:Cl(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:aN(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:oN(e.externalDrift)}}}function NT(e,t,r,i,n){let a=[],o=i===void 0?null:new Set(i),s=[],c=[],l=0,u=!1,f=0,d=0;return nN(e,t,p=>{let m=r.some(h=>go(h,p.path));if(f+=1,c.push(p.path),!m&&!n?.has(p.path)&&(d+=1),o?.has(p.path)&&s.push(p.path),!u&&a.length<oT){let h=mT(p,r),g=vo(h);l+g<=Pi?(a.push(h),l+=g):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:f,totalUnattributed:d}}function sN(e,t){return hr({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 bT(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:xn(Number(t[1]),"Scope overflow change count"),unresolved:xn(Number(t[2]),"Scope overflow unresolved count"),unattributed:xn(Number(t[3]),"Scope overflow unattributed count")},i=Ri(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(sN(i,r)))throw new Error("Implementation scope detail overflow is inconsistent");return{...r,hash:i}}function kT(e){let t=eN("sha256");t.update(`${nT}
|
|
215
|
-
`);let r=0;nN(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){Mr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)go(o,n.path)&&(a+=1,Mr(t,"change-attribution",o));Mr(t,"change-end",{attributionCount:a}),a===0&&Mr(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&&Mr(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function ST(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=NT(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let x=new Set(r.externalDrift.paths),k=new Set(o.changePaths),E=r.externalDrift.paths.filter(C=>!k.has(C)||n.some(H=>go(H,C)));if(E.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${E.slice(0,8).join(", ")}`);if(x.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=T(ho,e),c=T(ho,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[x,k]of[["baseline",e],["current",t]])for(let E of k.omitted){if(l.length>=sT)break;l.push(hr({kind:"snapshot-omission",source:x,path:E.path,evidence:{reason:E.reason,size:E.size,type:E.type}},`${x} snapshot omitted ${E.path}: ${E.reason}`))}let f=e.omitted.length+t.omitted.length,d=[...Ky("baseline",e),...Ky("current",t),...o.totalChanges===0&&a===null?[hr({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 x=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(k=>x.has(k)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(k=>!x.has(k))}},m=x=>{let k=o.candidates.slice(0,x.detailedChangeCount),E=k.filter(Ce=>Ce.attributedTo.length===0&&!u.has(Ce.path)),C=o.totalChanges-k.length,H=o.totalUnattributed-E.length,P=f-x.detailedOmissionCount,W=H+P,ue=[...E.map(Ce=>hr({kind:"unattributed-change",source:"implementation-scope",path:Ce.path,evidence:{after:Ce.after,before:Ce.before,changeKind:Ce.kind}},`Changed path is not covered by a declared artifact: ${Ce.path}`)),...l.slice(0,x.detailedOmissionCount),...d,...W>0?[sN(x.overflowHash,{changes:C,unattributed:H,unresolved:W})]:[]],$t=gT(ue),ri=x.includeGitAdvisory?p():void 0;return{schema:Sp,contractHash:i,baselineProjectionRef:Ep(s),baselineProjectionHash:s,currentProjectionRef:Ep(c),currentProjectionHash:c,complete:$t.length===0,declaredArtifacts:n,changes:k,unattributed:E,unresolvedScopes:$t,noCodeReason:a,...ri?{gitAdvisory:ri}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},h=o.candidates.length,g=l.length,v=r.gitChangedPaths!==void 0,w="0".repeat(64);for(;;){let x=m({detailedChangeCount:h,detailedOmissionCount:g,includeGitAdvisory:v,overflowHash:w});if(vo({...x,scopeHash:w})<=Pi)break;if(v){v=!1;continue}if(g>0){g-=Math.max(1,Math.ceil(g/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let b=o.totalChanges>h||f>g?kT({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:g}):w,S=m({detailedChangeCount:h,detailedOmissionCount:g,includeGitAdvisory:v,overflowHash:b}),N={...S,scopeHash:T(rN,S)};if(vo(N)>Pi)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return N}function Ut(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Kt(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 Ri(e,t){if(typeof e!="string"||!Cp.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Xy(e,t,r){let i=Ep(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function xl(e,t){let r=Ut(e,"Native snapshot projection");if(Kt(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==tN)throw new Error("Native snapshot projection schema is invalid");let i=kp({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=hT(i);if(T(ho,r)!==T(ho,n))throw new Error("Native snapshot projection is not canonical");let a=T(ho,n);if(t!==void 0&&Ri(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Rp(e,t){let r=Ut(e,`Declared artifact ${t}`);if(Kt(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Wr(r.path,`Declared artifact ${t} path`),kind:r.kind}}function Qy(e,t){if(e===null)return null;let r=Ut(e,t);return Kt(r,["hash","size"],[],t),{hash:Ri(r.hash,`${t} hash`),size:xn(r.size,`${t} size`)}}function Zy(e,t){let r=Ut(e,`Implementation change ${t}`);if(Kt(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(Rp),n=Cl(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Qy(r.before,`Implementation change ${t} before`),o=Qy(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:Wr(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function xT(e,t){let r=Ut(e,`Unresolved scope ${t}`);Kt(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"?iN(r.path,`Unresolved scope ${t} path`):Wr(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function mo(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)=>Wr(n,`${t} ${a}`)),i=[...new Set(r)].sort(Re);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function cN(e){let t=Ut(e,"Native implementation external drift");if(Kt(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=mo(t.paths,"Native external drift paths");return oN({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function Rl(e){let t=Ut(e,"Native implementation scope"),r=[...ET].filter(E=>E!=="gitAdvisory"&&E!=="externalDrift");if(Kt(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Sp)throw new Error("Native implementation scope schema is invalid");let i=Ri(t.contractHash,"Implementation scope contractHash"),n=Ri(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Xy(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=Ri(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Xy(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(Rp);if(JSON.stringify(c)!==JSON.stringify(Cl(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Zy),u=[...l].sort((E,C)=>Re(E.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(E=>E.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let f=new Set(c.map(E=>`${E.kind}:${E.path}`));if(l.some(E=>E.attributedTo.some(C=>!f.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(E=>JSON.stringify(E.attributedTo)!==JSON.stringify(c.filter(C=>go(C,E.path)))))throw new Error("Implementation scope change attribution is inconsistent");let d=t.unattributed.map(Zy),p=t.externalDrift===void 0?void 0:cN(t.externalDrift),m=new Set(p?.paths??[]),h=l.filter(E=>E.attributedTo.length===0&&!m.has(E.path));if(JSON.stringify(d)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let g=t.unresolvedScopes.map(xT),v=g.filter(E=>E.kind==="scope-detail-overflow");if(v.length>1)throw new Error("Implementation scope has multiple detail overflow records");let w=v[0]===void 0?null:bT(v[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 y=t.noCodeReason,b=[...h.map(E=>hr({kind:"unattributed-change",source:"implementation-scope",path:E.path,evidence:{after:E.after,before:E.before,changeKind:E.kind}},`Changed path is not covered by a declared artifact: ${E.path}`)),...l.length+(w?.changes??0)===0&&y===null?[hr({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")]:[]],S=g.filter(E=>E.kind==="unattributed-change"||E.kind==="missing-no-code-reason");if(JSON.stringify(g)!==JSON.stringify([...g].sort(xp))||new Set(g.map(E=>E.id)).size!==g.length||JSON.stringify(S)!==JSON.stringify(b.sort(xp))||t.complete!==(g.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 N;if(t.gitAdvisory!==void 0){let E=Ut(t.gitAdvisory,"Implementation scope Git advisory");if(Kt(E,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),E.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=mo(E.changedPaths,"Git changed paths"),H=mo(E.pathsPresentInSnapshotChanges,"Git present paths"),P=mo(E.pathsAbsentFromSnapshotChanges,"Git absent paths"),W=[...H,...P].sort(Re);if(JSON.stringify(W)!==JSON.stringify(C)||P.some(ue=>l.some($t=>$t.path===ue)))throw new Error("Implementation scope Git advisory partition is invalid");N={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:H,pathsAbsentFromSnapshotChanges:P}}let x={schema:Sp,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:d,unresolvedScopes:g,noCodeReason:y,...N?{gitAdvisory:N}:{},...p?{externalDrift:p}:{}},k=Ri(t.scopeHash,"Implementation scope scopeHash");if(T(rN,x)!==k)throw new Error("Implementation scope content hash mismatch");return{...x,scopeHash:k}}function CT(e){let t=Ut(e,"Native implementation scope authority");if(Kt(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(Rp);if(JSON.stringify(r)!==JSON.stringify(Cl(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=mo(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:cN(t.externalDrift),a=yT({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 wo(e){let t=Ut(e,"Native implementation scope bundle");Kt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=CT(t.authority),i=xl(t.baseline),n=xl(t.current),a=Rl(t.scope),o=ST(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 lN(e){let t=Rl(e.scope);return wo({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 Sp,tN,ho,rN,iT,nT,aT,Cp,Pi,oT,sT,ET,Cn=A(()=>{"use strict";fe();po();Sp="comet.native.implementation-scope.v2",tN="comet.native.content-snapshot-projection.v1",ho="comet.native.content-snapshot-projection.v1",rN="comet.native.implementation-scope.v2",iT="comet.native.unresolved-scope-id.v1",nT="comet.native.scope-detail-overflow.v1",aT="comet.native.snapshot-projection-overflow.v2",Cp=/^[a-f0-9]{64}$/u,Pi=1024*1024,oT=128,sT=128;ET=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import uN from"node:path";function mr(e,t){if(!fN.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function pN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function hN(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 Pp(e,t,r=2e3){let i=Me(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function yo(e,t){let r=uN.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})||uN.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 AT(e,t,r){let i=yo(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=Xi(i),a=i.toLowerCase(),o=r?yo(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 _p(e){let t=yo(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 Rn(e,t){return e<t?-1:e>t?1:0}function Pl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function _l(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 mN(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 dN(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 IT(e){let t=Pl(e,"Native acceptance trace");if(_l(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"||!fN.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=yo(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=Pl(o,`Native acceptance trace entry ${s}`);if(_l(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(f=>typeof f!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(f=>_p(f)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Rn))||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:yo(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Pp(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>Rn(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=mr(t.traceHash,"Native acceptance trace hash");if(T(RT,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function vN(e){let t=Pl(e,"Native partial allowance");if(_l(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(Rn))||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:hN(t.change),scopeHash:mr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Pp(t.reason,"Partial allowance reason"),confirmedSummary:Pp(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:pN(t.sourceRevision),confirmedAt:mN(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=mr(t.allowanceHash,"Native partial allowance hash");if(T(PT,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function Ap(e){let t=Pl(e,"Native verification evidence");if(_l(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=mr(t.implementationScopeHash,"Native verification implementation scope hash"),i=IT(t.acceptanceTrace),n=mr(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:mr(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(d=>_p(d));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Rn)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(d=>d.evidenceRefs))].sort(Rn);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(d=>_p(d));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Rn)))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:hN(t.change),sourceRevision:pN(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:mr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:dN(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:AT(t.reportRef,"Native verification report ref"),reportHash:mr(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:dN(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:mN(t.createdAt,"Native verification timestamp")},f=mr(t.envelopeHash,"Native verification envelope hash");if(T(_T,u)!==f)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:f}}var fN,RT,PT,_T,Al=A(()=>{"use strict";fe();qr();Sa();Cn();fN=/^[a-f0-9]{64}$/u,RT="comet.native.acceptance-trace.v2",PT="comet.native.partial-allowance.v1",_T="comet.native.verification-evidence.v2"});var Il,TT,jT,$T,iF,OT,nF,Ip=A(()=>{"use strict";fe();Il="scoped-text-safety",TT=1,jT=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),$T="comet.native.checker-policy.v1",iF=T($T,{policy:Il,version:TT,limits:jT,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),OT=["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"],nF=new Set(OT)});function Pn(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 zr(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 vr(e,t){if(typeof e!="string"||!DT.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Rt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=Me(e).trim();if(!r||r.length>FT||r!==e.trim())throw new Error(`${t} is invalid`);return r}function Tp(e,t){let r=Rt(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 No(e,t,r=Rt,i=!1,n=VT){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 WT(e,t){if(typeof e!="string"||!BT.test(e))throw new Error(`${t} is invalid`);return e}function zT(e){let t=Pn(e,"Native verification receipt bindings");if(zr(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!LT.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:vr(t.contractHash,"Native verification receipt contract hash"),scopeHash:vr(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:vr(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:vr(t.artifactHash,"Native verification receipt artifact hash")}}function JT(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=qT.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function GT(e,t,r,i){let n=Pn(t,`Native ${e} evidence`);if(e==="automated-check"){if(zr(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=Tp(n.startedAt,"Native automated-check start time"),o=Tp(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=Pn(n.worktree,"Native automated-check worktree");if(zr(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=Pn(n.afterFence,"Native automated-check after fence");if(zr(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:Rt(n.executable,"Native automated-check executable"),args:No(n.args,"Native automated-check arguments",Rt,!0),cwd:Rt(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:Rt(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:vr(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:vr(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:vr(n.outputHash,"Native automated-check output hash"),outputSummary:Rt(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){zr(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=JT(n.checkReceiptRef);if(vr(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:No(n.subjects,"Native static inspection subjects",Rt,i==="required-check"),rule:Rt(n.rule,"Native static inspection rule"),resultSummary:Rt(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return zr(n,["steps","observations"],"Native manual-evidence evidence"),{steps:No(n.steps,"Native manual evidence steps"),observations:No(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function UT(e){let t=Pn(e,"Native verification receipt");if(zr(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=Rt(t.actor,"Native verification receipt actor"),o=No(t.acceptanceIds,"Native receipt acceptance IDs",WT,i==="required-check",MT).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:jp,kind:r,role:i,status:n,bindings:zT(t.bindings),acceptanceIds:o,actor:a,issuedAt:Tp(t.issuedAt,"Native verification receipt issue time"),evidence:GT(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Il||s.actor!==`native-runtime:${Il}`))throw new Error("Native required check policy identity is invalid");return s}function $p(e){let t=Pn(e,"Native verification receipt");if(zr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==jp)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=UT(i),a=vr(t.receiptHash,"Native verification receipt hash");if(T(HT,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}var jp,HT,DT,BT,LT,qT,FT,VT,MT,Tl=A(()=>{"use strict";fe();Ip();qr();jp="comet.native.verification-receipt.v3",HT=jp,DT=/^[a-f0-9]{64}$/u,BT=/^acceptance-[a-f0-9]{64}$/u,LT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,qT=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,FT=4096,VT=256,MT=1024});var RN={};du(RN,{MAX_NATIVE_EVIDENCE_DOCUMENT_BYTES:()=>Yt,MAX_NATIVE_IMPLEMENTATION_SCOPE_BUNDLE_BYTES:()=>KT,listNativeVerificationReceiptRefs:()=>xN,nativeEvidenceRef:()=>Jr,nativeReportEvidenceRef:()=>ZT,readArchivedNativeVerificationAcceptanceCounts:()=>oj,readNativeImplementationScope:()=>Eo,readNativeImplementationScopeBundle:()=>$l,readNativePartialAllowance:()=>Lp,readNativeVerificationEvidence:()=>qp,readNativeVerificationReceipt:()=>Ol,readNativeVerificationReportSnapshot:()=>So,removeNativeVerificationReportSnapshot:()=>kN,writeNativeImplementationScope:()=>nj,writeNativePartialAllowance:()=>aj,writeNativeVerificationEvidence:()=>CN,writeNativeVerificationReceipt:()=>EN,writeNativeVerificationReportSnapshot:()=>ko});import{createHash as NN}from"node:crypto";import{promises as Te}from"node:fs";import Pt from"node:path";function Op(e,t){let r=Pt.relative(e,t);return r===""||!Pt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Pt.sep}`)}function YT(e,t){return Z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function bo(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return wt(r,i)?Z(r,i):Z(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function gN(e){let t=await Te.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Te.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function XT(e,t){let r=Pt.resolve(e),i=Pt.resolve(t);if(!Op(r,i))throw new Error("Native evidence path is outside its change");let n=[await gN(r)],a=r;for(let o of Pt.relative(r,i).split(Pt.sep).filter(Boolean)){a=Pt.join(a,o);let s=await gN(a);if(!Op(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function wN(e){for(let t of e){let r=await Te.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!YT(t,r)||await Te.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function QT(e,t,r={}){let i=await XT(t,Pt.dirname(e));await r.afterParentChainCaptured?.();let n=await Te.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Te.realpath(e);if(!Op(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Te.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Te.lstat(e),Te.realpath(e)]);if(await wN(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!bo(s,n)||!bo(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Yt)throw new Error(`Native evidence document exceeds ${Yt} bytes`);await r.afterOpen?.();let u=[],f=0,d=Buffer.allocUnsafe(64*1024);for(;;){let g=Yt+1-f,v=await o.read(d,0,Math.min(d.length,g),null);if(v.bytesRead===0)break;if(f+=v.bytesRead,f>Yt)throw new Error(`Native evidence document exceeds ${Yt} bytes`);u.push(Buffer.from(d.subarray(0,v.bytesRead)))}await r.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),Te.lstat(e),Te.realpath(e)]);if(await wN(i),!m.isFile()||m.isSymbolicLink()||h!==a||!bo(s,p)||!bo(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,f).toString("utf8"))}finally{await o.close()}}function Jr(e,t){if(!bN.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function ZT(e){return Jr("reports",e)}async function ko(e){let t=Buffer.from(e.text,"utf8");if(t.byteLength>Yt||NN("sha256").update(t).digest("hex")!==e.hash)throw new Error("Native verification report snapshot hash or size is invalid");return Ai({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 kN(e){let t=Hp(e.paths,e.name,"reports",e.hash),r=qe(e.paths,t);await z(r,t);let i=await Te.lstat(t);if(await So(e.paths,e.name,e.hash),await z(r,t),!bo(i,await Te.lstat(t)))throw new Error("Native report evidence changed before rollback");await Te.unlink(t)}async function So(e,t,r,i,n){if(!bN.test(r))throw new Error("Native report evidence hash is invalid");let a=await Xt({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"||NN("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 _i(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 Hp(e,t,r,i,n){let a=Jr(r,i);return n?Pt.join(n,...a.split("/")):wf(ot(e,t),a)}async function Xt(e){let t=Hp(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??qe(e.paths,t);return await z(r,t),QT(t,r,e.hooks)}async function Ai(e){jl(e.value);let t=Hp(e.paths,e.name,e.kind,e.hash),r=qe(e.paths,t);await z(r,t);try{let n=await Xt(e);if(JSON.stringify(n)!==JSON.stringify(e.value))throw new Error(`Native evidence hash collision for ${e.hash}`);return Jr(e.kind,e.hash)}catch(n){if(n.code!=="ENOENT")throw n}await we(t,e.value,{containedRoot:r}),e.onCreated?.();let i=await Xt(e);if(JSON.stringify(i)!==JSON.stringify(e.value))throw new Error(`Native evidence changed during commit for ${e.hash}`);return Jr(e.kind,e.hash)}function jl(e){if(ej(e)>Yt)throw new Error(`Native evidence document exceeds ${Yt} bytes`)}function ej(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
215
|
+
`);let r=0;nN(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){Mr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)go(o,n.path)&&(a+=1,Mr(t,"change-attribution",o));Mr(t,"change-end",{attributionCount:a}),a===0&&Mr(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&&Mr(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function ST(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=NT(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let x=new Set(r.externalDrift.paths),k=new Set(o.changePaths),E=r.externalDrift.paths.filter(C=>!k.has(C)||n.some(H=>go(H,C)));if(E.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${E.slice(0,8).join(", ")}`);if(x.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=T(ho,e),c=T(ho,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[x,k]of[["baseline",e],["current",t]])for(let E of k.omitted){if(l.length>=sT)break;l.push(hr({kind:"snapshot-omission",source:x,path:E.path,evidence:{reason:E.reason,size:E.size,type:E.type}},`${x} snapshot omitted ${E.path}: ${E.reason}`))}let f=e.omitted.length+t.omitted.length,d=[...Ky("baseline",e),...Ky("current",t),...o.totalChanges===0&&a===null?[hr({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 x=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(k=>x.has(k)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(k=>!x.has(k))}},m=x=>{let k=o.candidates.slice(0,x.detailedChangeCount),E=k.filter(Ce=>Ce.attributedTo.length===0&&!u.has(Ce.path)),C=o.totalChanges-k.length,H=o.totalUnattributed-E.length,P=f-x.detailedOmissionCount,W=H+P,ue=[...E.map(Ce=>hr({kind:"unattributed-change",source:"implementation-scope",path:Ce.path,evidence:{after:Ce.after,before:Ce.before,changeKind:Ce.kind}},`Changed path is not covered by a declared artifact: ${Ce.path}`)),...l.slice(0,x.detailedOmissionCount),...d,...W>0?[sN(x.overflowHash,{changes:C,unattributed:H,unresolved:W})]:[]],$t=gT(ue),ri=x.includeGitAdvisory?p():void 0;return{schema:Sp,contractHash:i,baselineProjectionRef:Ep(s),baselineProjectionHash:s,currentProjectionRef:Ep(c),currentProjectionHash:c,complete:$t.length===0,declaredArtifacts:n,changes:k,unattributed:E,unresolvedScopes:$t,noCodeReason:a,...ri?{gitAdvisory:ri}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},h=o.candidates.length,g=l.length,v=r.gitChangedPaths!==void 0,w="0".repeat(64);for(;;){let x=m({detailedChangeCount:h,detailedOmissionCount:g,includeGitAdvisory:v,overflowHash:w});if(vo({...x,scopeHash:w})<=Pi)break;if(v){v=!1;continue}if(g>0){g-=Math.max(1,Math.ceil(g/4));continue}if(h>0){h-=Math.max(1,Math.ceil(h/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let b=o.totalChanges>h||f>g?kT({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:h,detailedOmissionCount:g}):w,S=m({detailedChangeCount:h,detailedOmissionCount:g,includeGitAdvisory:v,overflowHash:b}),N={...S,scopeHash:T(rN,S)};if(vo(N)>Pi)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return N}function Ut(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Kt(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 Ri(e,t){if(typeof e!="string"||!Cp.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Xy(e,t,r){let i=Ep(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function xl(e,t){let r=Ut(e,"Native snapshot projection");if(Kt(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==tN)throw new Error("Native snapshot projection schema is invalid");let i=kp({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=hT(i);if(T(ho,r)!==T(ho,n))throw new Error("Native snapshot projection is not canonical");let a=T(ho,n);if(t!==void 0&&Ri(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Rp(e,t){let r=Ut(e,`Declared artifact ${t}`);if(Kt(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Wr(r.path,`Declared artifact ${t} path`),kind:r.kind}}function Qy(e,t){if(e===null)return null;let r=Ut(e,t);return Kt(r,["hash","size"],[],t),{hash:Ri(r.hash,`${t} hash`),size:xn(r.size,`${t} size`)}}function Zy(e,t){let r=Ut(e,`Implementation change ${t}`);if(Kt(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(Rp),n=Cl(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Qy(r.before,`Implementation change ${t} before`),o=Qy(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:Wr(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function xT(e,t){let r=Ut(e,`Unresolved scope ${t}`);Kt(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"?iN(r.path,`Unresolved scope ${t} path`):Wr(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function mo(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)=>Wr(n,`${t} ${a}`)),i=[...new Set(r)].sort(Re);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function cN(e){let t=Ut(e,"Native implementation external drift");if(Kt(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=mo(t.paths,"Native external drift paths");return oN({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function Rl(e){let t=Ut(e,"Native implementation scope"),r=[...ET].filter(E=>E!=="gitAdvisory"&&E!=="externalDrift");if(Kt(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==Sp)throw new Error("Native implementation scope schema is invalid");let i=Ri(t.contractHash,"Implementation scope contractHash"),n=Ri(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Xy(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=Ri(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Xy(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(Rp);if(JSON.stringify(c)!==JSON.stringify(Cl(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Zy),u=[...l].sort((E,C)=>Re(E.path,C.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(E=>E.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let f=new Set(c.map(E=>`${E.kind}:${E.path}`));if(l.some(E=>E.attributedTo.some(C=>!f.has(`${C.kind}:${C.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(E=>JSON.stringify(E.attributedTo)!==JSON.stringify(c.filter(C=>go(C,E.path)))))throw new Error("Implementation scope change attribution is inconsistent");let d=t.unattributed.map(Zy),p=t.externalDrift===void 0?void 0:cN(t.externalDrift),m=new Set(p?.paths??[]),h=l.filter(E=>E.attributedTo.length===0&&!m.has(E.path));if(JSON.stringify(d)!==JSON.stringify(h))throw new Error("Implementation scope unattributed changes are inconsistent");let g=t.unresolvedScopes.map(xT),v=g.filter(E=>E.kind==="scope-detail-overflow");if(v.length>1)throw new Error("Implementation scope has multiple detail overflow records");let w=v[0]===void 0?null:bT(v[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 y=t.noCodeReason,b=[...h.map(E=>hr({kind:"unattributed-change",source:"implementation-scope",path:E.path,evidence:{after:E.after,before:E.before,changeKind:E.kind}},`Changed path is not covered by a declared artifact: ${E.path}`)),...l.length+(w?.changes??0)===0&&y===null?[hr({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")]:[]],S=g.filter(E=>E.kind==="unattributed-change"||E.kind==="missing-no-code-reason");if(JSON.stringify(g)!==JSON.stringify([...g].sort(xp))||new Set(g.map(E=>E.id)).size!==g.length||JSON.stringify(S)!==JSON.stringify(b.sort(xp))||t.complete!==(g.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 N;if(t.gitAdvisory!==void 0){let E=Ut(t.gitAdvisory,"Implementation scope Git advisory");if(Kt(E,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),E.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let C=mo(E.changedPaths,"Git changed paths"),H=mo(E.pathsPresentInSnapshotChanges,"Git present paths"),P=mo(E.pathsAbsentFromSnapshotChanges,"Git absent paths"),W=[...H,...P].sort(Re);if(JSON.stringify(W)!==JSON.stringify(C)||P.some(ue=>l.some($t=>$t.path===ue)))throw new Error("Implementation scope Git advisory partition is invalid");N={advisoryOnly:!0,changedPaths:C,pathsPresentInSnapshotChanges:H,pathsAbsentFromSnapshotChanges:P}}let x={schema:Sp,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:d,unresolvedScopes:g,noCodeReason:y,...N?{gitAdvisory:N}:{},...p?{externalDrift:p}:{}},k=Ri(t.scopeHash,"Implementation scope scopeHash");if(T(rN,x)!==k)throw new Error("Implementation scope content hash mismatch");return{...x,scopeHash:k}}function CT(e){let t=Ut(e,"Native implementation scope authority");if(Kt(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(Rp);if(JSON.stringify(r)!==JSON.stringify(Cl(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=mo(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:cN(t.externalDrift),a=yT({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 wo(e){let t=Ut(e,"Native implementation scope bundle");Kt(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=CT(t.authority),i=xl(t.baseline),n=xl(t.current),a=Rl(t.scope),o=ST(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 lN(e){let t=Rl(e.scope);return wo({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 Sp,tN,ho,rN,iT,nT,aT,Cp,Pi,oT,sT,ET,Cn=A(()=>{"use strict";fe();po();Sp="comet.native.implementation-scope.v2",tN="comet.native.content-snapshot-projection.v1",ho="comet.native.content-snapshot-projection.v1",rN="comet.native.implementation-scope.v2",iT="comet.native.unresolved-scope-id.v1",nT="comet.native.scope-detail-overflow.v1",aT="comet.native.snapshot-projection-overflow.v2",Cp=/^[a-f0-9]{64}$/u,Pi=1024*1024,oT=128,sT=128;ET=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});import uN from"node:path";function mr(e,t){if(!fN.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function pN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function hN(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 Pp(e,t,r=2e3){let i=Me(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function yo(e,t){let r=uN.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})||uN.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 AT(e,t,r){let i=yo(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=Xi(i),a=i.toLowerCase(),o=r?yo(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 _p(e){let t=yo(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 Rn(e,t){return e<t?-1:e>t?1:0}function Pl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function _l(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 mN(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 dN(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 IT(e){let t=Pl(e,"Native acceptance trace");if(_l(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"||!fN.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=yo(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=Pl(o,`Native acceptance trace entry ${s}`);if(_l(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(f=>typeof f!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(f=>_p(f)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Rn))||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:yo(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Pp(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>Rn(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=mr(t.traceHash,"Native acceptance trace hash");if(T(RT,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function vN(e){let t=Pl(e,"Native partial allowance");if(_l(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(Rn))||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:hN(t.change),scopeHash:mr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Pp(t.reason,"Partial allowance reason"),confirmedSummary:Pp(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:pN(t.sourceRevision),confirmedAt:mN(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=mr(t.allowanceHash,"Native partial allowance hash");if(T(PT,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function Ap(e){let t=Pl(e,"Native verification evidence");if(_l(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=mr(t.implementationScopeHash,"Native verification implementation scope hash"),i=IT(t.acceptanceTrace),n=mr(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:mr(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(d=>_p(d));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Rn)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(d=>d.evidenceRefs))].sort(Rn);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(d=>_p(d));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Rn)))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:hN(t.change),sourceRevision:pN(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:mr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:dN(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:AT(t.reportRef,"Native verification report ref"),reportHash:mr(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:dN(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:mN(t.createdAt,"Native verification timestamp")},f=mr(t.envelopeHash,"Native verification envelope hash");if(T(_T,u)!==f)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:f}}var fN,RT,PT,_T,Al=A(()=>{"use strict";fe();qr();Sa();Cn();fN=/^[a-f0-9]{64}$/u,RT="comet.native.acceptance-trace.v2",PT="comet.native.partial-allowance.v1",_T="comet.native.verification-evidence.v2"});var Il,TT,jT,$T,nF,OT,aF,Ip=A(()=>{"use strict";fe();Il="scoped-text-safety",TT=1,jT=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),$T="comet.native.checker-policy.v1",nF=T($T,{policy:Il,version:TT,limits:jT,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),OT=["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"],aF=new Set(OT)});function Pn(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 zr(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 vr(e,t){if(typeof e!="string"||!DT.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Rt(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=Me(e).trim();if(!r||r.length>FT||r!==e.trim())throw new Error(`${t} is invalid`);return r}function Tp(e,t){let r=Rt(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 No(e,t,r=Rt,i=!1,n=VT){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 WT(e,t){if(typeof e!="string"||!BT.test(e))throw new Error(`${t} is invalid`);return e}function zT(e){let t=Pn(e,"Native verification receipt bindings");if(zr(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!LT.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:vr(t.contractHash,"Native verification receipt contract hash"),scopeHash:vr(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:vr(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:vr(t.artifactHash,"Native verification receipt artifact hash")}}function JT(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=qT.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function GT(e,t,r,i){let n=Pn(t,`Native ${e} evidence`);if(e==="automated-check"){if(zr(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=Tp(n.startedAt,"Native automated-check start time"),o=Tp(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=Pn(n.worktree,"Native automated-check worktree");if(zr(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=Pn(n.afterFence,"Native automated-check after fence");if(zr(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:Rt(n.executable,"Native automated-check executable"),args:No(n.args,"Native automated-check arguments",Rt,!0),cwd:Rt(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:Rt(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:vr(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:vr(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:vr(n.outputHash,"Native automated-check output hash"),outputSummary:Rt(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){zr(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=JT(n.checkReceiptRef);if(vr(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:No(n.subjects,"Native static inspection subjects",Rt,i==="required-check"),rule:Rt(n.rule,"Native static inspection rule"),resultSummary:Rt(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return zr(n,["steps","observations"],"Native manual-evidence evidence"),{steps:No(n.steps,"Native manual evidence steps"),observations:No(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function UT(e){let t=Pn(e,"Native verification receipt");if(zr(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=Rt(t.actor,"Native verification receipt actor"),o=No(t.acceptanceIds,"Native receipt acceptance IDs",WT,i==="required-check",MT).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:jp,kind:r,role:i,status:n,bindings:zT(t.bindings),acceptanceIds:o,actor:a,issuedAt:Tp(t.issuedAt,"Native verification receipt issue time"),evidence:GT(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==Il||s.actor!==`native-runtime:${Il}`))throw new Error("Native required check policy identity is invalid");return s}function $p(e){let t=Pn(e,"Native verification receipt");if(zr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==jp)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=UT(i),a=vr(t.receiptHash,"Native verification receipt hash");if(T(HT,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}var jp,HT,DT,BT,LT,qT,FT,VT,MT,Tl=A(()=>{"use strict";fe();Ip();qr();jp="comet.native.verification-receipt.v3",HT=jp,DT=/^[a-f0-9]{64}$/u,BT=/^acceptance-[a-f0-9]{64}$/u,LT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,qT=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,FT=4096,VT=256,MT=1024});var RN={};du(RN,{MAX_NATIVE_EVIDENCE_DOCUMENT_BYTES:()=>Yt,MAX_NATIVE_IMPLEMENTATION_SCOPE_BUNDLE_BYTES:()=>KT,listNativeVerificationReceiptRefs:()=>xN,nativeEvidenceRef:()=>Jr,nativeReportEvidenceRef:()=>ZT,readArchivedNativeVerificationAcceptanceCounts:()=>oj,readNativeImplementationScope:()=>Eo,readNativeImplementationScopeBundle:()=>$l,readNativePartialAllowance:()=>Lp,readNativeVerificationEvidence:()=>qp,readNativeVerificationReceipt:()=>Ol,readNativeVerificationReportSnapshot:()=>So,removeNativeVerificationReportSnapshot:()=>kN,writeNativeImplementationScope:()=>nj,writeNativePartialAllowance:()=>aj,writeNativeVerificationEvidence:()=>CN,writeNativeVerificationReceipt:()=>EN,writeNativeVerificationReportSnapshot:()=>ko});import{createHash as NN}from"node:crypto";import{promises as Te}from"node:fs";import Pt from"node:path";function Op(e,t){let r=Pt.relative(e,t);return r===""||!Pt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Pt.sep}`)}function YT(e,t){return Z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function bo(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return wt(r,i)?Z(r,i):Z(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function gN(e){let t=await Te.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await Te.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function XT(e,t){let r=Pt.resolve(e),i=Pt.resolve(t);if(!Op(r,i))throw new Error("Native evidence path is outside its change");let n=[await gN(r)],a=r;for(let o of Pt.relative(r,i).split(Pt.sep).filter(Boolean)){a=Pt.join(a,o);let s=await gN(a);if(!Op(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function wN(e){for(let t of e){let r=await Te.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!YT(t,r)||await Te.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function QT(e,t,r={}){let i=await XT(t,Pt.dirname(e));await r.afterParentChainCaptured?.();let n=await Te.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await Te.realpath(e);if(!Op(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await Te.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),Te.lstat(e),Te.realpath(e)]);if(await wN(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!bo(s,n)||!bo(s,c))throw new Error("Native evidence document changed while opening");if(s.size>Yt)throw new Error(`Native evidence document exceeds ${Yt} bytes`);await r.afterOpen?.();let u=[],f=0,d=Buffer.allocUnsafe(64*1024);for(;;){let g=Yt+1-f,v=await o.read(d,0,Math.min(d.length,g),null);if(v.bytesRead===0)break;if(f+=v.bytesRead,f>Yt)throw new Error(`Native evidence document exceeds ${Yt} bytes`);u.push(Buffer.from(d.subarray(0,v.bytesRead)))}await r.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),Te.lstat(e),Te.realpath(e)]);if(await wN(i),!m.isFile()||m.isSymbolicLink()||h!==a||!bo(s,p)||!bo(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,f).toString("utf8"))}finally{await o.close()}}function Jr(e,t){if(!bN.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function ZT(e){return Jr("reports",e)}async function ko(e){let t=Buffer.from(e.text,"utf8");if(t.byteLength>Yt||NN("sha256").update(t).digest("hex")!==e.hash)throw new Error("Native verification report snapshot hash or size is invalid");return Ai({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 kN(e){let t=Hp(e.paths,e.name,"reports",e.hash),r=qe(e.paths,t);await z(r,t);let i=await Te.lstat(t);if(await So(e.paths,e.name,e.hash),await z(r,t),!bo(i,await Te.lstat(t)))throw new Error("Native report evidence changed before rollback");await Te.unlink(t)}async function So(e,t,r,i,n){if(!bN.test(r))throw new Error("Native report evidence hash is invalid");let a=await Xt({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"||NN("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 _i(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 Hp(e,t,r,i,n){let a=Jr(r,i);return n?Pt.join(n,...a.split("/")):wf(ot(e,t),a)}async function Xt(e){let t=Hp(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??qe(e.paths,t);return await z(r,t),QT(t,r,e.hooks)}async function Ai(e){jl(e.value);let t=Hp(e.paths,e.name,e.kind,e.hash),r=qe(e.paths,t);await z(r,t);try{let n=await Xt(e);if(JSON.stringify(n)!==JSON.stringify(e.value))throw new Error(`Native evidence hash collision for ${e.hash}`);return Jr(e.kind,e.hash)}catch(n){if(n.code!=="ENOENT")throw n}await we(t,e.value,{containedRoot:r}),e.onCreated?.();let i=await Xt(e);if(JSON.stringify(i)!==JSON.stringify(e.value))throw new Error(`Native evidence changed during commit for ${e.hash}`);return Jr(e.kind,e.hash)}function jl(e){if(ej(e)>Yt)throw new Error(`Native evidence document exceeds ${Yt} bytes`)}function ej(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
216
216
|
`,"utf8")}function yN(e,t){return xl(e,t)}function tj(e,t){let r=Rl(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function SN(e,t,r){let i=vN(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function Dp(e,t,r){let i=Ap(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}function rj(e){return{total:e.total,evidenced:e.evidenced,skipped:e.skipped}}function ij(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,f=typeof c=="number"?c:Number.NaN;if(a.schema!=="comet.native.acceptance-trace.v1"||!Number.isSafeInteger(l)||!Number.isSafeInteger(u)||!Number.isSafeInteger(f)||l<0||u<0||f<0||u+f>l)throw new Error("Legacy Native acceptance trace is invalid");return{total:l,evidenced:u,skipped:f}}async function Bp(e,t,r,i=!1,n){let a=await Eo(e,t,r.implementationScopeRef,void 0,n);if(i&&await So(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 Lp(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 nj(e){let t=wo(e.bundle),{baseline:r,current:i,scope:n}=t;return jl(r),jl(i),jl(n),await Ai({paths:e.paths,name:e.name,kind:"snapshots",hash:n.baselineProjectionHash,value:r}),await Ai({paths:e.paths,name:e.name,kind:"snapshots",hash:n.currentProjectionHash,value:i}),Ai({paths:e.paths,name:e.name,kind:"scopes",hash:n.scopeHash,value:n})}async function $l(e,t,r,i,n){let a=_i(r,"scopes"),o=tj(await Xt({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=_i(o.baselineProjectionRef,"snapshots"),c=_i(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Xt({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(f=>yN(f,s)),Xt({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(f=>yN(f,c))]);return lN({baseline:l,current:u,scope:o})}async function Eo(e,t,r,i,n){return(await $l(e,t,r,i,n)).scope}async function aj(e){let t=SN(e.allowance,e.name,e.allowance.allowanceHash),r=await Eo(e.paths,e.name,Jr("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 Ai({...e,kind:"allowances",hash:t.allowanceHash,value:t})}async function Lp(e,t,r,i,n){let a=_i(r,"allowances");return SN(await Xt({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function EN(e){let t=$p(e.receipt);if(t.bindings.change!==e.name)throw new Error("Native verification receipt change mismatch");return Ai({paths:e.paths,name:e.name,kind:"receipts",hash:t.receiptHash,value:t})}async function Ol(e,t,r,i,n){let a=_i(r,"receipts"),o=$p(await Xt({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 xN(e,t){let r=Pt.join(ot(e,t),"evidence","receipts");await z(qe(e,r),r);let i;try{i=await Te.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=>Jr("receipts",n))}async function CN(e){let t=Dp(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 Bp(e.paths,e.name,t,!0),Ai({...e,kind:"verifications",hash:t.envelopeHash,value:t})}async function qp(e,t,r,i,n){let a=_i(r,"verifications"),o=Dp(await Xt({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await Bp(e,t,o,!1,n),o}async function oj(e,t,r,i){let n=_i(r,"verifications"),a=await Xt({paths:e,name:t,kind:"verifications",hash:n,changeDir:i}),o=ij(a,t,n);if(o)return o;let s=Dp(a,t,n);return await Bp(e,t,s,!1,i),rj(s.acceptanceTrace)}var bN,Yt,KT,Gr=A(()=>{"use strict";ne();te();Dt();Cn();Al();Tl();bN=/^[a-f0-9]{64}$/u,Yt=Pi,KT=3*Yt});var _N={};du(_N,{executeNativeSupervisorChecks:()=>Mp,readNativeSupervisorCheckEvidence:()=>_n});import{createHash as sj,randomUUID as cj}from"node:crypto";import{promises as PN}from"node:fs";import Vp from"node:path";function Co(e){return sj("sha256").update(e).digest("hex")}function Fp(e,t){if(I(t.projectRoot,["branch","--show-current"])!==`comet/supervisor/${e}/${t.child}`||I(t.projectRoot,["rev-parse","HEAD"])!==t.baseCommit||!zt(t.projectRoot))throw new Error("Native Supervisor checks require the clean current candidate in its bound worktree")}function xo(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 lj(e,t){return Promise.all(t.map(async r=>{let i=gl(r),n=await z(e,Vp.resolve(e,...i.logRef.split(/[\\/]/u))),a=await PN.readFile(n,"utf8"),o=Me(a);return{...i,logContent:o.slice(0,128*1024),logDigest:Co(o)}}))}function uj(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 dj(e){try{let t=pe(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 z(t,Vp.resolve(t,...i.logRef.split(/[\\/]/u))),a=Me(await PN.readFile(n,"utf8"));return Co(a)===i.logDigest&&a.slice(0,128*1024)===i.logContent}))).every(Boolean)}catch{return!1}}function fj(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 pj(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 Mp(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=fj(e.retryCheckIds),r=await _(e.paths,"reserve Supervisor checks",async()=>{let l=await O(e.paths,e.parent),u=xo(l,e.child,e.runId);Fp(e.parent,u),Ye(u.projectRoot,e.plans);let f=yl(),d=await wl({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=T("comet.native.supervisor-check-plan.v2",{machineId:f,inputFingerprint:d}),m=u.checkExecution;if(m?.status==="running"){let w=await mn(m.ownerPid,m.ownerIdentity),y=Date.parse(m.expiresAt??"")||Date.parse(m.startedAt)+3e4;if(w){if(!(Date.now()<y))throw new Error("Native Supervisor check lease expired while owner PID is alive; inspect the original execution before retrying");if(m.key!==p)throw new Error("Native Supervisor check plan is already running with different inputs");return{task:structuredClone(u),execute:!1}}let b=m.activeProcess;if(b===void 0||b?.status==="starting")throw new Error(`Native Supervisor check process registration is incomplete. Check logs in ${Vp.join(pe(e.paths,e.parent),"logs","checks")} for operation ${m.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 mn(b.pid,b.identity)){if(!(Date.now()<y))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(m.checkStates?.length&&m.checkStates.every(({status:N})=>N==="passed"||N==="failed")&&m.receiptRef){m.status="completed";try{return await _n({...e,task:u,receiptRef:m.receiptRef}),l.stateVersion+=1,await q(e.paths,l),{task:structuredClone(u),execute:!1,key:m.key}}catch{m.status="interrupted"}}m.status="interrupted";for(let N of m.checkStates??[])(N.status==="planned"||N.status==="running")&&(N.status="interrupted")}let h=m?.key===p&&m.machineId===f&&m.inputFingerprint===d;if(t){if(!h||m?.status!=="interrupted")throw new Error("Native Supervisor check retry requires the interrupted current plan on the same candidate, machine and workspace");pj(m.checkStates,e.plans,t)}else if(m?.status==="interrupted"&&h)return{task:structuredClone(u),execute:!1,key:p};if(m?.status==="completed"&&h&&m.receiptRef)try{return await _n({...e,task:u,receiptRef:m.receiptRef}),{task:structuredClone(u),execute:!1,key:p}}catch{}let g=t&&m?.checkStates?m.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(bn),v=e.plans.map(w=>g.find(y=>y.id===w.id)??bn(w));return u.checkExecution={operationId:cj(),key:p,status:"running",ownerPid:process.pid,ownerIdentity:await Ke(process.pid)??void 0,activeProcess:null,startedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+e.plans.reduce((w,y)=>w+y.timeoutMs,0)+3e4).toISOString(),machineId:f,inputFingerprint:d,checkStates:v},u.checksReason="running",l.stateVersion+=1,await q(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 _n({...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=pe(e.paths,e.parent),o=r.plansToExecute,s=async l=>{await _(e.paths,"register Supervisor check process",async()=>{let u=await O(e.paths,e.parent),f=xo(u,e.child,e.runId);if(f.checkExecution?.operationId!==n||f.checkExecution.status!=="running")throw new Error("Native Supervisor check operation is stale");if(l?.status==="starting"){let d=f.checkExecution.checkStates?.find(({id:p})=>p===l.checkId);if(!d||d.status!=="planned")throw new Error(`Native Supervisor check ${l.checkId} is not planned`);d.status="running",d.executionCount+=1,d.startedAt=new Date().toISOString(),d.completedAt=null,d.logRef=null}f.checkExecution.activeProcess=l,u.stateVersion+=1,await q(e.paths,u)})},c=async l=>_(e.paths,"record Supervisor check result",async()=>{let u=await O(e.paths,e.parent),f=xo(u,e.child,e.runId);if(f.checkExecution?.operationId!==n||f.checkExecution.status!=="running")throw new Error("Native Supervisor check operation is stale");let d=f.checkExecution.checkStates?.find(({id:p})=>p===l.id);if(!d)throw new Error(`Native Supervisor check state is missing: ${l.id}`);Object.assign(d,vl(d,l)),f.checkExecution.activeProcess=null,u.stateVersion+=1,await q(e.paths,u)});try{for(let g of o){await s({status:"starting",checkId:g.id});let v=await Ni({projectRoot:i.projectRoot,runtimeDir:a,operationId:n,plan:g,onSpawn:async({pid:w})=>{await s({status:"running",checkId:g.id,pid:w,identity:await Ke(w)??void 0})}});if(await c(v),v.status==="interrupted")throw new Error(`Native Supervisor check ${v.id} was interrupted; retry only the listed repeatable check after the process has exited`)}let l=await O(e.paths,e.parent),u=xo(l,e.child,e.runId);Fp(e.parent,u);let f=u.checkExecution?.checkStates;if(!f||f.some(({status:g})=>!["passed","failed"].includes(g)))throw new Error("Native Supervisor check plan remains incomplete; retry each interrupted check explicitly");let d=await lj(a,f),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:d,materials:e.materials.map(({name:g,content:v})=>{let w=Me(v);return{name:g,content:w,hash:Co(w)}})},m=JSON.stringify(p),h=await ko({paths:e.paths,name:e.parent,hash:Co(m),text:m});return await _(e.paths,"complete Supervisor checks",async()=>{let g=await O(e.paths,e.parent),v=xo(g,e.child,e.runId);if(v.checkExecution?.operationId!==n)throw new Error("Native Supervisor check operation is stale");Fp(e.parent,v),v.checkExecution.status="completed",v.checkExecution.receiptRef=h,v.checkExecution.activeProcess=null,v.checksReason="completed",g.stateVersion+=1,await q(e.paths,g)}),{status:"completed",operationId:n,receiptRef:h}}catch(l){throw await _(e.paths,"interrupt Supervisor checks",async()=>{let u=await O(e.paths,e.parent),f=u?.children.find(({name:d})=>d===e.child)?.task;if(f?.runId===e.runId&&f.checkExecution?.operationId===n){f.checkExecution.status="interrupted",f.checkExecution.activeProcess=null;for(let d of f.checkExecution.checkStates??[])(d.status==="planned"||d.status==="running")&&(d.status="interrupted");f.checksReason="not-run",u.stateVersion+=1,await q(e.paths,u)}}),l}}async function _n(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 So(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)=>uj(s,n[c])),o=Array.isArray(r.checks)&&await dj({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})=>Co(s)!==c))throw new Error("Native Supervisor receipt does not match the current candidate, runId, contract or execution");return r}var Wp=A(()=>{"use strict";kn();rt();Xa();fe();gn();yp();Gr();le();te();qr();lr()});var $N=br(rr(),1);import{promises as Nj}from"node:fs";import _t from"node:path";import{execFileSync as wR}from"child_process";import yR from"fs";import Xs from"path";function ir(e,t){return wR("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Ki(e,t){return Ig(e)===Ig(t)}function Ig(e){let t=Xs.resolve(e);try{let r=yR.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function ie(e){try{let t=Xs.resolve(ir(e,["rev-parse","--show-toplevel"])),i=ir(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?Xs.resolve(i.slice(9)):t,a=null;try{a=ir(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Ki(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Qs(e){try{ir(e,["rev-parse","--is-inside-work-tree"]);let t=ir(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:Xs.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 nr(e){return Qs(e).map(t=>t.root)}function Tg(e){try{return ir(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{return null}}function Yi(e,t){try{return ir(e,["check-ref-format","--branch",t]),ir(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function ar(e,t){try{let r=ir(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}rt();nt();fe();st();te();ut();Pc();Pc();gi();lr();import{randomUUID as mj}from"node:crypto";import Hl from"node:path";rt();Xa();ne();fe();gn();le();te();yp();gi();lr();kn();rt();import{promises as fo}from"node:fs";import ze from"node:path";st();kn();ro();te();var Vr=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function Fy(e,t){let r=ze.relative(e,t);return r===""||!ze.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ze.sep}`)}function Ly(e){return JSON.stringify(e.native)}async function kl(e,t){let r=await _e(e);if(r&&t){if(Ly(r)!==Ly(t))throw new Error(`Native worktree configuration differs from the source project: ${ze.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await yc(e,t),await By(e),!0):!1}async function RI(e,t){if(!Fy(e,t))return!1;let i=`/${ze.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=I(e,["rev-parse","--git-common-dir"]),a=ze.resolve(e,n),o=ze.join(a,"info","exclude"),s="";try{s=await fo.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await fo.mkdir(ze.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
|
|
217
217
|
`)?"":`
|
|
218
218
|
`;return await fo.appendFile(o,`${c}${i}
|
|
219
|
-
`,"utf8"),!0}function PI(e,t,r){let i=ze.resolve(e,r??ze.join(".worktrees",t)),n=ze.resolve(e,I(e,["rev-parse","--git-common-dir"]));if(Fy(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(nr(e).some(a=>Ki(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function _I(e){try{throw await fo.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function qy(e){try{return await fo.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Np(e){let t=ze.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=ie(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await Dr(t,e.sourceConfig?.native.artifact_root??"docs");return Bw([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=ie(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;Gd(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(Gd(t,o),!Yi(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let p=!1;if(!a){if(!Zs(t))throw new Error("Native branch isolation requires a clean current working directory");if(Yi(t,n))throw new Error(`Native change branch already exists: ${n}`);I(t,["switch","-c",n,o]),p=!0}let m;try{m=await kl(t,e.sourceConfig)}catch(h){throw new Vr(`Native branch preparation is incomplete: ${h.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let p=e.worktreePath?ze.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!Ki(p,i.currentWorktreeRoot))throw new Error(`Native worktree path ${p} does not match the current worktree ${i.currentWorktreeRoot}`);let m;try{m=await kl(t,e.sourceConfig)}catch(h){throw new Vr(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}let s=Qs(i.primaryWorktreeRoot),c=s.find(p=>p.branch===n);if(c&&await qy(c.root)){let p=e.worktreePath?ze.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!Ki(p,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let m;try{m=await kl(c.root,e.sourceConfig)}catch(h){throw new Vr(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}c&&!await qy(c.root)&&(I(i.primaryWorktreeRoot,["worktree","prune"]),s=Qs(i.primaryWorktreeRoot));let l=Yi(t,n);if(s.some(p=>p.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=PI(i.primaryWorktreeRoot,e.name,e.worktreePath);await _I(u);let f=await RI(i.primaryWorktreeRoot,u),d={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:f,configInitialized:!1};try{I(i.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),d.createdBranch=!l,d.createdWorktree=!0,d.configInitialized=await kl(u,e.sourceConfig)}catch(p){throw new Vr(`Native worktree preparation is incomplete: ${p.message}`,d,{cause:p})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:d}})}function Dl(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}async function zp(e){let t=Hl.join(".worktrees",`${e.parent}-integration`);return Np({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:Dl(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function Jp(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.parent)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.child))throw new Error("Native Supervisor parent and child names are invalid");return Np({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:Hl.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function vj(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 gj(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}`)}}function AN(e,t,r){let i=ie(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor child worktree identity is not ${t}`);if(!zt(e))throw new Error(`Native Supervisor child worktree is not clean: ${e}`);let n=I(e,["rev-parse","HEAD"]);if(n===r)return;if(!(()=>{try{return I(e,["merge-base","--is-ancestor",n,r]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} cannot be refreshed from integration HEAD`);if((()=>{try{return I(e,["merge-base","--is-ancestor",r,n]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} contains unintegrated commits`);if(I(e,["merge","--ff-only",r]),I(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor child worktree did not reach integration HEAD")}function Ro(e){if(!zt(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=I(e.integration.worktree,["rev-parse","--show-toplevel"]);if(Hl.resolve(t)!==Hl.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=I(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return I(e.integration.worktree,["rev-parse","HEAD"])}function IN(e,t,r){let i=ie(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor Verifier worktree identity is not ${t}`);if(!zt(e))throw new Error(`Native Supervisor Verifier worktree is not clean: ${e}`);if(I(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor Verifier worktree is not at its candidate commit")}async function Gp(e){let t=vj(e.retryCheckIds),r=await _(e.paths,`integrate Native Supervisor child ${e.name}`,async()=>{let p=await O(e.paths,e.state.parent)??e.state,m=p.integration.checkExecution;if(m?.status==="running"){if(await mn(m.ownerPid,m.ownerIdentity))throw new Error("Native Supervisor integration checks are already running; wait for the original execution");if(m.activeProcess===void 0||m.activeProcess?.status==="starting")throw new Error("Native Supervisor integration check launch was interrupted; inspect the original check process before retrying");if(m.activeProcess&&await mn(m.activeProcess.pid,m.activeProcess.identity))throw new Error("Native Supervisor integration check process is still running after its owner stopped; wait for that process before retrying")}if(p.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before integration; reload status first");let h=p.children.find(({name:S})=>S===e.name);if(!h)throw new Error(`Native Supervisor child ${e.name} does not exist`);let g=gw(p).find(({status:S})=>S!=="integrated"&&S!=="archived");if(g&&g.name!==e.name)throw new Error(`Native Supervisor integration order requires ${g.name} before ${e.name}`);if(h.status!=="verified"||!h.verifiedCommit)throw new Error(`Native Supervisor child ${e.name} must be verified before integration`);if(e.checkPlans){if(e.checkPlans.some(({repeatable:x})=>!x))throw new Error("Native Supervisor integration checks must be repeatable for safe recovery");if(e.checkPlans.length===0||new Set(e.checkPlans.map(({id:x})=>x)).size!==e.checkPlans.length)throw new Error("Native Supervisor integration requires non-empty checks with unique IDs");if(Ye(p.integration.worktree,e.checkPlans),!h.verification?.receiptRef||!h.verification.execution)throw new Error("Native Supervisor integration requires current Runtime verification evidence; reverify the child");let{readNativeSupervisorCheckEvidence:S}=await Promise.resolve().then(()=>(Wp(),_N)),N=await S({paths:e.paths,parent:p.parent,task:h.verification.execution,receiptRef:h.verification.receiptRef});if(N.candidateCommit!==h.verifiedCommit||N.checks.some(({status:x})=>x!=="passed"))throw new Error("Native Supervisor integration verification evidence is stale or failed")}let v=Ro(p),w=e.checkPlans!==void 0&&m?.status==="interrupted"&&m.child===e.name&&m.candidateCommit===h.verifiedCommit&&v!==p.integration.headCommit&&v===m.integrationCommit;if(v!==p.integration.headCommit){let S=(()=>{try{return I(p.integration.worktree,["merge-base","--is-ancestor",p.integration.headCommit,v]),!0}catch{return!1}})(),N=(()=>{try{return I(p.integration.worktree,["merge-base","--is-ancestor",h.verifiedCommit,v]),!0}catch{return!1}})();if(!S||!N)throw new Error(`Native Supervisor integration head drifted: expected ${p.integration.headCommit}, got ${v}`)}try{I(p.integration.worktree,["cat-file","-e",`${h.verifiedCommit}^{commit}`])}catch(S){throw new Error(`Native Supervisor verified commit is unavailable: ${h.verifiedCommit}`,{cause:S})}if(v===p.integration.headCommit&&!w){try{I(p.integration.worktree,["merge","--no-ff","--no-edit",h.verifiedCommit])}catch(S){throw new Error(`Native Supervisor integration conflict preserved in ${p.integration.worktree}`,{cause:S})}v=I(p.integration.worktree,["rev-parse","HEAD"])}let y=v;if(e.checkPlans){let S=yl(),N=await wl({kind:"integration",parent:p.parent,child:e.name,runId:h.verification?.execution?.runId??`integration:${e.name}`,projectRoot:p.integration.worktree,candidateCommit:h.verifiedCommit,integrationCommit:y,contractHash:h.contractHash??null,plans:e.checkPlans,materials:[]}),x=T("comet.native.supervisor-integration-plan.v2",{machineId:S,inputFingerprint:N}),k=m?.key===x&&m.machineId===S&&m.inputFingerprint===N&&m.child===e.name&&m.candidateCommit===h.verifiedCommit&&m.integrationCommit===y;if(t){if(!k||m?.status!=="interrupted")throw new Error("Native Supervisor integration retry requires the interrupted current plan on the same candidate, machine and workspace");gj(m.checkStates,e.checkPlans,t)}else if(m?.status==="interrupted"&&k){let P=(m.checkStates??[]).filter(({status:W})=>W==="failed");if(P.length>0)throw new Error(`Native Supervisor integration checks already failed on the identical plan (${P.map(({id:W})=>W).join(", ")}); change the integration check plan or re-verify the child instead of rerunning the same integrate`);return{completed:p}}let E=t&&m?.checkStates?m.checkStates.map(P=>t.has(P.id)?{...P,status:"planned",exitCode:null,signal:null,timedOut:!1,durationMs:0,startedAt:null,completedAt:null,logRef:null}:{...P}):e.checkPlans.map(bn),C=e.checkPlans.map(P=>E.find(W=>W.id===P.id)??bn(P)),H=mj();return p.integration.checkExecution={operationId:H,key:x,child:e.name,candidateCommit:h.verifiedCommit,integrationCommit:y,status:"running",ownerPid:process.pid,ownerIdentity:await Ke(process.pid)??void 0,startedAt:new Date().toISOString(),activeProcess:null,machineId:S,inputFingerprint:N,checkStates:C},p.stateVersion+=1,await q(e.paths,p),{pending:{state:p,candidateCommit:h.verifiedCommit,integrationCommit:y,operationId:H,key:x,machineId:S,inputFingerprint:N,plansToExecute:e.checkPlans.filter(P=>!t||t.has(P.id))}}}let b=$c(p,{name:e.name,integrationCommit:y,checks:e.checks});return await q(e.paths,b),{completed:b}});if(r.completed)return r.completed;let{state:i,candidateCommit:n,integrationCommit:a,operationId:o,key:s}=r.pending,{writeNativeVerificationReportSnapshot:c}=await Promise.resolve().then(()=>(Gr(),RN)),{createHash:l}=await import("node:crypto"),u=async d=>_(e.paths,"record Supervisor integration check process",async()=>{let p=await O(e.paths,i.parent),m=p?.integration.checkExecution;if(!p||m?.operationId!==o||m.key!==s||m.status!=="running")throw new Error("Native Supervisor integration check operation is stale");if(d?.status==="starting"){let h=m.checkStates?.find(({id:g})=>g===d.checkId);if(!h||h.status!=="planned")throw new Error(`Native Supervisor check ${d.checkId} is not planned`);h.status="running",h.executionCount+=1,h.startedAt=new Date().toISOString(),h.completedAt=null,h.logRef=null}m.activeProcess=d,p.stateVersion+=1,await q(e.paths,p)}),f=async d=>_(e.paths,"record Supervisor integration check result",async()=>{let p=await O(e.paths,i.parent),m=p?.integration.checkExecution;if(!p||m?.operationId!==o||m.key!==s||m.status!=="running")throw new Error("Native Supervisor integration check operation is stale");let h=m.checkStates?.find(({id:g})=>g===d.id);if(!h)throw new Error(`Native Supervisor check state is missing: ${d.id}`);Object.assign(h,vl(h,d)),m.activeProcess=null,p.stateVersion+=1,await q(e.paths,p)});try{for(let b of r.pending.plansToExecute){await u({status:"starting",checkId:b.id});let S=await Ni({projectRoot:i.integration.worktree,runtimeDir:pe(e.paths,i.parent),operationId:o,plan:b,onSpawn:async({pid:N})=>u({status:"running",checkId:b.id,pid:N,identity:await Ke(N)??void 0})});if(await f(S),S.status==="interrupted")throw new Error(`Native Supervisor integration check ${S.id} was interrupted; retry only the listed repeatable check after the process has exited`)}let d=await O(e.paths,i.parent),m=d?.integration.checkExecution?.checkStates;if(!d||!m||m.some(({status:b})=>!["passed","failed"].includes(b)))throw new Error("Native Supervisor integration check plan remains incomplete; retry each interrupted check explicitly");let h=m.map(gl),g=JSON.stringify({schema:"comet.native.supervisor-integration-checks.v1",parent:i.parent,child:e.name,candidateCommit:n,integrationCommit:a,operationId:o,planHash:s,results:h}),v=await c({paths:e.paths,name:i.parent,hash:l("sha256").update(g).digest("hex"),text:g}),w=h.map(b=>({name:b.name,status:b.status==="interrupted"?"incomplete":b.status,reason:b.status==="passed"?null:b.timedOut?"timed out":`exit ${b.exitCode??b.signal??"interrupted"}`,receiptRef:v})),y=w.filter(({status:b})=>b!=="passed");return await _(e.paths,"complete Supervisor integration checks",async()=>{let b=await O(e.paths,i.parent),S=b?.children.find(({name:k})=>k===e.name),N=b?.integration.checkExecution;if(!b||!S||N?.operationId!==o||N.key!==s||N.status!=="running"||N.child!==e.name||N.candidateCommit!==n||N.integrationCommit!==a||S.verifiedCommit!==n||Ro(b)!==a)throw new Error("Native Supervisor integration changed during checks");if(N.receiptRef=v,N.checks=w,y.length>0){let k=`Native Supervisor integration checks did not pass (${y.map(({name:E,reason:C})=>`${E}: ${C}`).join("; ")}); receipt ${v}`;throw N.status="interrupted",N.error=k,S.blocker=k,b.stateVersion+=1,await q(e.paths,b),new Error(k)}N.status="completed";let x=$c(b,{name:e.name,integrationCommit:a,checks:w});return await q(e.paths,x),x})}catch(d){throw await _(e.paths,"interrupt Supervisor integration checks",async()=>{let p=await O(e.paths,i.parent),m=p?.integration.checkExecution;if(p&&m?.operationId===o&&m.key===s&&m.status==="running"){m.status="interrupted",m.error=d.message,m.activeProcess=null;for(let h of m.checkStates??[])(h.status==="planned"||h.status==="running")&&(h.status="interrupted");p.stateVersion+=1,await q(e.paths,p)}}),d}}import{randomUUID as wj}from"node:crypto";import yj from"node:path";rt();st();le();gi();lr();async function Po(e){let t=Dl(e.parent),r=ar(e.paths.projectRoot,t);if(!r)return null;let i=ar(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=nr(e.paths.projectRoot).map(o=>yj.resolve(o)).find(o=>ie(o).currentBranch===t);if(!n)return null;let a=Ja({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return Ue(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}async function Up(e){return _(e.paths,`dispatch Native Supervisor children ${e.parent}`,async()=>{let t=await O(e.paths,e.parent);if(!t)throw new Error(`Native Supervisor state is missing for ${e.parent}`);let r=e.maxParallel??2;if(!Number.isSafeInteger(r)||r<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let i=t.children.filter(({task:l})=>l!==null).length,n=Math.max(0,r-i);if(n===0)return{state:t,tasks:[]};let a=await _e(e.paths.projectRoot),o=t,s=[],c=!1;for(let l of t.children){if(s.length>=n)break;if(l.task!==null)continue;let u=l.status==="needs-reverify"&&l.candidateCommit!==null;if(l.status!=="ready"&&!u)continue;let f;try{f=await Jp({projectRoot:e.paths.projectRoot,parent:t.parent,child:l.name,targetBranch:t.integration.branch,sourceConfig:a}),u?IN(f.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,l.candidateCommit):AN(f.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,t.integration.headCommit)}catch(p){let m=Ve(o),h=m.children.find(({name:g})=>g===l.name);h&&(h.blocker=p.message,Ue(m,{kind:"task-blocked",child:l.name,runId:null,summary:h.blocker}),m.stateVersion+=1,o=m,c=!0);continue}let d=Ga(o,{role:u?"verifier":"builder",child:l.name,projectRoot:f.projectRoot,runId:wj()});o=d.state,s.push(d.task)}return(s.length>0||c)&&await q(e.paths,o),{state:o,tasks:s}})}function TN(e,t){if(ft(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=Ve(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function Ii(e){let t=Ro(e);if(t===e.integration.headCommit)return e;try{I(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let r=Ve(e);return r.integration.headCommit=t,Ue(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function Ti(e,t){let r=t.verification;if(r===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let i=Ro(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=r.checks.length>0&&r.checks.every(({status:o})=>o==="passed");return TN(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}function Kp(e,t){let r=_t.normalize(_t.resolve(e)),i=_t.normalize(_t.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function bj(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function kj(e){let t=bj(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function _o(e){try{let t=await Q({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return kj(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function An(e){return T("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function Sj(e){let t=nr(e.projectRoot);t.some(i=>Kp(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>_t.resolve(n)))]){let n=await _e(i);n&&r.push({projectRoot:i,paths:await Dr(i,n.native.artifact_root),parent:Kp(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function Ej(e,t){let r=_t.join(e.paths.changesDir,t,"comet-state.yaml");try{return await lt(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function xj(e,t){let r;try{r=await Nj.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=_t.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await lt(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function Cj(e,t,r){let i=_t.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${_t.sep}`))return null;let n=i.split(_t.sep).join("/");try{let a=(0,$N.parseDocument)(I(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:B(a.toJS({mapAsMap:!1}))}catch{return null}}function Rj(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function jN(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function je(e){let t=_t.join(e.paths.changesDir,e.state.name),r=await _o(t),i=null,n;try{n=await Fe({changeDir:t,validation:dt(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:v})=>v)}:{},policy:"advisory"})}catch(v){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${v.message}`,n=null}if(!n){let v=await O(e.paths,e.state.name,{diagnostics:!0});if(v){let w=Oc(v);return{...w,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(y=>({...y,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=An({acceptance:e.state.acceptance,children:n.contract}),o=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&e.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===Br){let v=await O(e.paths,e.state.name,{diagnostics:!0});if(!v){let b=e.state.workspace.change_branch??e.state.workspace.target_branch;if(b){let S=await Po({paths:e.paths,parent:e.state.name,targetBranch:b,contract:n.contract});S&&(v=S,await q(e.paths,S))}}if(v){let b=Oc(v);return e.state.children_contract_hash!==a||n.drift?{...b,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:b.children.map(S=>({...S,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...b,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&b.confirmed}}let w=new Map(n.contract.children.map(b=>[b.name,b])),y=n.contract.children.map(b=>({name:b.name,summary:b.summary,dependsOn:[...b.depends_on],covers:[],status:s&&b.depends_on.every(S=>n.contract.children.filter(({name:N})=>N!==b.name).every(({name:N})=>N!==S))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let b of y){if(b.status!=="ready")continue;w.get(b.name).depends_on.length>0&&(b.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:y,readyChildren:y.filter(({status:b})=>b==="ready").map(({name:b})=>b),allDone:!1}}let c=await Sj(e.paths),l=new Set(n.contract.children.map(({name:v})=>v)),u=new Map,f=new Map;for(let v of c){let w=v.parent&&o?`refs/heads/${o}`:"HEAD";for(let y of await xj(v,l)){let b={...y,source:v,committedState:Cj(v,y.file,w)};u.set(y.state.name,[...u.get(y.state.name)??[],b])}for(let y of l){let b=await Ej(v,y);b&&f.set(y,[...f.get(y)??[],{source:v,state:b}])}}let d=new Map;for(let v of n.contract.children){let w=(u.get(v.name)??[]).find(({source:S,committedState:N})=>S.parent&&N?.name===v.name&&jN(N,o));if(w){d.set(v.name,{kind:"done",phase:w.state.phase,projectRoot:w.source.projectRoot,message:null});continue}let y=u.get(v.name)?.[0];if(y){d.set(v.name,{kind:"blocked",phase:y.state.phase,projectRoot:y.source.projectRoot,message:`Native child ${v.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let b=f.get(v.name)??[];b.length>1?d.set(v.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${v.name} has multiple active workspace owners`}):b[0]&&d.set(v.name,Rj(b[0].state,b[0].source,o))}let p=new Map(n.contract.children.map(v=>[v.name,v])),m=new Map,h=v=>{let w=m.get(v);if(w)return w;let y=p.get(v),S=y.depends_on.map(h).every(({status:H})=>H==="done"),N=d.get(v),x=N?.kind==="active"&&S?y.depends_on.filter(H=>!(u.get(H)??[]).some(({source:P,committedState:W})=>Kp(P.projectRoot,N.projectRoot)&&W?.name===H&&jN(W,o))):[],k,E=N?.message??null;N?.kind==="done"?(k=S?"done":"blocked",S||(E=`Native child ${v} was merged before its dependencies`)):N?.kind==="active"?(k=S&&x.length===0?"active":"blocked",S?x.length>0&&(E=`Native child ${v} does not include merged dependencies: ${x.join(", ")}`):E=`Native child ${v} started before its dependencies merged`):N?.kind==="blocked"?k="blocked":(k=s&&S?"ready":"pending",s||(E="Parent Shape confirmation is required"));let C={name:v,summary:y.summary,dependsOn:[...y.depends_on],covers:[...y.covers],status:k,phase:N?.phase??null,projectRoot:N?.projectRoot??null,message:E};return m.set(v,C),C},g=n.contract.children.map(({name:v})=>h(v));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:g,readyChildren:g.filter(({status:v})=>v==="ready").map(({name:v})=>v),allDone:g.every(({status:v})=>v==="done")}}cn();gi();function $e(e,t,r){return e.language==="zh-CN"?r:t}function Pj(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:$e(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:$e(e,"Reply A or B","回复 A 或 B"),agentInstruction:$e(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($e(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($e(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:$e(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:$e(e,"Accept the result","接受结果"),agentInstruction:$e(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)>=cr)??!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($e(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($e(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 _j(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 Aj(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:$e(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:$e(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function BN(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function ji(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function ON(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function Ij(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function HN(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function Tj(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function jj(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 Ur(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:BN({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[ji("summary","--summary"),Ij(e.name,e.flag)]}}function DN(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:$e(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function $j(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function Bl(e){return[Ur({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Ur({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Oj(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 K(e,t,r={}){let i=Tj(t)&&e.coordination_mode===void 0,n=Pj(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:[ji("summary","--summary")],commandAlternatives:[Ur({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:[ji("summary","--summary")],commandAlternatives:[Ur({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Bl({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:[ji("summary","--summary")],commandAlternatives:[Ur({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Ur({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:[ji("summary","--summary")],commandAlternatives:[Ur({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Bl({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:[ji("summary","--summary")],commandAlternatives:Bl({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:Bl({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?BN({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:jj({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?[HN("coordination-mode","--coordination-mode",Nc)]:[]],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:[ON()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:m})=>m==="verified");if(s){let m=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}],...m&&m.length>0?{retry_check_ids:[...m]}:{}}}],runnerAction:o("none")}}let c=t.children.some(({status:m})=>m==="blocked"||m==="needs-reverify"),l=t.children.some(({status:m})=>m==="needs-reverify"),u=t.children.some(({status:m})=>m==="ready"||m==="active"),f=t.supervisorStateVersion===void 0?null:t.children.find(m=>m.status==="blocked"&&(m.builderFailureCount??0)>=cr)??null,d=f===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:f.name,stateVersion:t.supervisorStateVersion},description:$e(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},p=c&&!l&&!u&&d===null;return{...a,disposition:p?"blocked":"continue",action:"advance-children",commandArgs:p?null:d!==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?[]:d!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:p?[]:d!==null?[d]:[ji("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=ON();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} ${$e(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:Oj([{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=DN(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(f=>$j(f))?{...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:DN(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:[HN("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...Aj(e)],userCommunication:_j(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Ur({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")}}rt();Xa();fe();gn();import{createHash as bb,randomUUID as kb}from"node:crypto";import{promises as Qt}from"node:fs";import Zr from"node:os";import j from"node:path";ut();Fr();mi();Ma();import{randomUUID as Hj}from"node:crypto";var Ao=3,Yp=2;function Oe(e){return e.state_version+1}function Dj(e,t,r){let i=[...e];if(new Set(i).size!==i.length)throw new Error(`${r} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${r} contains unknown IDs: ${a.join(", ")}`);return i}function LN(e){return e.map(t=>({...t,result:"pending",reason:null}))}function Xp(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function Bj(e){return(e??[]).map(t=>({name:J(t.name),result:t.result,note:t.note?J(t.note):null}))}function Kr(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:J(e.summary),completed_at:e.completedAt}}function qN(e){let t=B(e.state);if(t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native acceptance can only be confirmed from the persisted Shape confirmation boundary");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return B({...t,phase:"build",status:"active",state_version:Oe(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function FN(e){let t=B(e.state);if(t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return B({...t,status:"await-user",state_version:Oe(t),loop:{...t.loop,stage:"await-user",next_action:"confirm-shape"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function VN(e){let t=B(e.state),{input:r}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!mw(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(r.review){if(r.review.status!=="passed")throw new Error("Native Builder review status must be passed when supplied");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}let i=Dj(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=LN(t.acceptance),a=(r.now??new Date).toISOString();return B({...t,phase:"verify",state_version:Oe(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:n,builder_handoff:{candidate_id:r.candidateId??Hj(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:J(r.summary),addressed_acceptance_ids:i,checks:Bj(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(o=>J(o)),known_limits_truncated:!1,review:r.review?{status:"passed",summary:J(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef}:null,submitted_at:a},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function MN(e){let t=B(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null)throw new Error("Native Verifier attempt requires a current Builder candidate");return B({...t,state_version:Oe(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function Lj(e,t){let r=e.loop.previous_unresolved_ids;if(r.length===0)return 0;let i=new Set(r),n=new Set(t);return n.size<i.size&&[...n].every(o=>i.has(o))?0:e.loop.no_progress_count+1}function qj(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===Ne?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:J(e.response.result.summary),risks:e.response.result.risks.map(t=>J(t)),risks_truncated:!1,completed_at:e.completedAt}}function WN(e){let t=B(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let r=Xp(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let i=vw({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,knownAcceptanceIds:t.acceptance.map(({id:g})=>g),previouslyPassedAcceptanceIds:t.acceptance.filter(({result:g})=>g==="passed").map(({id:g})=>g),requiredChecksPassed:e.checks.every(({status:g})=>g==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let n=(e.now??new Date).toISOString(),a=new Map(i.result.acceptance.map(g=>[g.id,g])),o=t.acceptance.map(g=>{let v=a.get(g.id);return v?{...g,result:v.result,reason:J(v.reason)}:g}),s=o.filter(({result:g})=>g==="failed"||g==="blocked").map(({id:g})=>g),c=qj({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:n});if(i.result.verdict==="pass"){let g=ye({...t,acceptance:o,verification:c},Kr({state:t,outcome:"pass",summary:i.result.summary,completedAt:n})),v=t.builder_handoff.identity_provider===Ne;return{response:i,state:B({...g,phase:v?"verify":"archive",status:v?"await-user":"active",state_version:Oe(t),verification_result:"pass",verification_report:"verification.md",blockers:v?[{owner:"user",reason:J("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:v?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:v?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let g=ye({...t,acceptance:o,verification:c},Kr({state:t,outcome:"blocked",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:B({...g,status:"await-user",state_version:Oe(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:J(i.result.summary),acceptance_ids:s,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:s,next_action:"resolve-verifier-blocker"}})}}let l=t.loop.failed_iteration_count+1,u=Lj(t,s),f=l>=e.maxVerifyFailures,d=u>=3,p=f||d,m=d?"stalled":f?"budget":void 0,h=ye({...t,acceptance:o,verification:c},Kr({state:t,outcome:"fail",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:B({...h,phase:p?"verify":"build",status:p?"await-user":"active",state_version:Oe(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:p?[{owner:"user",reason:J(m==="budget"?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:s,resolution_action:"await-user"}]:u>=2?[{owner:"builder",reason:J("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:s,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:p?"await-user":"repairing",iteration:p?t.loop.iteration:t.loop.iteration+1,attempt:p?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:u,...m===void 0?{}:{stop_reason:m},execution_failure_count:0,previous_unresolved_ids:s,next_action:p?"await-user":"repair-failed-acceptance"}})}}function zN(e){let t=B(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==Ne||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return B({...t,phase:"archive",status:"active",state_version:Oe(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function JN(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==Ne||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let r=(e.now??new Date).toISOString(),i=Xp(t),n=ye(t,Kr({state:t,outcome:"blocked",unresolvedIds:i,summary:e.summary,completedAt:r}));return B({...n,status:"await-user",state_version:Oe(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:J(e.summary),risks:[J("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:r},blockers:[{owner:"user",reason:J("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:i,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:i,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function GN(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let r=(e.now??new Date).toISOString(),i=J(e.summary),n=ye(t,Kr({state:t,outcome:"pass",summary:e.summary,completedAt:r}));return B({...n,phase:"archive",status:"active",state_version:Oe(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:i,completed_at:r},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:J(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function UN(e,t){let r=B(e);if(r.phase!=="verify"||r.status!=="await-user"||r.verification_result!=="blocked"||r.verification?.verdict!=="blocked"||r.verification.assurance==="semantic-verification-unavailable"||r.loop.stage!=="await-user"||r.loop.next_action!=="resolve-verifier-blocker"||!r.blockers.some(({resolution_action:n})=>n==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");let i=ye(r,Kr({state:r,outcome:"recovery",summary:t?.reason??"Resolved the semantic Verifier blocker and resumed verification.",completedAt:(t?.now??new Date).toISOString()}));return B({...i,status:"active",state_version:Oe(r),verification_result:"pending",verification_report:null,verification:null,acceptance:r.acceptance.map(n=>n.result==="failed"||n.result==="blocked"?{...n,result:"pending",reason:null}:n),blockers:[],loop:{...r.loop,stage:"verify-ready",retry_epoch:r.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function KN(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let r=(e.now??new Date).toISOString(),i=t.loop.execution_failure_count+1,n=i>=Ao,a=ye(t,Kr({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return B({...a,status:n?"blocked":"active",state_version:Oe(t),blockers:n?[{owner:"runtime",reason:J(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:i,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function YN(e){let t=B(e),r=t.status==="blocked"&&t.blockers.some(({resolution_action:o})=>o==="retry-verifier"),i=t.status==="await-user"&&t.verification_result==="blocked"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.stage==="await-user"&&t.loop.next_action==="confirm-verifier-unavailable"&&t.blockers.some(({resolution_action:o})=>o==="confirm-verifier-unavailable");if(t.phase!=="verify"||!r&&!i)throw new Error("Native change is not blocked on Verifier infrastructure");let n=Xp(t),a=t.acceptance.some(({result:o})=>o==="passed");return B({...t,status:"active",state_version:Oe(t),...i?{verification_result:"pending",verification_report:null,verification:null}:{},blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,...i?{previous_unresolved_ids:a?n:[]}:{},next_action:"dispatch-new-verifier"}})}function Yr(e){let t=B(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=e.failureBudget,i=r?t.loop.failed_iteration_count+1:t.loop.failed_iteration_count,n=r!==void 0&&i>=r.maxVerifyFailures,a=(e.now??new Date).toISOString(),o=ye(t,Kr({state:t,outcome:"recovery",summary:e.reason,completedAt:a})),s=new Set(t.loop.previous_unresolved_ids),c=s.size===0?LN(t.acceptance):t.acceptance.map(l=>s.has(l.id)?{...l,result:"pending",reason:null}:l);return n?B({...o,phase:"verify",status:"await-user",state_version:Oe(t),verification_result:"fail",builder_handoff:t.builder_handoff,blockers:[{owner:"user",reason:J(`Native Runtime checks failed at Builder handoff and reached the configured failed iteration limit: ${e.reason}`),acceptance_ids:[...s],resolution_action:"await-user"}],loop:{...t.loop,stage:"await-user",failed_iteration_count:i,execution_failure_count:0,stop_reason:"budget",next_action:"resolve-loop-stop"}}):B({...o,phase:"build",status:"active",state_version:Oe(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:c,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,failed_iteration_count:i,stop_reason:void 0,next_action:"submit-builder-candidate"}})}ne();cn();import{promises as XN}from"node:fs";import Fj from"node:os";import jo from"node:path";function Io(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function To(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 He(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 In(e,t){return e===null?null:He(e,t)}function Tn(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 Vj(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 Mj(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function jn(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Qp(e,t){if(e===null)return null;let r=He(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Wj(e,t){let r=He(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Zp(e,t){let r=He(e,t);if(!jo.isAbsolute(r))throw new Error(`${t} must be absolute`);return jo.resolve(r)}function zj(e,t){let r=`Native local checks[${t}]`,i=Io(e,r);if(To(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,f)=>He(u,`${r}.argv[${f}]`,!0)),a=jn(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Qp(i.startedAt,`${r}.startedAt`),s=Qp(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=Tn(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=Io(i.activeProcess,`${r}.activeProcess`),f=jn(u.status,["starting","running"],`${r}.activeProcess.status`);if(To(u,new Set(["status","pid","identity"]),`${r}.activeProcess`),f==="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:Tn(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:He(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:He(i.id,`${r}.id`),name:He(i.name,`${r}.name`),operationId:He(i.operationId,`${r}.operationId`),status:a,repeatable:Mj(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:Tn(i.executionCount,`${r}.executionCount`),argv:n,cwd:Zp(i.cwd,`${r}.cwd`),exitCode:Vj(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:He(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:jn(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:He(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function eh(e){let t="Native local execution state",r=Io(e,t);if(To(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==Da)throw new Error(`Native local execution schema must be ${Da}`);let i=Io(r.workspace,"Native local workspace");To(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Io(r.execution,"Native local execution");To(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=Qp(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:He(o.operationId,"Native local execution.operationId"),stage:jn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:jn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:In(o.executionId,"Native local execution.executionId"),status:jn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Tn(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:Wj(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:Tn(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:He(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(zj);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:Da,change:He(r.change,"Native local change"),basedOnStateVersion:Tn(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:In(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:In(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:In(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:In(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Zp(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Zp(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:In(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:He(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}function re(e){return eh({schema:Da,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:jo.resolve(e.projectRoot),worktreeRoot:jo.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null,machineId:Fj.hostname()},execution:null,checks:[]})}async function Se(e){let t;try{t=await XN.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 eh(r)}function QN(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 F(e,t,r={}){let i=eh(t);await XN.mkdir(jo.dirname(e),{recursive:!0}),await we(e,i,r)}async function Ll(e){let t=null,r=null;try{t=await Se(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=re(e);return await F(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}le();Fr();te();async function th(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}import{promises as ZN}from"node:fs";import ql from"node:path";rt();ut();te();var rh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,eb="comet-state.yaml",tb="state.json";function se(e,t){if(!rh.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=ql.join(e.changesDir,t);if(!be(e.changesDir,r))throw new Error("Native change path escaped");return r}function Qe(e,t){return ql.join(se(e,t),eb)}function D(e,t){return ql.join(pe(e,t),tb)}async function $n(e,t){try{let r=await ZN.readFile(Qe(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function ve(e){return Tg(e)}function Fl(e,t){let r=ie(t);if(!r.isGitWorktree||r.currentBranch===null||ar(t,r.currentBranch)===null)return null;if(!Zs(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}}async function $(e,t){return lt(Qe(e,t))}async function ce(e){let t=await dn({file:Qe(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=ql.join(se(e.paths,t.name),"verification.md");await z(e.paths.nativeRoot,r),await ZN.rm(r,{force:!0})}return t}async function ih(e){let t=await $(e.paths,e.name),r=D(e.paths,e.name);try{let i=await Se(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"}}}ne();import{promises as zl}from"node:fs";import $i from"node:path";xi();var ah=br(rr(),1);import Ho from"path";nt();ne();xi();st();le();te();Mt();po();le();te();nn();$r();var Xj=br(rr(),1);nn();$r();Hr();Hr();rn();hf();nn();Hr();var gM=4*1024*1024;var Qj=null;function Zj(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function rb(e,t){return(...r)=>{let i=Qj;if(i===null)return t(...r);let n=Zj(`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}}rn();var kM=rb("hookWritePolicy",async e=>(await nf(e))?.hook??{allow_paths:[]});Ta();var e$=16*1024;ff();Ea();var k1=Number.MAX_SAFE_INTEGER;ne();Dt();var O1={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};import On from"node:path";ne();nt();le();te();var $o=/^[a-f0-9]{64}$/u,nb=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,s$=16*1024,Y1=process.platform;function c$(e,t){let r=On.relative(e,t);return On.isAbsolute(r)||r===".."||r.startsWith(`..${On.sep}`)?null:r.replaceAll("\\","/")||"."}function ab(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function ob(e,t){if(e.length===0||ab(e)||e.includes("\\")||On.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=On.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function l$(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 nh(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||ab(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function u$(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(nh(e.changeBranch,"Native workspace change branch"),nh(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 d$(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"||!nb.test(t.baseCommit)||typeof t.targetCommit!="string"||!nb.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");nh(t.targetBranch,"Native workspace Git target branch")}function f$(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"||!$o.test(String(t.projectRootId))||!$o.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");l$(t.capturedAt),ob(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&&!$o.test(String(t.projectRootPathId))||a&&!$o.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!$o.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&d$(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(u$(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 p$(e,t){return On.join(ot(e,t),"workspace.json")}function h$(e,t){let r=p$(e,t),i=qe(e,r),n=c$(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:ob(n,"Native workspace file ref")}}async function m$(e,t){try{let r=h$(e,t),i=await Q({root:r.root,ref:r.ref,maxBytes:s$});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Oo(e,t){let r=await m$(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(f$(r),r)}no();Yc();Yc();var Vl=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"},Do=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"},Ml=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"},SW=Qc("en");function At(e,t){co(t);let r=Ho.join(e.changesDir,t);if(!be(e.changesDir,r))throw new Error("Native change path escaped");return r}async function y$(e,t=Ho.dirname(e)){let r=Ho.relative(t,e).split(Ho.sep).join("/"),i=await Q({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,ah.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 sb(e,t){let r=Ho.join(At(e,t),fr);await z(e.nativeRoot,r);let i=ip(await y$(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}nt();Jt();te();var lb=["outcome","scope","nonGoals","acceptanceExamples"],cb=[...lb,"constraints","decisions","openQuestions","verificationExpectations"];var b$=new Set(["nonGoals","decisions","openQuestions"]),k$={maxFileBytes:Kd};function S$(e){let t=new Map,r=null,i=[],n=()=>{r!==null&&t.set(r,i.join(`
|
|
219
|
+
`,"utf8"),!0}function PI(e,t,r){let i=ze.resolve(e,r??ze.join(".worktrees",t)),n=ze.resolve(e,I(e,["rev-parse","--git-common-dir"]));if(Fy(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(nr(e).some(a=>Ki(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function _I(e){try{throw await fo.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function qy(e){try{return await fo.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Np(e){let t=ze.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=ie(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await Dr(t,e.sourceConfig?.native.artifact_root??"docs");return Bw([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=ie(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;Gd(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(Gd(t,o),!Yi(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let p=!1;if(!a){if(!Zs(t))throw new Error("Native branch isolation requires a clean current working directory");if(Yi(t,n))throw new Error(`Native change branch already exists: ${n}`);I(t,["switch","-c",n,o]),p=!0}let m;try{m=await kl(t,e.sourceConfig)}catch(h){throw new Vr(`Native branch preparation is incomplete: ${h.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let p=e.worktreePath?ze.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!Ki(p,i.currentWorktreeRoot))throw new Error(`Native worktree path ${p} does not match the current worktree ${i.currentWorktreeRoot}`);let m;try{m=await kl(t,e.sourceConfig)}catch(h){throw new Vr(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}let s=Qs(i.primaryWorktreeRoot),c=s.find(p=>p.branch===n);if(c&&await qy(c.root)){let p=e.worktreePath?ze.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!Ki(p,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let m;try{m=await kl(c.root,e.sourceConfig)}catch(h){throw new Vr(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}c&&!await qy(c.root)&&(I(i.primaryWorktreeRoot,["worktree","prune"]),s=Qs(i.primaryWorktreeRoot));let l=Yi(t,n);if(s.some(p=>p.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=PI(i.primaryWorktreeRoot,e.name,e.worktreePath);await _I(u);let f=await RI(i.primaryWorktreeRoot,u),d={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:f,configInitialized:!1};try{I(i.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),d.createdBranch=!l,d.createdWorktree=!0,d.configInitialized=await kl(u,e.sourceConfig)}catch(p){throw new Vr(`Native worktree preparation is incomplete: ${p.message}`,d,{cause:p})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:d}})}function Dl(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}async function zp(e){let t=Hl.join(".worktrees",`${e.parent}-integration`);return Np({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:Dl(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function Jp(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.parent)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.child))throw new Error("Native Supervisor parent and child names are invalid");return Np({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:Hl.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function vj(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 gj(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}`)}}function AN(e,t,r){let i=ie(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor child worktree identity is not ${t}`);if(!zt(e))throw new Error(`Native Supervisor child worktree is not clean: ${e}`);let n=I(e,["rev-parse","HEAD"]);if(n===r)return;if(!(()=>{try{return I(e,["merge-base","--is-ancestor",n,r]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} cannot be refreshed from integration HEAD`);if((()=>{try{return I(e,["merge-base","--is-ancestor",r,n]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} contains unintegrated commits`);if(I(e,["merge","--ff-only",r]),I(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor child worktree did not reach integration HEAD")}function Ro(e){if(!zt(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=I(e.integration.worktree,["rev-parse","--show-toplevel"]);if(Hl.resolve(t)!==Hl.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=I(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return I(e.integration.worktree,["rev-parse","HEAD"])}function IN(e,t,r){let i=ie(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor Verifier worktree identity is not ${t}`);if(!zt(e))throw new Error(`Native Supervisor Verifier worktree is not clean: ${e}`);if(I(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor Verifier worktree is not at its candidate commit")}async function Gp(e){let t=vj(e.retryCheckIds),r=await _(e.paths,`integrate Native Supervisor child ${e.name}`,async()=>{let p=await O(e.paths,e.state.parent)??e.state,m=p.integration.checkExecution;if(m?.status==="running"){if(await mn(m.ownerPid,m.ownerIdentity))throw new Error("Native Supervisor integration checks are already running; wait for the original execution");if(m.activeProcess===void 0||m.activeProcess?.status==="starting")throw new Error("Native Supervisor integration check launch was interrupted; inspect the original check process before retrying");if(m.activeProcess&&await mn(m.activeProcess.pid,m.activeProcess.identity))throw new Error("Native Supervisor integration check process is still running after its owner stopped; wait for that process before retrying")}if(p.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before integration; reload status first");let h=p.children.find(({name:S})=>S===e.name);if(!h)throw new Error(`Native Supervisor child ${e.name} does not exist`);let g=gw(p).find(({status:S})=>S!=="integrated"&&S!=="archived");if(g&&g.name!==e.name)throw new Error(`Native Supervisor integration order requires ${g.name} before ${e.name}`);if(h.status!=="verified"||!h.verifiedCommit)throw new Error(`Native Supervisor child ${e.name} must be verified before integration`);if(e.checkPlans){if(e.checkPlans.some(({repeatable:x})=>!x))throw new Error("Native Supervisor integration checks must be repeatable for safe recovery");if(e.checkPlans.length===0||new Set(e.checkPlans.map(({id:x})=>x)).size!==e.checkPlans.length)throw new Error("Native Supervisor integration requires non-empty checks with unique IDs");if(Ye(p.integration.worktree,e.checkPlans),!h.verification?.receiptRef||!h.verification.execution)throw new Error("Native Supervisor integration requires current Runtime verification evidence; reverify the child");let{readNativeSupervisorCheckEvidence:S}=await Promise.resolve().then(()=>(Wp(),_N)),N=await S({paths:e.paths,parent:p.parent,task:h.verification.execution,receiptRef:h.verification.receiptRef});if(N.candidateCommit!==h.verifiedCommit||N.checks.some(({status:x})=>x!=="passed"))throw new Error("Native Supervisor integration verification evidence is stale or failed")}let v=Ro(p),w=e.checkPlans!==void 0&&m?.status==="interrupted"&&m.child===e.name&&m.candidateCommit===h.verifiedCommit&&v!==p.integration.headCommit&&v===m.integrationCommit;if(v!==p.integration.headCommit){let S=(()=>{try{return I(p.integration.worktree,["merge-base","--is-ancestor",p.integration.headCommit,v]),!0}catch{return!1}})(),N=(()=>{try{return I(p.integration.worktree,["merge-base","--is-ancestor",h.verifiedCommit,v]),!0}catch{return!1}})();if(!S||!N)throw new Error(`Native Supervisor integration head drifted: expected ${p.integration.headCommit}, got ${v}`)}try{I(p.integration.worktree,["cat-file","-e",`${h.verifiedCommit}^{commit}`])}catch(S){throw new Error(`Native Supervisor verified commit is unavailable: ${h.verifiedCommit}`,{cause:S})}if(v===p.integration.headCommit&&!w){try{I(p.integration.worktree,["merge","--no-ff","--no-edit",h.verifiedCommit])}catch(S){throw new Error(`Native Supervisor integration conflict preserved in ${p.integration.worktree}`,{cause:S})}v=I(p.integration.worktree,["rev-parse","HEAD"])}let y=v;if(e.checkPlans){let S=yl(),N=await wl({kind:"integration",parent:p.parent,child:e.name,runId:h.verification?.execution?.runId??`integration:${e.name}`,projectRoot:p.integration.worktree,candidateCommit:h.verifiedCommit,integrationCommit:y,contractHash:h.contractHash??null,plans:e.checkPlans,materials:[]}),x=T("comet.native.supervisor-integration-plan.v2",{machineId:S,inputFingerprint:N}),k=m?.key===x&&m.machineId===S&&m.inputFingerprint===N&&m.child===e.name&&m.candidateCommit===h.verifiedCommit&&m.integrationCommit===y;if(t){if(!k||m?.status!=="interrupted")throw new Error("Native Supervisor integration retry requires the interrupted current plan on the same candidate, machine and workspace");gj(m.checkStates,e.checkPlans,t)}else if(m?.status==="interrupted"&&k){let P=(m.checkStates??[]).filter(({status:W})=>W==="failed");if(P.length>0)throw new Error(`Native Supervisor integration checks already failed on the identical plan (${P.map(({id:W})=>W).join(", ")}); change the integration check plan or re-verify the child instead of rerunning the same integrate`);return{completed:p}}let E=t&&m?.checkStates?m.checkStates.map(P=>t.has(P.id)?{...P,status:"planned",exitCode:null,signal:null,timedOut:!1,durationMs:0,startedAt:null,completedAt:null,logRef:null}:{...P}):e.checkPlans.map(bn),C=e.checkPlans.map(P=>E.find(W=>W.id===P.id)??bn(P)),H=mj();return p.integration.checkExecution={operationId:H,key:x,child:e.name,candidateCommit:h.verifiedCommit,integrationCommit:y,status:"running",ownerPid:process.pid,ownerIdentity:await Ke(process.pid)??void 0,startedAt:new Date().toISOString(),activeProcess:null,machineId:S,inputFingerprint:N,checkStates:C},p.stateVersion+=1,await q(e.paths,p),{pending:{state:p,candidateCommit:h.verifiedCommit,integrationCommit:y,operationId:H,key:x,machineId:S,inputFingerprint:N,plansToExecute:e.checkPlans.filter(P=>!t||t.has(P.id))}}}let b=$c(p,{name:e.name,integrationCommit:y,checks:e.checks});return await q(e.paths,b),{completed:b}});if(r.completed)return r.completed;let{state:i,candidateCommit:n,integrationCommit:a,operationId:o,key:s}=r.pending,{writeNativeVerificationReportSnapshot:c}=await Promise.resolve().then(()=>(Gr(),RN)),{createHash:l}=await import("node:crypto"),u=async d=>_(e.paths,"record Supervisor integration check process",async()=>{let p=await O(e.paths,i.parent),m=p?.integration.checkExecution;if(!p||m?.operationId!==o||m.key!==s||m.status!=="running")throw new Error("Native Supervisor integration check operation is stale");if(d?.status==="starting"){let h=m.checkStates?.find(({id:g})=>g===d.checkId);if(!h||h.status!=="planned")throw new Error(`Native Supervisor check ${d.checkId} is not planned`);h.status="running",h.executionCount+=1,h.startedAt=new Date().toISOString(),h.completedAt=null,h.logRef=null}m.activeProcess=d,p.stateVersion+=1,await q(e.paths,p)}),f=async d=>_(e.paths,"record Supervisor integration check result",async()=>{let p=await O(e.paths,i.parent),m=p?.integration.checkExecution;if(!p||m?.operationId!==o||m.key!==s||m.status!=="running")throw new Error("Native Supervisor integration check operation is stale");let h=m.checkStates?.find(({id:g})=>g===d.id);if(!h)throw new Error(`Native Supervisor check state is missing: ${d.id}`);Object.assign(h,vl(h,d)),m.activeProcess=null,p.stateVersion+=1,await q(e.paths,p)});try{for(let b of r.pending.plansToExecute){await u({status:"starting",checkId:b.id});let S=await Ni({projectRoot:i.integration.worktree,runtimeDir:pe(e.paths,i.parent),operationId:o,plan:b,onSpawn:async({pid:N})=>u({status:"running",checkId:b.id,pid:N,identity:await Ke(N)??void 0})});if(await f(S),S.status==="interrupted")throw new Error(`Native Supervisor integration check ${S.id} was interrupted; retry only the listed repeatable check after the process has exited`)}let d=await O(e.paths,i.parent),m=d?.integration.checkExecution?.checkStates;if(!d||!m||m.some(({status:b})=>!["passed","failed"].includes(b)))throw new Error("Native Supervisor integration check plan remains incomplete; retry each interrupted check explicitly");let h=m.map(gl),g=JSON.stringify({schema:"comet.native.supervisor-integration-checks.v1",parent:i.parent,child:e.name,candidateCommit:n,integrationCommit:a,operationId:o,planHash:s,results:h}),v=await c({paths:e.paths,name:i.parent,hash:l("sha256").update(g).digest("hex"),text:g}),w=h.map(b=>({name:b.name,status:b.status==="interrupted"?"incomplete":b.status,reason:b.status==="passed"?null:b.timedOut?"timed out":`exit ${b.exitCode??b.signal??"interrupted"}`,receiptRef:v})),y=w.filter(({status:b})=>b!=="passed");return await _(e.paths,"complete Supervisor integration checks",async()=>{let b=await O(e.paths,i.parent),S=b?.children.find(({name:k})=>k===e.name),N=b?.integration.checkExecution;if(!b||!S||N?.operationId!==o||N.key!==s||N.status!=="running"||N.child!==e.name||N.candidateCommit!==n||N.integrationCommit!==a||S.verifiedCommit!==n||Ro(b)!==a)throw new Error("Native Supervisor integration changed during checks");if(N.receiptRef=v,N.checks=w,y.length>0){let k=`Native Supervisor integration checks did not pass (${y.map(({name:E,reason:C})=>`${E}: ${C}`).join("; ")}); receipt ${v}`;throw N.status="interrupted",N.error=k,S.blocker=k,b.stateVersion+=1,await q(e.paths,b),new Error(k)}N.status="completed";let x=$c(b,{name:e.name,integrationCommit:a,checks:w});return await q(e.paths,x),x})}catch(d){throw await _(e.paths,"interrupt Supervisor integration checks",async()=>{let p=await O(e.paths,i.parent),m=p?.integration.checkExecution;if(p&&m?.operationId===o&&m.key===s&&m.status==="running"){m.status="interrupted",m.error=d.message,m.activeProcess=null;for(let h of m.checkStates??[])(h.status==="planned"||h.status==="running")&&(h.status="interrupted");p.stateVersion+=1,await q(e.paths,p)}}),d}}import{randomUUID as wj}from"node:crypto";import yj from"node:path";rt();st();le();gi();lr();async function Po(e){let t=Dl(e.parent),r=ar(e.paths.projectRoot,t);if(!r)return null;let i=ar(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=nr(e.paths.projectRoot).map(o=>yj.resolve(o)).find(o=>ie(o).currentBranch===t);if(!n)return null;let a=Ja({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return Ue(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}async function Up(e){return _(e.paths,`dispatch Native Supervisor children ${e.parent}`,async()=>{let t=await O(e.paths,e.parent);if(!t)throw new Error(`Native Supervisor state is missing for ${e.parent}`);let r=e.maxParallel??2;if(!Number.isSafeInteger(r)||r<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let i=t.children.filter(({task:l})=>l!==null).length,n=Math.max(0,r-i);if(n===0)return{state:t,tasks:[]};let a=await _e(e.paths.projectRoot),o=t,s=[],c=!1;for(let l of t.children){if(s.length>=n)break;if(l.task!==null)continue;let u=l.status==="needs-reverify"&&l.candidateCommit!==null;if(l.status!=="ready"&&!u)continue;let f;try{f=await Jp({projectRoot:e.paths.projectRoot,parent:t.parent,child:l.name,targetBranch:t.integration.branch,sourceConfig:a}),u?IN(f.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,l.candidateCommit):AN(f.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,t.integration.headCommit)}catch(p){let m=Ve(o),h=m.children.find(({name:g})=>g===l.name);h&&(h.blocker=p.message,Ue(m,{kind:"task-blocked",child:l.name,runId:null,summary:h.blocker}),m.stateVersion+=1,o=m,c=!0);continue}let d=Ga(o,{role:u?"verifier":"builder",child:l.name,projectRoot:f.projectRoot,runId:wj()});o=d.state,s.push(d.task)}return(s.length>0||c)&&await q(e.paths,o),{state:o,tasks:s}})}function TN(e,t){if(ft(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=Ve(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function Ii(e){let t=Ro(e);if(t===e.integration.headCommit)return e;try{I(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let r=Ve(e);return r.integration.headCommit=t,Ue(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function Ti(e,t){let r=t.verification;if(r===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let i=Ro(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=r.checks.length>0&&r.checks.every(({status:o})=>o==="passed");return TN(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}function Kp(e,t){let r=_t.normalize(_t.resolve(e)),i=_t.normalize(_t.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function bj(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function kj(e){let t=bj(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function _o(e){try{let t=await Q({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return kj(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function An(e){return T("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function Sj(e){let t=nr(e.projectRoot);t.some(i=>Kp(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>_t.resolve(n)))]){let n=await _e(i);n&&r.push({projectRoot:i,paths:await Dr(i,n.native.artifact_root),parent:Kp(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function Ej(e,t){let r=_t.join(e.paths.changesDir,t,"comet-state.yaml");try{return await lt(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function xj(e,t){let r;try{r=await Nj.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=_t.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await lt(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function Cj(e,t,r){let i=_t.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${_t.sep}`))return null;let n=i.split(_t.sep).join("/");try{let a=(0,$N.parseDocument)(I(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:B(a.toJS({mapAsMap:!1}))}catch{return null}}function Rj(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function jN(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function je(e){let t=_t.join(e.paths.changesDir,e.state.name),r=await _o(t),i=null,n;try{n=await Fe({changeDir:t,validation:dt(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:v})=>v)}:{},policy:"advisory"})}catch(v){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${v.message}`,n=null}if(!n){let v=await O(e.paths,e.state.name,{diagnostics:!0});if(v){let w=Oc(v);return{...w,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(y=>({...y,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=An({acceptance:e.state.acceptance,children:n.contract}),o=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&e.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===Br){let v=await O(e.paths,e.state.name,{diagnostics:!0});if(!v){let b=e.state.workspace.change_branch??e.state.workspace.target_branch;if(b){let S=await Po({paths:e.paths,parent:e.state.name,targetBranch:b,contract:n.contract});S&&(v=S,await q(e.paths,S))}}if(v){let b=Oc(v);return e.state.children_contract_hash!==a||n.drift?{...b,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:b.children.map(S=>({...S,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...b,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&b.confirmed}}let w=new Map(n.contract.children.map(b=>[b.name,b])),y=n.contract.children.map(b=>({name:b.name,summary:b.summary,dependsOn:[...b.depends_on],covers:[],status:s&&b.depends_on.every(S=>n.contract.children.filter(({name:N})=>N!==b.name).every(({name:N})=>N!==S))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let b of y){if(b.status!=="ready")continue;w.get(b.name).depends_on.length>0&&(b.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:y,readyChildren:y.filter(({status:b})=>b==="ready").map(({name:b})=>b),allDone:!1}}let c=await Sj(e.paths),l=new Set(n.contract.children.map(({name:v})=>v)),u=new Map,f=new Map;for(let v of c){let w=v.parent&&o?`refs/heads/${o}`:"HEAD";for(let y of await xj(v,l)){let b={...y,source:v,committedState:Cj(v,y.file,w)};u.set(y.state.name,[...u.get(y.state.name)??[],b])}for(let y of l){let b=await Ej(v,y);b&&f.set(y,[...f.get(y)??[],{source:v,state:b}])}}let d=new Map;for(let v of n.contract.children){let w=(u.get(v.name)??[]).find(({source:S,committedState:N})=>S.parent&&N?.name===v.name&&jN(N,o));if(w){d.set(v.name,{kind:"done",phase:w.state.phase,projectRoot:w.source.projectRoot,message:null});continue}let y=u.get(v.name)?.[0];if(y){d.set(v.name,{kind:"blocked",phase:y.state.phase,projectRoot:y.source.projectRoot,message:`Native child ${v.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let b=f.get(v.name)??[];b.length>1?d.set(v.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${v.name} has multiple active workspace owners`}):b[0]&&d.set(v.name,Rj(b[0].state,b[0].source,o))}let p=new Map(n.contract.children.map(v=>[v.name,v])),m=new Map,h=v=>{let w=m.get(v);if(w)return w;let y=p.get(v),S=y.depends_on.map(h).every(({status:H})=>H==="done"),N=d.get(v),x=N?.kind==="active"&&S?y.depends_on.filter(H=>!(u.get(H)??[]).some(({source:P,committedState:W})=>Kp(P.projectRoot,N.projectRoot)&&W?.name===H&&jN(W,o))):[],k,E=N?.message??null;N?.kind==="done"?(k=S?"done":"blocked",S||(E=`Native child ${v} was merged before its dependencies`)):N?.kind==="active"?(k=S&&x.length===0?"active":"blocked",S?x.length>0&&(E=`Native child ${v} does not include merged dependencies: ${x.join(", ")}`):E=`Native child ${v} started before its dependencies merged`):N?.kind==="blocked"?k="blocked":(k=s&&S?"ready":"pending",s||(E="Parent Shape confirmation is required"));let C={name:v,summary:y.summary,dependsOn:[...y.depends_on],covers:[...y.covers],status:k,phase:N?.phase??null,projectRoot:N?.projectRoot??null,message:E};return m.set(v,C),C},g=n.contract.children.map(({name:v})=>h(v));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:g,readyChildren:g.filter(({status:v})=>v==="ready").map(({name:v})=>v),allDone:g.every(({status:v})=>v==="done")}}cn();gi();function $e(e,t,r){return e.language==="zh-CN"?r:t}function Pj(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:$e(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:$e(e,"Reply A or B","回复 A 或 B"),agentInstruction:$e(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($e(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($e(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:$e(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:$e(e,"Accept the result","接受结果"),agentInstruction:$e(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)>=cr)??!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($e(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($e(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 _j(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 Aj(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:$e(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:$e(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function BN(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function ji(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function ON(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function Ij(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function HN(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function Tj(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function jj(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 Ur(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:BN({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[ji("summary","--summary"),Ij(e.name,e.flag)]}}function DN(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:$e(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function $j(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function Bl(e){return[Ur({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Ur({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Oj(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 K(e,t,r={}){let i=Tj(t)&&e.coordination_mode===void 0,n=Pj(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:[ji("summary","--summary")],commandAlternatives:[Ur({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:[ji("summary","--summary")],commandAlternatives:[Ur({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Bl({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:[ji("summary","--summary")],commandAlternatives:[Ur({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Ur({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:[ji("summary","--summary")],commandAlternatives:[Ur({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Bl({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:[ji("summary","--summary")],commandAlternatives:Bl({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:Bl({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?BN({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:jj({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?[HN("coordination-mode","--coordination-mode",Nc)]:[]],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:[ON()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:m})=>m==="verified");if(s){let m=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}],...m&&m.length>0?{retry_check_ids:[...m]}:{}}}],runnerAction:o("none")}}let c=t.children.some(({status:m})=>m==="blocked"||m==="needs-reverify"),l=t.children.some(({status:m})=>m==="needs-reverify"),u=t.children.some(({status:m})=>m==="ready"||m==="active"),f=t.supervisorStateVersion===void 0?null:t.children.find(m=>m.status==="blocked"&&(m.builderFailureCount??0)>=cr)??null,d=f===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:f.name,stateVersion:t.supervisorStateVersion},description:$e(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},p=c&&!l&&!u&&d===null;return{...a,disposition:p?"blocked":"continue",action:"advance-children",commandArgs:p?null:d!==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?[]:d!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:p?[]:d!==null?[d]:[ji("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=ON();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} ${$e(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:Oj([{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=DN(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(f=>$j(f))?{...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:DN(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:[HN("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...Aj(e)],userCommunication:_j(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Ur({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")}}rt();Xa();fe();gn();import{createHash as bb,randomUUID as kb}from"node:crypto";import{promises as Qt}from"node:fs";import Zr from"node:os";import j from"node:path";ut();Fr();mi();Ma();import{randomUUID as Hj}from"node:crypto";var Ao=3,Yp=2;function Oe(e){return e.state_version+1}function Dj(e,t,r){let i=[...e];if(new Set(i).size!==i.length)throw new Error(`${r} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${r} contains unknown IDs: ${a.join(", ")}`);return i}function LN(e){return e.map(t=>({...t,result:"pending",reason:null}))}function Xp(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function Bj(e){return(e??[]).map(t=>({name:J(t.name),result:t.result,note:t.note?J(t.note):null}))}function Kr(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:J(e.summary),completed_at:e.completedAt}}function qN(e){let t=B(e.state);if(t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native acceptance can only be confirmed from the persisted Shape confirmation boundary");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return B({...t,phase:"build",status:"active",state_version:Oe(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function FN(e){let t=B(e.state);if(t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return B({...t,status:"await-user",state_version:Oe(t),loop:{...t.loop,stage:"await-user",next_action:"confirm-shape"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function VN(e){let t=B(e.state),{input:r}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!mw(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(r.review){if(r.review.status!=="passed")throw new Error("Native Builder review status must be passed when supplied");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}let i=Dj(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=LN(t.acceptance),a=(r.now??new Date).toISOString();return B({...t,phase:"verify",state_version:Oe(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:n,builder_handoff:{candidate_id:r.candidateId??Hj(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:J(r.summary),addressed_acceptance_ids:i,checks:Bj(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(o=>J(o)),known_limits_truncated:!1,review:r.review?{status:"passed",summary:J(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef}:null,submitted_at:a},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function MN(e){let t=B(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null)throw new Error("Native Verifier attempt requires a current Builder candidate");return B({...t,state_version:Oe(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function Lj(e,t){let r=e.loop.previous_unresolved_ids;if(r.length===0)return 0;let i=new Set(r),n=new Set(t);return n.size<i.size&&[...n].every(o=>i.has(o))?0:e.loop.no_progress_count+1}function qj(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===Ne?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:J(e.response.result.summary),risks:e.response.result.risks.map(t=>J(t)),risks_truncated:!1,completed_at:e.completedAt}}function WN(e){let t=B(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let r=Xp(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let i=vw({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,knownAcceptanceIds:t.acceptance.map(({id:g})=>g),previouslyPassedAcceptanceIds:t.acceptance.filter(({result:g})=>g==="passed").map(({id:g})=>g),requiredChecksPassed:e.checks.every(({status:g})=>g==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let n=(e.now??new Date).toISOString(),a=new Map(i.result.acceptance.map(g=>[g.id,g])),o=t.acceptance.map(g=>{let v=a.get(g.id);return v?{...g,result:v.result,reason:J(v.reason)}:g}),s=o.filter(({result:g})=>g==="failed"||g==="blocked").map(({id:g})=>g),c=qj({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:n});if(i.result.verdict==="pass"){let g=ye({...t,acceptance:o,verification:c},Kr({state:t,outcome:"pass",summary:i.result.summary,completedAt:n})),v=t.builder_handoff.identity_provider===Ne;return{response:i,state:B({...g,phase:v?"verify":"archive",status:v?"await-user":"active",state_version:Oe(t),verification_result:"pass",verification_report:"verification.md",blockers:v?[{owner:"user",reason:J("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:v?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:v?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let g=ye({...t,acceptance:o,verification:c},Kr({state:t,outcome:"blocked",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:B({...g,status:"await-user",state_version:Oe(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:J(i.result.summary),acceptance_ids:s,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:s,next_action:"resolve-verifier-blocker"}})}}let l=t.loop.failed_iteration_count+1,u=Lj(t,s),f=l>=e.maxVerifyFailures,d=u>=3,p=f||d,m=d?"stalled":f?"budget":void 0,h=ye({...t,acceptance:o,verification:c},Kr({state:t,outcome:"fail",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:B({...h,phase:p?"verify":"build",status:p?"await-user":"active",state_version:Oe(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:p?[{owner:"user",reason:J(m==="budget"?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:s,resolution_action:"await-user"}]:u>=2?[{owner:"builder",reason:J("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:s,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:p?"await-user":"repairing",iteration:p?t.loop.iteration:t.loop.iteration+1,attempt:p?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:u,...m===void 0?{}:{stop_reason:m},execution_failure_count:0,previous_unresolved_ids:s,next_action:p?"await-user":"repair-failed-acceptance"}})}}function zN(e){let t=B(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==Ne||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return B({...t,phase:"archive",status:"active",state_version:Oe(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function JN(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==Ne||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let r=(e.now??new Date).toISOString(),i=Xp(t),n=ye(t,Kr({state:t,outcome:"blocked",unresolvedIds:i,summary:e.summary,completedAt:r}));return B({...n,status:"await-user",state_version:Oe(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:J(e.summary),risks:[J("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:r},blockers:[{owner:"user",reason:J("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:i,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:i,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function GN(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let r=(e.now??new Date).toISOString(),i=J(e.summary),n=ye(t,Kr({state:t,outcome:"pass",summary:e.summary,completedAt:r}));return B({...n,phase:"archive",status:"active",state_version:Oe(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:i,completed_at:r},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:J(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function UN(e,t){let r=B(e);if(r.phase!=="verify"||r.status!=="await-user"||r.verification_result!=="blocked"||r.verification?.verdict!=="blocked"||r.verification.assurance==="semantic-verification-unavailable"||r.loop.stage!=="await-user"||r.loop.next_action!=="resolve-verifier-blocker"||!r.blockers.some(({resolution_action:n})=>n==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");let i=ye(r,Kr({state:r,outcome:"recovery",summary:t?.reason??"Resolved the semantic Verifier blocker and resumed verification.",completedAt:(t?.now??new Date).toISOString()}));return B({...i,status:"active",state_version:Oe(r),verification_result:"pending",verification_report:null,verification:null,acceptance:r.acceptance.map(n=>n.result==="failed"||n.result==="blocked"?{...n,result:"pending",reason:null}:n),blockers:[],loop:{...r.loop,stage:"verify-ready",retry_epoch:r.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function KN(e){let t=B(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let r=(e.now??new Date).toISOString(),i=t.loop.execution_failure_count+1,n=i>=Ao,a=ye(t,Kr({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return B({...a,status:n?"blocked":"active",state_version:Oe(t),blockers:n?[{owner:"runtime",reason:J(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:i,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function YN(e){let t=B(e),r=t.status==="blocked"&&t.blockers.some(({resolution_action:o})=>o==="retry-verifier"),i=t.status==="await-user"&&t.verification_result==="blocked"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.stage==="await-user"&&t.loop.next_action==="confirm-verifier-unavailable"&&t.blockers.some(({resolution_action:o})=>o==="confirm-verifier-unavailable");if(t.phase!=="verify"||!r&&!i)throw new Error("Native change is not blocked on Verifier infrastructure");let n=Xp(t),a=t.acceptance.some(({result:o})=>o==="passed");return B({...t,status:"active",state_version:Oe(t),...i?{verification_result:"pending",verification_report:null,verification:null}:{},blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,...i?{previous_unresolved_ids:a?n:[]}:{},next_action:"dispatch-new-verifier"}})}function Yr(e){let t=B(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=e.failureBudget,i=r?t.loop.failed_iteration_count+1:t.loop.failed_iteration_count,n=r!==void 0&&i>=r.maxVerifyFailures,a=(e.now??new Date).toISOString(),o=ye(t,Kr({state:t,outcome:"recovery",summary:e.reason,completedAt:a})),s=new Set(t.loop.previous_unresolved_ids),c=s.size===0?LN(t.acceptance):t.acceptance.map(l=>s.has(l.id)?{...l,result:"pending",reason:null}:l);return n?B({...o,phase:"verify",status:"await-user",state_version:Oe(t),verification_result:"fail",builder_handoff:t.builder_handoff,blockers:[{owner:"user",reason:J(`Native Runtime checks failed at Builder handoff and reached the configured failed iteration limit: ${e.reason}`),acceptance_ids:[...s],resolution_action:"await-user"}],loop:{...t.loop,stage:"await-user",failed_iteration_count:i,execution_failure_count:0,stop_reason:"budget",next_action:"resolve-loop-stop"}}):B({...o,phase:"build",status:"active",state_version:Oe(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:c,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,failed_iteration_count:i,stop_reason:void 0,next_action:"submit-builder-candidate"}})}ne();cn();import{promises as XN}from"node:fs";import Fj from"node:os";import jo from"node:path";function Io(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function To(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 He(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 In(e,t){return e===null?null:He(e,t)}function Tn(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 Vj(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 Mj(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function jn(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Qp(e,t){if(e===null)return null;let r=He(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Wj(e,t){let r=He(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Zp(e,t){let r=He(e,t);if(!jo.isAbsolute(r))throw new Error(`${t} must be absolute`);return jo.resolve(r)}function zj(e,t){let r=`Native local checks[${t}]`,i=Io(e,r);if(To(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,f)=>He(u,`${r}.argv[${f}]`,!0)),a=jn(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Qp(i.startedAt,`${r}.startedAt`),s=Qp(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=Tn(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=Io(i.activeProcess,`${r}.activeProcess`),f=jn(u.status,["starting","running"],`${r}.activeProcess.status`);if(To(u,new Set(["status","pid","identity"]),`${r}.activeProcess`),f==="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:Tn(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:He(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:He(i.id,`${r}.id`),name:He(i.name,`${r}.name`),operationId:He(i.operationId,`${r}.operationId`),status:a,repeatable:Mj(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:Tn(i.executionCount,`${r}.executionCount`),argv:n,cwd:Zp(i.cwd,`${r}.cwd`),exitCode:Vj(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:He(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:jn(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:He(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function eh(e){let t="Native local execution state",r=Io(e,t);if(To(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==Da)throw new Error(`Native local execution schema must be ${Da}`);let i=Io(r.workspace,"Native local workspace");To(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Io(r.execution,"Native local execution");To(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=Qp(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:He(o.operationId,"Native local execution.operationId"),stage:jn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:jn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:In(o.executionId,"Native local execution.executionId"),status:jn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Tn(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:Wj(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:Tn(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:He(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(zj);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:Da,change:He(r.change,"Native local change"),basedOnStateVersion:Tn(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:In(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:In(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:In(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:In(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Zp(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Zp(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:In(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:He(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}function re(e){return eh({schema:Da,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:jo.resolve(e.projectRoot),worktreeRoot:jo.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null,machineId:Fj.hostname()},execution:null,checks:[]})}async function Se(e){let t;try{t=await XN.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 eh(r)}function QN(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 F(e,t,r={}){let i=eh(t);await XN.mkdir(jo.dirname(e),{recursive:!0}),await we(e,i,r)}async function Ll(e){let t=null,r=null;try{t=await Se(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=re(e);return await F(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}le();Fr();te();async function th(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}import{promises as ZN}from"node:fs";import ql from"node:path";rt();ut();te();var rh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,eb="comet-state.yaml",tb="state.json";function se(e,t){if(!rh.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=ql.join(e.changesDir,t);if(!be(e.changesDir,r))throw new Error("Native change path escaped");return r}function Qe(e,t){return ql.join(se(e,t),eb)}function D(e,t){return ql.join(pe(e,t),tb)}async function $n(e,t){try{let r=await ZN.readFile(Qe(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function ve(e){return Tg(e)}function Fl(e,t){let r=ie(t);if(!r.isGitWorktree||r.currentBranch===null||ar(t,r.currentBranch)===null)return null;if(!Zs(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}}async function $(e,t){return lt(Qe(e,t))}async function ce(e){let t=await dn({file:Qe(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=ql.join(se(e.paths,t.name),"verification.md");await z(e.paths.nativeRoot,r),await ZN.rm(r,{force:!0})}return t}async function ih(e){let t=await $(e.paths,e.name),r=D(e.paths,e.name);try{let i=await Se(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"}}}ne();import{promises as zl}from"node:fs";import $i from"node:path";xi();var ah=br(rr(),1);import Ho from"path";nt();ne();xi();st();le();te();Mt();po();le();te();nn();$r();var Xj=br(rr(),1);nn();$r();Hr();Hr();rn();hf();nn();Hr();var wM=4*1024*1024;var Qj=null;function Zj(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function rb(e,t){return(...r)=>{let i=Qj;if(i===null)return t(...r);let n=Zj(`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}}rn();var SM=rb("hookWritePolicy",async e=>(await nf(e))?.hook??{allow_paths:[]});Ta();var e$=16*1024;ff();Ea();var S1=Number.MAX_SAFE_INTEGER;ne();Dt();var H1={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};import On from"node:path";ne();nt();le();te();var $o=/^[a-f0-9]{64}$/u,nb=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,s$=16*1024,X1=process.platform;function c$(e,t){let r=On.relative(e,t);return On.isAbsolute(r)||r===".."||r.startsWith(`..${On.sep}`)?null:r.replaceAll("\\","/")||"."}function ab(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function ob(e,t){if(e.length===0||ab(e)||e.includes("\\")||On.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=On.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function l$(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 nh(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||ab(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function u$(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(nh(e.changeBranch,"Native workspace change branch"),nh(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 d$(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"||!nb.test(t.baseCommit)||typeof t.targetCommit!="string"||!nb.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");nh(t.targetBranch,"Native workspace Git target branch")}function f$(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"||!$o.test(String(t.projectRootId))||!$o.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");l$(t.capturedAt),ob(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&&!$o.test(String(t.projectRootPathId))||a&&!$o.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!$o.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&d$(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(u$(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 p$(e,t){return On.join(ot(e,t),"workspace.json")}function h$(e,t){let r=p$(e,t),i=qe(e,r),n=c$(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:ob(n,"Native workspace file ref")}}async function m$(e,t){try{let r=h$(e,t),i=await Q({root:r.root,ref:r.ref,maxBytes:s$});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Oo(e,t){let r=await m$(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(f$(r),r)}no();Yc();Yc();var Vl=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"},Do=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"},Ml=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"},EW=Qc("en");function At(e,t){co(t);let r=Ho.join(e.changesDir,t);if(!be(e.changesDir,r))throw new Error("Native change path escaped");return r}async function y$(e,t=Ho.dirname(e)){let r=Ho.relative(t,e).split(Ho.sep).join("/"),i=await Q({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,ah.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 sb(e,t){let r=Ho.join(At(e,t),fr);await z(e.nativeRoot,r);let i=ip(await y$(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}nt();Jt();te();var lb=["outcome","scope","nonGoals","acceptanceExamples"],cb=[...lb,"constraints","decisions","openQuestions","verificationExpectations"];var b$=new Set(["nonGoals","decisions","openQuestions"]),k$={maxFileBytes:Kd};function S$(e){let t=new Map,r=null,i=[],n=()=>{r!==null&&t.set(r,i.join(`
|
|
220
220
|
`).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}function oh(e){return{valid:e.length===0,findings:e}}function sh(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 E$(e){return sh(e).trim()}function Wl(e){let t=E$(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(`
|
|
221
221
|
`).trim()}function x$(e){let t=Wl(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 ub(e){let t=Wl(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 db(e,t){let r=[];return Wl(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}):ub(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}),oh(r)}function ch(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 lh(e,t,r={}){let i=[],n;try{n=(await Q({root:e,ref:t,maxBytes:k$.maxFileBytes})).text}catch(s){return oh([{code:"brief-missing",message:s.message,path:t}])}let a=new Map;for(let[s,c]of S$(n))a.set(Xc(s)??s,c);for(let s of cb)a.has(s)||i.push({code:"brief-section-missing",message:`Missing brief section: ${s}`,path:t});let o=r.strict?cb:lb;for(let s of o){let c=a.get(s)??"";Wl(c).length===0?i.push({code:"brief-section-empty",message:`Brief section is empty: ${s}`,path:t}):ub(c)?i.push({code:"brief-section-placeholder",message:`Brief section contains only template placeholder content: ${s}`,path:t}):r.strict&&!b$.has(s)&&x$(c)&&i.push({code:"brief-section-empty",message:`Brief section must describe the confirmed work instead of declaring no items: ${s}`,path:t})}return ch(n)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),oh(i)}nt();fe();le();il();Zf();ut();Fr();ne();xi();mi();import{promises as C$}from"node:fs";function It(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
222
222
|
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function gr(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function R$(e){return e.archived?We(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?We(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?We(e.language,"Verification passed; ready to archive","验收通过,可归档"):We(e.language,"Verification passed","验收通过")}function P$(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?We(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?R$(e):e.verification_result==="blocked"?We(t,"Blocked","已阻塞"):e.verification_result==="fail"?We(t,"Failed","未通过"):We(t,"Pending","待处理")}function _$(e){if(e.verification?.assurance==="semantic-verification-unavailable")return We(e.language,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查");if(e.verification_result==="fail")return We(e.language,"Fix unresolved acceptance criteria and verify again","修复未通过的验收项后重新验证");if(e.verification_result==="blocked")return We(e.language,"Resolve the reported blockers and resume verification","解决报告中的阻塞项后恢复验证");let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===Ne?Ne:"host-attested"),r=t===Ne&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":r?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","skill-coordinated":r?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function A$(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,i=d=>ap(r,d),n=(d,p)=>We(r,d,p),a=e.acceptance.map(d=>`| ${gr(d.id)} | ${gr(d.result)} | ${gr(d.source)} | ${gr(d.text)} | ${gr(It(d.reason))} |`).join(`
|
|
@@ -280,31 +280,31 @@ ${e.history_overflow.dropped_entries>0?`${n("Earlier history entries folded into
|
|
|
280
280
|
`:""}## ${i("conclusion")}
|
|
281
281
|
|
|
282
282
|
${It(e.verification.summary)}
|
|
283
|
-
`}function I$(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function fb(e){let t;try{t=await C$.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=I$(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function Xr(e){await at(e.file,A$(e.state,e.supervisor))}te();xi();Gr();st();var dh=br(rr(),1);Hr();var
|
|
283
|
+
`}function I$(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function fb(e){let t;try{t=await C$.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=I$(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function Xr(e){await at(e.file,A$(e.state,e.supervisor))}te();xi();Gr();st();var dh=br(rr(),1);Hr();var LW=new Set("a an and are as at be by for from in is it of on or that the this to with you your".split(" "));var pb=5,T$=600,zW=256*1024,j$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,$$=/^[A-Za-z0-9][A-Za-z0-9._-]*$/u;var O$=/^[a-f0-9]{64}$/iu;function hb(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Qr(e,t,r=4096){if(typeof e!="string"||e.trim().length===0||e.length>r)throw new Error(`${t} must be a non-empty string within the association limit`);return e}function uh(e,t){let r=Qr(e,t).replaceAll("\\","/");if(r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").some(i=>i===""||i==="."||i===".."))throw new Error(`${t} must be a project-relative path`);return r}function H$(e,t){let r=Qr(e,t,64).toLowerCase();if(!O$.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function D$(e,t){let r=`Capability association evidence[${t}]`,i=hb(e,r),n=Object.keys(i).filter(a=>!new Set(["source","kind","title","snippet"]).has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return{source:uh(i.source,`${r}.source`),kind:Qr(i.kind,`${r}.kind`,128),...i.title===void 0?{}:{title:Qr(i.title,`${r}.title`)},...i.snippet===void 0?{}:{snippet:Qr(i.snippet,`${r}.snippet`,T$)}}}function mb(e){let t=typeof e=="string"?(()=>{if(e.length>65536)throw new Error("Capability association exceeds the size limit");let l=(0,dh.parseDocument)(e,{uniqueKeys:!0});if(l.errors.length>0)throw new Error(l.errors[0].message);return l.toJS({mapAsMap:!1})})():e,r=hb(t,"Capability association"),i=Object.keys(r).filter(l=>!new Set(["schema","status","workflow","capability","current_spec","current_hash","confidence","query","reason","historical_sources","evidence"]).has(l));if(i.length>0)throw new Error(`Capability association has unknown field(s): ${i.join(", ")}`);if(r.schema!=="comet.capability-association.v1")throw new Error("Unsupported capability association schema");let n=r.workflow;if(n!=="native"&&n!=="classic")throw new Error("Capability association workflow is invalid");let a=B$(Qr(r.capability,"Capability association capability"),n);if(!Array.isArray(r.historical_sources))throw new Error("Capability association historical_sources must be an array");let o=r.historical_sources.map((l,u)=>uh(l,`Capability association historical_sources[${u}]`));if(!Array.isArray(r.evidence)||r.evidence.length>pb)throw new Error(`Capability association evidence must contain at most ${pb} entries`);let s=r.status;if(s!=="suggested"&&s!=="explicit")throw new Error("Capability association status is invalid");let c=r.confidence;if(c!=="high"&&c!=="medium"&&c!=="low")throw new Error("Capability association confidence is invalid");return{schema:"comet.capability-association.v1",status:s,workflow:n,capability:a,current_spec:uh(r.current_spec,"Capability association current_spec"),current_hash:H$(r.current_hash,"Capability association current_hash"),confidence:c,...r.query===void 0?{}:{query:Qr(r.query,"Capability association query")},reason:Qr(r.reason,"Capability association reason",2048),historical_sources:o,evidence:r.evidence.map(D$)}}function B$(e,t){let r=e.replaceAll("\\","/").replace(/^\/+|\/+$/gu,""),i=r.split("/"),n=t==="native"?j$:$$;if(!r||i.some(a=>!n.test(a)))throw new Error(`Invalid ${t} capability: ${e}`);return i.join("/")}ut();Fr();async function Hn(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);if(t.verification===null||t.verification_result!=="pass")throw new Error("Native Supervisor recovery requires a persisted final verification pass");let i={...ye(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(e.reason),completed_at:new Date().toISOString()}),phase:"verify",status:"active",state_version:t.state_version+1,acceptance:t.acceptance.map(a=>({...a,result:"pending",reason:null})),blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}},n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),re({portableState:n,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}lr();var L$=Qc("en"),vb="capability-association.yaml";function Jl(e){let t=e.replace(/\r\n?/gu,`
|
|
284
284
|
`).split(`
|
|
285
285
|
`);for(;t.length>0&&t.at(-1)?.trim().length===0;)t.pop();return`${t.map(r=>r.replace(/[\t ]+$/gu,"")).join(`
|
|
286
286
|
`)}
|
|
287
287
|
`}function q$(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 F$(e){let t=[],r=!1;for(let i of sh(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&&!q$(n[1]??"")})}function gb(e,t){let r=e.map(({code:i,message:n,path:a})=>`- ${i}${a?` (${a})`:""}: ${n}`).join(`
|
|
288
288
|
`);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(`
|
|
289
|
-
`)}async function fh(e){let t=se(e.paths,e.state.name),r=[...(await lh(t,e.state.brief,{strict:!0})).findings],i="";try{i=(await Q({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&&!F$(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 f=(await Q({root:t,ref:u,maxBytes:null,includeHash:!1})).text;r.push(...db(f,u).findings)}catch(f){r.push({code:"spec-document-missing",message:`Target Spec cannot be read: ${f.message}. Restore the complete file at ${u}.`,path:u})}}return{valid:r.length===0,findings:r}}async function Gl(e){let t=await fh(e);if(!t.valid)throw new Error(gb(t.findings,{change:e.state.name,phase:e.state.phase}))}function Tt(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 Ul(e){let t=se(e.paths,e.state.name),r=$i.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await zl.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(!rh.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=$i.join(t,...s.split("/")),l=await zl.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=$i.join(e.paths.specsDir,o.name,"spec.md"),f="create",d=null;try{let g=await zl.lstat(u);if(!g.isFile()||g.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);f="modify",d=ur((await Q({root:e.paths.specsDir,ref:`${o.name}/spec.md`,maxBytes:null,includeHash:!1})).text)}catch(g){if(g.code!=="ENOENT")throw g}let p=`specs/${o.name}/${Ww}`,m=$i.join(t,...p.split("/")),h={};try{let g=await zl.lstat(m);if(!g.isFile()||g.isSymbolicLink())throw new Error(`Native delta manifest must be a regular file: ${p}`);let v=await Q({root:t,ref:p,maxBytes:null,includeHash:!1}),w=io(v.text);if(w.capability!==o.name)throw new Error(`Native delta capability ${w.capability} does not match directory ${o.name}`);let y=d??ur(""),b=e.state.spec_changes.find(S=>S.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!==y)throw new Error(`Native delta base_hash does not match the current total Spec for ${o.name}`);h={delta_source:p,base_hash:w.base_hash}}catch(g){if(g.code!=="ENOENT")throw g}a.push({capability:o.name,operation:f,source:s,...h})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Kl(e){let t=se(e.paths,e.state.name),r=await Q({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(ch(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 Q({root:t,ref:o.source,maxBytes:null,includeHash:!1}),c=s.text,l=null;if(o.delta_source){let u=await Q({root:t,ref:o.delta_source,maxBytes:null,includeHash:!1}),f=io(u.text);c=Uw(s.text,f);let d="";try{d=(await Q({root:e.paths.specsDir,ref:`${o.capability}/spec.md`,maxBytes:null,includeHash:!1})).text}catch(p){if(p.code!=="ENOENT")throw p}if(ur(d)===f.base_hash){let p=Yw({baselineMarkdown:d,delta:f,allowAlreadyApplied:!0});if(ur(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=T("comet.native.shape-artifact-content.v1",Jl(u.text))}i.push({capability:o.capability,source:s.ref,markdown:c}),n.push({...o,contentHash:T("comet.native.shape-artifact-content.v1",Jl(s.text)),...l===null?{}:{deltaContentHash:l}})}let a=null;try{let o=await Q({root:t,ref:vb,maxBytes:65536,includeHash:!1}),s=mb(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=$i.relative(e.paths.projectRoot,$i.join(e.paths.specsDir,s.capability,"spec.md")).replaceAll($i.sep,"/");if(s.current_spec!==l)throw new Error(`Native capability association points to ${s.current_spec}, expected ${l}`);a=T("comet.native.shape-artifact-content.v1",Jl(o.text))}catch(o){if(o.code!=="ENOENT")throw o}return{acceptance:rl({briefMarkdown:r.text,specs:i}),formalHash:T("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:T("comet.native.shape-artifact-content.v1",Jl(r.text))},specs:n,association:{source:vb,contentHash:a}})}}function Yl(e){return T("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function ph(e){return _(e.paths,`prepare portable shape confirmation ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(Tt({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 Ul({paths:e.paths,state:t});e.enforceDocumentConstraints===!0&&await Gl({paths:e.paths,state:t,specChanges:r});let i=await Kl({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Fe({changeDir:se(e.paths,t.name),acceptanceIds:n.map(({id:d})=>d),validation:dt({...t,acceptance:n})}),o=t;if(a&&t.workspace.change_branch===null){await Hc(e.paths,t.name);let d=Fl(t.workspace,e.paths.projectRoot);if(d===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=ye({...t,workspace:d},{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(`Native workspace bound to branch ${d.change_branch} at the Supervisor Shape confirmation boundary`),completed_at:new Date().toISOString()})}let s=await _o(se(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:Yl({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=FN({state:l,acceptance:n.map(d=>({...d}))});e.enforceDocumentConstraints===!0&&(u.document_constraints_version=1),a&&(u.children_contract_hash=An({acceptance:u.acceptance,children:a.contract}));let f=await ce({paths:e.paths,previous:t,next:u});return await F(D(e.paths,t.name),re({portableState:f,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),f})}async function Bo(e){if(e.state.document_constraints_version===1){let l=await fh(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 Ul(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 f=e.state.spec_changes[u];return f!==void 0&&l.capability===f.capability&&l.source===f.source&&l.delta_source===f.delta_source&&l.base_hash===f.base_hash&&(l.operation===f.operation||r?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await Kl({...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(!my(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await Fe({changeDir:se(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:dt({...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&&Yl({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?An({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 Je(e){let t=await Bo(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await qo({paths:e.paths,state:e.state,reason:r,keepFailureBudget:!0}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function Lo(e){return _(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await $(e.paths,e.name);if(Tt({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:qo({paths:e.paths,state:t,reason:e.reason,...e.keepFailureBudget?{keepFailureBudget:!0}:{}})})}async function qo(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...ye(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(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 ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),re({portableState:n,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}function eu(e,t){let r=j.relative(j.resolve(e),j.resolve(t));if(j.isAbsolute(r)||r===".."||r.startsWith(`..${j.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(j.sep).join("/");return Za(e,i),i}function Xl(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return vn({id:e.id,name:e.name,executable:r,argv:i,cwdRef:eu(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function Sb(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:eu(t,r.cwd),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}function Eb(e,t,r,i,n,a){return e.candidateId!==i.builder_handoff?.candidate_id||e.inputFingerprint!==n||j.resolve(e.workspace.projectRoot)!==j.resolve(r)||j.resolve(e.workspace.worktreeRoot)!==j.resolve(r)||e.workspace.branch!==a||e.workspace.machineId!==Zr.hostname()||e.checks.length!==t.length?!1:e.checks.every((o,s)=>Xl(o,r)===vn(t[s]))}function wb(e,t,r){return e.checks.length===t.length&&e.checks.every((i,n)=>Xl(i,r)===vn(t[n]))}async function Ql(e){let t=e.execution;if(t===null||t.status!=="running")return"not-running";if(t.ownerPid===void 0)return"unknown";let r=await hn(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 hn(a.pid,a.identity);if(o==="alive")return"running";o==="unknown"&&(i=!0)}return i?"unknown":"orphaned"}function yb(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 Zl(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:Za(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`,activeProcess:null}}function xb(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 Cb(e,t,r,i)}function Cb(e,t,r,i){return{...Zl(t,r,i),executionCount:e.executionCount}}function Rb(e){return bb("sha256").update(e).digest("hex")}async function Mo(e){let t=await Qt.lstat(e);if(!t.isFile())throw new Error("Native check input must be a regular file");let r=bb("sha256"),i=await Qt.open(e,"r"),n=0;try{let o=Buffer.allocUnsafe(V$);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 Qt.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 Pb=2e4,_b=1024*1024*1024,V$=65535,Ab=["build","dist","gen","generated","out","target",".next",".nuxt",".output",".svelte-kit"],M$=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"]),hh=[":(exclude).comet/runtime/**",":(exclude).comet/current-change.json"],Ib=new Set(["comet-state.yaml","children.yaml","verification.md"]);function Bn(e,t){if(!t)return[...hh];let r=j.relative(e,t).replaceAll("\\","/");if(j.isAbsolute(r)||r===".."||r.startsWith("../"))return[...hh];let i=r===""?"":`${r}/`;return[...hh,...["changes","archive"].flatMap(n=>[...Ib].map(a=>`:(exclude)${i}comet/${n}/**/${a}`))]}function mh(e,t,r){let i=e.replaceAll("\\","/").replace(/^\.\//u,"");if(i===".comet/current-change.json"||i.startsWith(".comet/runtime/"))return!0;if(!t||!r||!Ib.has(j.basename(i)))return!1;let n=j.resolve(t,...i.split("/")),a=j.relative(j.resolve(r),n);if(j.isAbsolute(a)||a===".."||a.startsWith(`..${j.sep}`))return!1;let[,o]=a.split(j.sep);return a.startsWith(`comet${j.sep}`)&&(o==="changes"||o==="archive")}function Dn(){return{complete:!1,files:[]}}function W$(e){let t=e==="."?"":`${e}/`;return Ab.flatMap(r=>[`:(glob)${t}${r}/**`,`:(glob)${t}**/${r}/**`])}function Tb(e){return/(?:^|\/)(?:\.env(?:\..*)?|[^/]+\.(?:key|pem|p12|pfx))$/iu.test(e)}async function jb(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(I(e,["ls-files","--others","--ignored","--exclude-standard","-z","--",...i.flatMap(W$)]).split("\0").filter(Boolean).map(s=>s.replaceAll("\\","/")))].sort()}catch{return Dn()}if(n.length>Pb)return Dn();let a=[],o=0;for(let s of n){if(mh(s,e,r))continue;let c=j.resolve(e,...s.split("/"));if(!be(e,c)||Tb(s))return Dn();try{let l=await Qt.lstat(c);if(!l.isFile()||o+l.size>_b)return Dn();let{digest:u,size:f}=await Mo(c);o+=f,a.push({path:s,digest:u,size:f})}catch{return Dn()}}return{complete:!0,files:a}}async function z$(e,t,r){let i=[...new Set(t.map(({cwdRef:c})=>c))],n=new Map,a=0,o=c=>Ab.includes(c),s=async(c,l,u)=>{let f;try{f=await Qt.readdir(c,{withFileTypes:!0})}catch{return!1}f.sort((d,p)=>d.name.localeCompare(p.name,"en"));for(let d of f){let p=l?`${l}/${d.name}`:d.name;if(mh(p,e,r)||d.isDirectory()&&M$.has(d.name))continue;let m=j.join(c,d.name);if(d.isDirectory()){if(!await s(m,p,u||o(d.name)))return!1;continue}if(u){if(Tb(p)||!d.isFile())return!1;try{let h=await Qt.lstat(m);if(a+h.size>_b)return!1;let{digest:g,size:v}=await Mo(m);if(a+=v,n.set(p,{path:p,digest:g,size:v}),n.size>Pb)return!1}catch{return!1}}}return!0};for(let c of i){let l=Za(e,c);if(!await s(l,c==="."?"":c,o(j.basename(l))))return Dn()}return{complete:!0,files:[...n.values()].sort((c,l)=>c.path.localeCompare(l.path,"en"))}}function vh(e,t){return T("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:j.resolve(e.cwd),exitCode:e.exitCode,startedAt:e.startedAt,completedAt:e.completedAt,log:e.log,logDigest:Rb(t)})}async function J$(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=I(e.projectRoot,["rev-parse","HEAD"]),r=!0,t.branch=I(e.projectRoot,["branch","--show-current"]),t.status=I(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--",...Bn(e.projectRoot,e.managedArtifactRoot)]);let i=I(e.projectRoot,["diff","--name-only","-z","HEAD","--",...Bn(e.projectRoot,e.managedArtifactRoot)]).split("\0").filter(Boolean).sort();t.diff=await th(i,4,async a=>{let o=j.resolve(e.projectRoot,...a.split("/"));try{let{digest:s}=await Mo(o);return{path:a,digest:s}}catch{return{path:a,digest:null}}}),t.diff.some(({digest:a})=>a===null)&&(t.complete=!1),t.stagedDiff=Rb(I(e.projectRoot,["ls-files","--stage","-z","--",...Bn(e.projectRoot,e.managedArtifactRoot)])),t.submodules=I(e.projectRoot,["submodule","status","--recursive"]);let n=I(e.projectRoot,["ls-files","--others","--exclude-standard","-z","--",...Bn(e.projectRoot,e.managedArtifactRoot)]).split("\0").filter(Boolean).sort();t.untracked=await th(n,4,async a=>{let o=j.resolve(e.projectRoot,...a.split("/"));try{let{digest:s,size:c}=await Mo(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 jb(e.projectRoot,e.plans,e.managedArtifactRoot),t.ignored.complete||(t.complete=!1)}catch{r?t.complete=!1:(t.capture="physical-tree",t.physical=await z$(e.projectRoot,e.plans,e.managedArtifactRoot),t.complete=t.physical.complete)}return T("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:j.resolve(e.projectRoot),machineId:Zr.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])=>$b.has(i.toUpperCase())).map(([i,n])=>[i,n??null]).sort(([i],[n])=>i.localeCompare(n))})}var $b=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 G$(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function U$(){return Object.entries(process.env).filter(([e])=>$b.has(e.toUpperCase())).map(([e,t])=>[e,t??null]).sort(([e],[t])=>e.localeCompare(t))}async function Nb(e){try{let t=I(e.projectRoot,["rev-parse","HEAD"]),r=I(e.projectRoot,["branch","--show-current"]),i=I(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--",...Bn(e.projectRoot,e.managedArtifactRoot)]),n=I(e.projectRoot,["ls-files","--stage","-z","--",...Bn(e.projectRoot,e.managedArtifactRoot)]);if(t===null||i===null)return null;let a=[];for(let s of ka(e.projectRoot).filter(c=>!mh(c,e.projectRoot,e.managedArtifactRoot))){let c=j.resolve(e.projectRoot,...s.split("/")),l=null;try{l=(await Mo(c)).digest}catch{return null}a.push({path:s,digest:l})}a.sort((s,c)=>s.path.localeCompare(c.path,"en"));let o=await jb(e.projectRoot,e.plans??[],e.managedArtifactRoot);return o.complete?T("comet.native.check-input-gate.v1",{candidateId:e.candidateId,head:t,branch:r,status:i,staged:n,workingTree:a,ignored:o,projectRoot:j.resolve(e.projectRoot),machineId:Zr.hostname(),execPath:process.execPath,node:process.version,platform:process.platform,arch:process.arch,boundEnvironment:U$()}):null}catch{return null}}function ei(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:J(i),argv_display:eo(r.argv.slice(1)).map(n=>J(n)),argv_truncated:!1,cwd_ref:eu(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:G$(r)}})}function K$(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function Oi(e){if(e.local===null||e.local.change!==e.state.name)return re({portableState:e.state,projectRoot:e.projectRoot,branch:ve(e.projectRoot)});let t=e.local.execution?.operationId??kb();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 ti(e){try{let t=await Se(D(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 Wo(e){let t=await ti({paths:e.paths,state:e.state}),r=KN({state:e.state,summary:e.summary}),i=await ce({paths:e.paths,previous:e.state,next:r});return await F(D(e.paths,e.state.name),Oi({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}async function Y$(e,t){for(let r of e.checks)if(r.status==="passed"){if(r.evidence!=="runtime")return!1;try{let i=await z(t,j.resolve(t,...r.log.split(/[\\/]/u)));if(!(await Qt.stat(i)).isFile())return!1;let n=await Qt.readFile(i,"utf8");if(!r.evidenceDigest||r.evidenceDigest!==vh(r,n))return!1}catch{return!1}}return!0}async function X$(e){return _(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(await Je({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let r=ve(e.projectRoot),i=D(e.paths,t.name),n=(await Ll({file:i,portableState:t,projectRoot:e.projectRoot,branch:r,containedRoot:e.paths.runtimeDir})).state,a=await Nb({projectRoot:e.projectRoot,candidateId:t.builder_handoff?.candidate_id??null,plans:e.plans,managedArtifactRoot:e.paths.artifactRoot}),o=await Nb({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&&j.resolve(n.workspace.projectRoot)===j.resolve(e.projectRoot)&&j.resolve(n.workspace.worktreeRoot)===j.resolve(e.projectRoot)&&n.workspace.machineId===Zr.hostname()?n.inputFingerprint:await J$({state:t,projectRoot:e.projectRoot,plans:e.plans,managedArtifactRoot:e.paths.artifactRoot}),u=pe(e.paths,t.name),f=await Y$(n,u),d=n.checks.every(k=>k.status==="passed"),p=e.retryCheckIds===void 0?null:new Set(e.retryCheckIds),m=n.candidateId===t.builder_handoff?.candidate_id&&j.resolve(n.workspace.projectRoot)===j.resolve(e.projectRoot)&&j.resolve(n.workspace.worktreeRoot)===j.resolve(e.projectRoot)&&n.workspace.branch===r&&n.workspace.machineId===Zr.hostname()&&n.inputFingerprint===l,h=o!==null&&n.candidateInputFingerprintGate===o&&n.candidateId===t.builder_handoff?.candidate_id&&j.resolve(n.workspace.projectRoot)===j.resolve(e.projectRoot)&&j.resolve(n.workspace.worktreeRoot)===j.resolve(e.projectRoot)&&n.workspace.branch===r&&n.workspace.machineId===Zr.hostname(),g=h&&n.inputFingerprint!==null&&n.inputFingerprint!==l,v=Eb(n,e.plans,e.projectRoot,t,l,r)||h&&wb(n,e.plans,e.projectRoot),w=n.candidateId===t.builder_handoff?.candidate_id&&j.resolve(n.workspace.projectRoot)===j.resolve(e.projectRoot)&&j.resolve(n.workspace.worktreeRoot)===j.resolve(e.projectRoot)&&n.workspace.branch===r&&n.workspace.machineId===Zr.hostname(),y=m&&d&&!f;if(p&&p.size===0)throw new Error("Native check retry list must contain at least one ID");if(!m&&n.execution?.stage==="checking"&&n.execution.actor==="runtime"&&n.execution.status==="running"){let k=await Ql(n);if(k!=="orphaned")throw new Error(k==="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=yb(n),await F(i,n,{containedRoot:e.paths.runtimeDir})}if(!m&&w&&n.inputFingerprint!==null&&(n.execution!==null||n.checks.length>0)){let k=n.inputFingerprint!==l;if(!(s&&!k||g)){let E=Yr({state:t,reason:"Native check input changed after the candidate was built; a new Builder candidate is required before checks can run again."}),C=await ce({paths:e.paths,previous:t,next:E});throw await F(i,re({portableState:C,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(!m&&!h){let k=re({portableState:t,projectRoot:e.projectRoot,branch:r});await F(i,k,{containedRoot:e.paths.runtimeDir}),n=k}let b=wb(n,e.plans,e.projectRoot);if(n.execution?.stage==="checking"&&n.execution.actor==="runtime"&&b&&v){let k=n.execution;if(k.status==="running"){let C=await Ql(n);if(C!=="orphaned")throw new Error(C==="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=yb(n),await F(i,n,{containedRoot:e.paths.runtimeDir}),k=n.execution}let E=n.checks.filter(C=>C.status==="interrupted");if(E.length===0&&k.status==="completed"&&d&&!y&&!g){let C=new Map(e.plans.map(({id:H,name:P})=>[H,P]));return{kind:"reuse",state:t,checks:ei({local:n,projectRoot:e.projectRoot,supplied:[],requestedNames:C})}}if(E.length===0&&k.status==="completed"&&!d&&!y&&!g)throw new Error(`Native check plan contains a failed check (${n.checks.filter(({status:C})=>C==="failed").map(({id:C})=>C).join(", ")}); submit a new Builder candidate`);if(E.length>0&&E.some(C=>!C.repeatable)&&!y){let C=Yr({state:t,reason:`A non-repeatable Runtime check was interrupted (${E.filter(P=>!P.repeatable).map(({id:P})=>P).join(", ")}); a new Builder candidate is required before it can run again.`}),H=await ce({paths:e.paths,previous:t,next:C});throw await F(D(e.paths,t.name),re({portableState:H,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${E.find(P=>!P.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}if(E.length>0&&p===null&&!y&&!g){let C=new Map(e.plans.map(({id:H,name:P})=>[H,P]));return{kind:"reuse",state:t,checks:ei({local:n,projectRoot:e.projectRoot,supplied:[],requestedNames:C})}}if(p){let C=[...p].filter(P=>!E.some(W=>W.id===P));if(C.length>0)throw new Error(`Native check retry IDs must refer to interrupted checks: ${C.join(", ")}`);let H=E.filter(P=>p.has(P.id)&&P.executionCount>=3);if(H.length>0)throw new Error(`Native check retry limit (3) reached: ${H.map(({id:P})=>P).join(", ")}`)}}if(n.execution!==null&&n.checks.length>0){if(!(n.execution.stage==="checking"&&n.execution.actor==="runtime"&&n.checks.some(E=>E.status==="interrupted")&&b)&&!y&&!g)throw new Error("Native check plan was already resolved with a different plan")}else if((n.execution!==null||n.checks.length>0)&&!y&&!g)throw new Error("Native check plan was already resolved with a different plan");let S=kb(),N=await Ke(process.pid),x={...n,candidateId:t.builder_handoff?.candidate_id??null,inputFingerprint:l,inputFingerprintGate:a,candidateInputFingerprintGate:o,workspace:{...n.workspace,projectRoot:j.resolve(e.projectRoot),worktreeRoot:j.resolve(e.projectRoot),branch:ve(e.projectRoot),machineId:Zr.hostname()},execution:{operationId:S,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0,ownerPid:process.pid,...N?{ownerIdentity:N}:{}},checks:e.plans.map(k=>{let E=n.checks.find(C=>C.id===k.id);return g&&E?Zl(k,S,e.projectRoot):y&&E?Cb(E,k,S,e.projectRoot):E?.status==="interrupted"&&(p===null||p.has(E.id))?xb(E,k,S,e.projectRoot):E?{...E,operationId:S,activeProcess:null}:Zl(k,S,e.projectRoot)})};return await F(i,x,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:x,plans:e.plans.filter(k=>{let E=n.checks.find(C=>C.id===k.id);return y||g||E===void 0||E.status==="interrupted"&&(p===null||p.has(E.id))})}})}async function Fo(e){return _(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await $(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=D(e.paths,t.name),i=await Se(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 F(r,n,{containedRoot:e.paths.runtimeDir}),n})}async function zo(e){let t=e.projectRoot??e.paths.projectRoot;Ye(t,e.plans);let r=[],i=new Set;for(let c of e.plans){to(t,c);let l=vn(c);i.has(l)||(i.add(l),r.push(c))}let n=await X$({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return{...n,disposition:"reused"};let a=n.local.execution.operationId,o=pe(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await Fo({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(p=>p.id===c.id?{...p,status:"running",executionCount:p.executionCount+1,startedAt:l,activeProcess:{status:"starting"}}:p)})});let u=await Ni({projectRoot:t,runtimeDir:o,operationId:a,plan:c,onSpawn:async({pid:d})=>{let p=await Ke(d);await Fo({paths:e.paths,state:n.state,operationId:a,update:m=>({...m,checks:m.checks.map(h=>h.id===c.id?{...h,activeProcess:{status:"running",pid:d,...p?{identity:p}:{}}}:h)})})}}),f=await Qt.readFile(j.resolve(o,...u.logRef.split("/")),"utf8");await Fo({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(p=>{if(p.id!==c.id)return p;let m={...p,status:u.status,exitCode:u.exitCode,startedAt:u.startedAt,completedAt:u.completedAt,log:u.logRef,activeProcess:null,evidence:"runtime"};return{...m,evidenceDigest:vh(m,f)}})})})}await Fo({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await Fo({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 Se(D(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:ei({local:s,projectRoot:t,supplied:[]}),disposition:"executed"}}async function gh(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 $(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 Se(D(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:eu(t,c.cwd),timeoutMs:c.timeoutMs,repeatable:c.repeatable}});return zo({paths:e.paths,name:e.name,plans:s,projectRoot:t,retryCheckIds:e.checkIds})}async function Ob(e){let t=D(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>=Yp)throw new Error(`Native Verifier request-checks exceeded ${Yp} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let p of r.checks){let m=Xl(p,e.projectRoot);n.set(m,p),p.status!=="interrupted"&&i.set(m,p),a.set(p.id,m)}let o=new Map,s=new Map;for(let p of e.response.checks){let m=K$(p);to(e.projectRoot,m);let h=vn(m),g=s.get(m.id);if(g!==void 0&&g!==h)throw new Error(`Native Verifier check ID ${m.id} refers to conflicting commands`);let v=a.get(m.id);if(v!==void 0&&v!==h)throw new Error(`Native Verifier check ID ${m.id} conflicts with a Runtime check`);s.set(m.id,h);let w=n.get(h);if(w?.status==="interrupted"&&!w.repeatable)throw new Error(`Native check ${w.id} was interrupted and is not repeatable; user resolution is required`);if(w?.status==="interrupted"&&w.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${w.id}`);o.has(h)||o.set(h,m)}Ye(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,f=new Map(c.map(([,p])=>[p.id,p.name])),d={...r,execution:{...r.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:u},checks:[...r.checks.map(p=>{let m=Xl(p,e.projectRoot),h=o.get(m);return h&&p.status==="interrupted"?xb(p,h,r.execution.operationId,e.projectRoot):p}),...l.filter(([p])=>!n.has(p)).map(([,p])=>Zl(p,r.execution.operationId,e.projectRoot))]};return await F(t,d,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:d,verifierExecutionRef:e.envelope.verifierExecutionRef,round:u,novelPlans:l.map(([,p])=>p),requestedNames:f,reusedCheckIds:c.filter(([p])=>i.has(p)).map(([,p])=>p.id),suppliedChecks:e.suppliedChecks}}async function Vo(e){return _(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await $(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=D(e.paths,t.name),i=await Se(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 F(r,a,{containedRoot:e.paths.runtimeDir}),a})}async function Hb(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await Vo({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=pe(e.paths,e.reservation.state.name),a=await Ni({projectRoot:e.projectRoot,runtimeDir:n,operationId:e.reservation.local.execution.operationId,plan:r,onSpawn:async({pid:s})=>{let c=await Ke(s);await Vo({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 Qt.readFile(await z(n,j.resolve(n,...a.logRef.split(/[\\/]/u))),"utf8");t=await Vo({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:vh(l,o)}})})})}t=await Vo({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await Vo({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:ei({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)}}}ne();Bc();rt();import{accessSync as wJ,constants as yJ,promises as qb}from"node:fs";import Mb from"node:path";st();le();st();le();gi();lr();ut();Fr();async function wh(e){return _(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(Tt({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 Je({paths:e.paths,state:t});let r=await Ul({paths:e.paths,state:t}),i=await Kl({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Fe({changeDir:se(e.paths,t.name),acceptanceIds:n.map(({id:v})=>v),validation:dt({...t,acceptance:n})}),o=t;if(a&&t.workspace.change_branch===null){await Hc(e.paths,t.name);let v=Fl(t.workspace,e.paths.projectRoot);if(v===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=ye({...t,workspace:v},{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(`Native workspace bound to branch ${v.change_branch} at the Supervisor Shape confirmation boundary`),completed_at:new Date().toISOString()})}let s=await _o(se(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=Yl({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:c});if(t.shape_confirmation_hash===void 0||l!==t.shape_confirmation_hash){let v=t.shape_confirmation_hash===void 0?"Native Shape confirmation fingerprint is missing":"Native Shape artifacts changed";throw await qo({paths:e.paths,state:t,reason:v,keepFailureBudget:!0}),new Error(`${v}; Native change returned to Shape and requires confirmation`)}let u=qN({state:{...o,spec_changes:r},acceptance:n.map(v=>({...v}))});if(delete u.children_contract_hash,delete u.coordination_mode,a){u.children_contract_hash=An({acceptance:u.acceptance,children:a.contract}),s&&(u.coordination_mode=c);let v=[...t.history].reverse().find(({outcome:w})=>w==="pass"||w==="fail");if(v?.outcome==="fail"&&v.unresolved_ids.length>0){let w=await je({paths:e.paths,state:u}),y=new Map((w?.children??[]).map(({name:N,status:x})=>[N,x])),b=new Set(a.contract.children.filter(({name:N})=>{let x=y.get(N);return x!=="done"&&x!=="integrated"&&x!=="archived"}).flatMap(({covers:N})=>N)),S=v.unresolved_ids.filter(N=>!b.has(N));if(S.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${S.join(", ")}`)}}let f=null,d=a?.contract.schema==="comet.native.children.v2"?await O(e.paths,t.name):null,p=null,m=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(m=ar(e.paths.projectRoot,p),!m)throw new Error(`Native Supervisor target branch has no commit: ${p}`);d||(d=await Po({paths:e.paths,parent:t.name,targetBranch:p,contract:a.contract})),d||(f=await zp({projectRoot:e.paths.projectRoot,parent:t.name,targetBranch:p,sourceConfig:await _e(e.paths.projectRoot)}))}let h=a?.contract.schema==="comet.native.children.v2"&&p&&m?d?_f({state:d,contract:a.contract}):f?Ja({parent:u.name,targetBranch:p,targetCommit:m,integrationBranch:f.binding.changeBranch,integrationWorktree:f.projectRoot,contract:a.contract}):null:null;if(a?.contract.schema==="comet.native.children.v2"&&!h)throw new Error("Native Supervisor integration state is unavailable");let g=await ce({paths:e.paths,previous:t,next:u});return await F(D(e.paths,t.name),re({portableState:g,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),h&&await q(e.paths,h),g})}import{randomUUID as Q$}from"node:crypto";import tu from"node:path";le();Ma();mi();function Db(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 Z$(e){let{state:t,local:r,envelope:i}=e;if(!Ac(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 eO(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function yh(e){return _(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(await Je({paths:e.paths,state:t}),await Fe({changeDir:se(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a),validation:dt(t)})||t.children_contract_hash){let a=await je({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=VN({state:t,input:e.input}),n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),re({portableState:n,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function Nh(e){return _(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await Je({paths:e.paths,state:t});let i=(await Ll({file:D(e.paths,t.name),portableState:t,projectRoot:r,branch:ve(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");ei({local:i,projectRoot:r,supplied:e.checks});let n=MN(t),a=await ce({paths:e.paths,previous:t,next:n}),o=D(e.paths,t.name),s=Q$();return await F(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 bh(e){return _(e.paths,`confirm portable verifier start ${e.name}`,async()=>{let t=await $(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=D(e.paths,e.name),i=await Se(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 F(r,{...i,execution:{...n,verifierStartedAt:new Date().toISOString()}},{containedRoot:e.paths.runtimeDir}),t})}async function kh(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await _(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await $(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await Je({paths:e.paths,state:r});let n=await ti({paths:e.paths,state:r}),a=Z$({state:r,local:n,envelope:e.envelope}),o;try{o=Va(a.payload)}catch(f){let d=`Native Verifier response was invalid: ${f.message}`,p=await Wo({paths:e.paths,state:r,summary:d});throw new Error(`${d}; execution error ${p.loop.execution_failure_count}/${Ao} was recorded`,{cause:f})}let s=eO(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=ei({local:n,projectRoot:i,supplied:e.checks}));let f=WN({state:r,envelope:a,checks:c,maxVerifyFailures:e.maxVerifyFailures});if(f.response.kind==="request-checks"){if(n===null)throw new Error("Native Verifier request-checks has no active local execution");let d=await Ob({paths:e.paths,projectRoot:i,state:r,local:n,envelope:a,response:f.response,suppliedChecks:c});return{kind:"request-checks",state:r,response:f.response,reservation:d}}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=f}catch(f){let d=`Native Verifier response was invalid: ${f.message}`,p=await Wo({paths:e.paths,state:r,summary:d});throw new Error(`${d}; execution error ${p.loop.execution_failure_count}/${Ao} was recorded`,{cause:f})}let u=await ce({paths:e.paths,previous:r,next:l.state});return await F(D(e.paths,r.name),u.loop.next_action==="resolve-verifier-blocker"||u.loop.next_action==="run-final-full-verification"?Oi({local:n,state:u,projectRoot:i}):re({portableState:u,projectRoot:i,branch:ve(i)}),{containedRoot:e.paths.runtimeDir}),u.verification!==null&&await Xr({file:tu.join(se(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 Hb({paths:e.paths,projectRoot:e.projectRoot??e.paths.projectRoot,reservation:t.reservation});return{state:t.state,response:t.response,checks:r.checks,requestChecks:r.requestChecks}}catch(r){let i=`Native Verifier response was invalid: ${r.message}`,n=await _(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await $(e.paths,e.name);return a.state_version!==t.state.state_version?null:Wo({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${Ao} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function Sh(e){return _(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await $(e.paths,e.name),r=await ti({paths:e.paths,state:t});if(Db({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 Wo({paths:e.paths,state:t,summary:e.summary})})}async function Eh(e){return _(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name);await Je({paths:e.paths,state:t});let r=await ti({paths:e.paths,state:t}),i=Db({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=ei({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=JN({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await ce({paths:e.paths,previous:t,next:a});return await F(D(e.paths,t.name),Oi({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await Xr({file:tu.join(se(e.paths,t.name),"verification.md"),state:o}),o})}async function xh(e){return _(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name);Tt({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await Je({paths:e.paths,state:t});let r=GN({state:t,summary:e.summary}),i=await ce({paths:e.paths,previous:t,next:r});return await F(D(e.paths,t.name),re({portableState:i,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Xr({file:tu.join(se(e.paths,t.name),"verification.md"),state:i}),i})}async function Ch(e){return _(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await $(e.paths,e.name);Tt({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await Je({paths:e.paths,state:t});let r=await ti({paths:e.paths,state:t}),i=UN(t,{reason:e.reason}),n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),Oi({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Rh(e){return _(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name);Tt({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await ti({paths:e.paths,state:t}),i=YN(t),n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),Oi({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Hi(e){return _(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await $(e.paths,e.name);if(Tt({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=e.preserveLocalChecks?await ti({paths:e.paths,state:t}):null,i=Yr({state:t,reason:e.reason,...e.failureBudget?{failureBudget:e.failureBudget}:{}}),n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),e.preserveLocalChecks?Oi({local:r,state:n,projectRoot:e.paths.projectRoot}):re({portableState:n,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function Jo(e){if(e.state.verification===null)return"not-applicable";let t=tu.join(se(e.paths,e.state.name),"verification.md");return await fb({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await Xr({file:t,state:e.state}),"rebuilt")}import tO from"node:path";lr();le();async function Ph(e){return _(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await $(e.paths,e.name);Tt({state:t,expected:e.expectedContinuation,action:"accept-result"}),await Je({paths:e.paths,state:t});let r=await O(e.paths,e.name);if(r?.finalVerification.status==="pending"){if(Ii(r).stateVersion!==r.stateVersion)return Hn({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; rerun the final full verification."});await q(e.paths,Ti(r,t))}let i=zN(t),n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),re({portableState:n,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Xr({file:tO.join(se(e.paths,t.name),"verification.md"),state:n}),n})}import{promises as Bb}from"node:fs";lr();le();cl();async function Go(e){let t=await $(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 je({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 Lb(e){let t=await $(e.paths,e.name),r=await sl(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 O(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 Bb.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=Ii(n);if(i||a.stateVersion!==n.stateVersion){let o=await Hn({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 Bb.rm(i.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await q(e.paths,Ti(n,t)),{state:t,action:"recorded-final-verification"}}async function ru(e){return _(e.paths,`recover Supervisor final verification ${e.name}`,()=>Lb(e),{allowedPortableTransaction:{kind:"archive",change:e.name}})}var lJ=16*1024;kn();Bc();var Fb="comet.native.workspace-finish.v1",rO="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Wb=new RegExp(`^${rO}$`,"u"),iO=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;function nO(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==Fb||typeof t.name!="string"||!Wb.test(t.name)||typeof t.transactionId!="string"||!iO.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!Mb.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:Fb,name:t.name,transactionId:t.transactionId,archiveDir:t.archiveDir,status:t.status,result:t.result,updatedAt:t.updatedAt}}function aO(e,t){if(!Wb.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return Mb.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function zb(e,t,r={}){let i=aO(e,t);try{let n=await qb.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=nO(JSON.parse(await qb.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}}import{randomUUID as oO}from"node:crypto";import{promises as Uo}from"node:fs";import sO from"node:path";ne();nt();le();lp();cl();il();ut();te();var Jb=["evidence.md","repair.md","archive.md","checkpoint.md"],cO="verification.md";async function lO(e,t){let r=await sl(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function Gb(e,t){await Uo.mkdir(e.transactionsDir,{recursive:!0}),await we(ol(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Ub(e,t,r={}){let i=r.removeVerificationReport===!1?Jb:[...Jb,cO];await Promise.all([Uo.rm(pe(e,t),{recursive:!0,force:!0}),Uo.rm(gf(e,t),{recursive:!0,force:!0}),...i.map(n=>Uo.rm(sO.join(At(e,t),n),{force:!0}))])}async function Kb(e,t){await F(D(e,t.name),re({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function Yb(e,t){try{let r=await Oo(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 Xb(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 uO(e){let t=At(e.paths,e.state.name),r=await Q({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 Q({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return rl({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Qb(e,t){let r=await sb(e,t);if(r.status==="runtime-incompatible")throw new Vt(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function Zb(e){return _(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await lO(e.paths,e.name),r=await $n(e.paths,e.name)?await lt(Qe(e.paths,e.name)):null;if(!t&&r)return await Ub(e.paths,e.name,{removeVerificationReport:!1}),await Kb(e.paths,r),r;let i=null,n=null;for(t||(i=await Qb(e.paths,e.name),n=await Yb(e.paths,e.name),Xb(e.paths,n),t={schema:nl,id:oO(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Gb(e.paths,t));;){let a=gy(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await Qb(e.paths,e.name),n??=await Yb(e.paths,e.name),Xb(e.paths,n),r=vy({state:i,acceptance:await uO({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await La(Qe(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Ub(e.paths,e.name):a.action==="commit-transaction"&&(r??=await lt(Qe(e.paths,e.name)),await Kb(e.paths,r)),t={...t,status:a.nextStatus},await Gb(e.paths,t)}return await Uo.rm(ol(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??lt(Qe(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as tk}from"node:fs";import rk from"node:path";le();import{promises as _h}from"node:fs";import dO from"node:path";fe();var fO=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),pO=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),hO=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task","builderFailureCount"]),mO=new Set(["status","summary"]);function iu(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function nu(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 vO(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function Di(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function gO(e,t,r,i){let n=iu(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=nu(n,fO,"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=iu(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=nu(o,pO,"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=iu(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=nu(c,mO,"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,f]of n.children.entries()){let d=iu(f,`Native Supervisor child ${u}`);if(!d)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:p,contractHash:m,...h}=d,g=nu(h,hO,`Native Supervisor child ${u}`,new Set(["builderFailureCount"]));if(g)return g;let v=r.children[u],w=v.covers.length>0?v.covers.map(b=>({id:b,source:r.acceptance_index?.[b]?.source??"brief.md",text:r.acceptance_index?.[b]?.text??b})):[{id:`child:${v.name}`,source:"children.yaml",text:v.summary??v.name}];if(p!==void 0&&JSON.stringify(p)!==JSON.stringify(w)||m!==void 0&&m!==T("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${v.name} acceptance scope does not match the legacy contract`;if(d.name!==v.name||d.summary!==v.summary||!vO(d.dependsOn,v.depends_on))return`Native Supervisor child ${v.name} does not match the legacy children contract`;let y=v.depends_on.length===0?"ready":"pending";if(d.status!==y)return`Native Supervisor child ${v.name} has progressed beyond its initial ${y} status`;if(d.baseCommit!==null||d.candidateCommit!==null||d.verifiedCommit!==null||d.integrationCommit!==null||d.verification!==null||d.blocker!==null||d.projectRoot!==null||d.task!==null)return`Native Supervisor child ${v.name} contains execution progress`;if((d.builderFailureCount??0)!==0)return`Native Supervisor child ${v.name} contains Builder failure progress`;if(!Array.isArray(d.checks)||d.checks.length!==0)return`Native Supervisor child ${v.name} contains integration checks`}return null}async function qn(e){let t=wi(e.paths,e.state.name),r;try{let c=await _h.lstat(t);if(!c.isFile()||c.isSymbolicLink())return Di(t,"","Native Supervisor overlay is not a regular file");r=await _h.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:Di(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return Di(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=dO.join(e.paths.changesDir,e.state.name),a;try{a=await Fe({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return Di(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 O(e.paths,e.state.name)}catch(c){return Di(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return Di(t,r,"Native Supervisor overlay disappeared during inspection");let s=gO(i,e.state,a.contract,o);return s?Di(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 ek(e){let t=await qn({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 _h.rm(t.file,{force:!1})}ut();Fr();function Ah(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 wO(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function yO(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:ye(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(t),completed_at:i});return B({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?wO(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 NO(e){try{let t=await Se(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 Ih(e){return _(e.paths,`recover portable change ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(t.status==="done")return await Jo({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=Ah(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await qn({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 ek({paths:e.paths,state:t,expected:i}),n=!0);let a=D(e.paths,e.name),o=await NO(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 h=o.local.execution,g=await Ql(o.local),v=h.stage==="verifying"&&h.actor==="verifier"&&h.executionId!==null,w=g==="unknown"&&e.recoverUnknownRuntimeCheck===!0&&h.stage==="checking"&&h.actor==="runtime";if(v||g!=="orphaned"&&!w)return{state:t,local:o.local,action:"await-user",reason:"execution-active",message:v?h.verifierStartedAt===void 0&&h.requestCheckRounds===0?`Native Verifier execution ${h.executionId} is registered but never confirmed startup; if the task did not start, record an explicit Verifier failure before retrying it.`:`Native Verifier execution ${h.executionId} remains owned by its host task; record an explicit Verifier failure before retrying it.`:g==="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(h=>h.status==="planned"||h.status==="running"?{...h,status:"interrupted"}:h)},await F(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await Jo({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(h=>h.status==="interrupted"&&!h.repeatable):void 0;if(l){let h=Yr({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await dn({file:Qe(e.paths,t.name),expectedStateVersion:t.state_version,next:h,containedRoot:e.paths.nativeRoot}),await tk.rm(rk.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let g=re({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await F(a,g,{containedRoot:e.paths.runtimeDir}),{state:t,local:g,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",f=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",d=u||f;if(d){let h=yO(t,f?"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.",f);t=await dn({file:Qe(e.paths,t.name),expectedStateVersion:t.state_version,next:h,containedRoot:e.paths.nativeRoot})}let p=re({portableState:t,projectRoot:e.paths.projectRoot,branch:ie(e.paths.projectRoot).currentBranch});await tk.mkdir(rk.dirname(D(e.paths,t.name)),{recursive:!0}),await F(a,p,{containedRoot:e.paths.runtimeDir}),await Jo({paths:e.paths,state:t});let m=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:d?"reverify":"resume-stable-boundary",reason:s,message:m??(d?"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.`)}})}import ik from"node:path";function nk(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function xe(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:nk(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:nk(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=>ik.relative(t.projectRoot,ik.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}_c();function Th(e){return e.charCodeAt(0)===65279?e.slice(1):e}kn();rt();import{randomUUID as dk}from"node:crypto";import{promises as ak}from"node:fs";import Ko from"node:path";gn();Wp();Ma();le();mi();function Mn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function V(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 Fn(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>V(r,`${t}[${i}]`))}function bO(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=Mn(t,`Native Builder check ${r}`);if(ee(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:V(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function au(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=Mn(t,`Native Runtime check ${r}`);if(ee(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:V(i.id,`Native Runtime check ${r} id`),name:V(i.name,`Native Runtime check ${r} name`),executable:V(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:V(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function ok(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:V(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function kO(e){let t=Mn(e,"Native Supervisor evidence");return ee(t,["summary","checks","acceptance","receiptRef"],"Native Supervisor evidence","/evidence"),{summary:V(t.summary,"Native Supervisor evidence summary"),checks:Fn(t.checks,"Native Supervisor evidence checks"),acceptance:Tc(t.acceptance,"/evidence/acceptance"),...t.receiptRef===null?{}:{receiptRef:V(t.receiptRef,"Native Supervisor receipt ref")}}}function SO(e){let t=Mn(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"),ee(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=Mn(t.review,"Native Builder review");if(ee(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:V(n.summary,"Native Builder review summary"),reviewer_execution_ref:V(n.reviewer_execution_ref,"Native Builder reviewer execution ref")}}return{kind:"builder-handoff",summary:V(t.summary,"Native Builder summary"),addressed_acceptance_ids:Fn(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:bO(t.checks),...Object.hasOwn(t,"verification_checks")?{verification_checks:au(t.verification_checks)}:{},known_limits:Fn(t.known_limits,"Native Builder known limits"),review:i}}if(t.kind==="dispatch-verifier")return ee(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:au(t.checks)};if(t.kind==="retry-checks")return ee(t,["kind","check_ids"],"Native Runner check retry input"),{kind:"retry-checks",check_ids:Fn(t.check_ids,"Native check retry IDs")};if(t.kind==="verifier-response")return ee(t,["kind","candidateId","verifierExecutionRef","response"],"Native Runner Verifier input"),{kind:"verifier-response",candidateId:V(t.candidateId,"Native Runner Verifier candidateId"),verifierExecutionRef:V(t.verifierExecutionRef,"Native Runner Verifier verifierExecutionRef"),response:Va(t.response,"/response")};if(t.kind==="verifier-started")return ee(t,["kind","candidateId","verifierExecutionRef"],"Native Runner started input"),{kind:"verifier-started",candidateId:V(t.candidateId,"Native Runner started candidateId"),verifierExecutionRef:V(t.verifierExecutionRef,"Native Runner started verifierExecutionRef")};if(t.kind==="verifier-execution-error")return ee(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:V(t.summary,"Native Verifier execution error summary"),...ok(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return ee(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:V(t.summary,"Native unavailable Verifier summary"),...ok(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return ee(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId"),candidateCommit:V(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return ee(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId"),reason:V(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-retry-builder"){if(ee(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:V(t.child,"Native Supervisor child"),stateVersion:t.stateVersion}}if(t.kind==="supervisor-reconnect")return ee(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return ee(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId"),reason:V(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(ee(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:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:kO(t.evidence)}}if(t.kind==="supervisor-checks"){let r=["kind","child","runId","checks","materials"];if(ee(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:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId"),checks:au(t.checks),...t.retry_check_ids===void 0?{}:{retry_check_ids:Fn(t.retry_check_ids,"Native Supervisor retry IDs")},materials:t.materials.map((i,n)=>{let a=Mn(i,"Native Supervisor material");return ee(a,["name","content"],"Native Supervisor material",`/materials/${n}`),{name:V(a.name,"Native Supervisor material name"),content:V(a.content,"Native Supervisor material content")}})}}if(t.kind==="supervisor-integrate"){let r=["kind","child","checks"];return ee(t,Object.hasOwn(t,"retry_check_ids")?[...r,"retry_check_ids"]:r,"Native Supervisor integration input"),{kind:"supervisor-integrate",child:V(t.child,"Native Supervisor child"),checks:au(t.checks),...t.retry_check_ids===void 0?{}:{retry_check_ids:Fn(t.retry_check_ids,"Native Supervisor retry IDs")}}}throw new Error("Native Runner input kind is invalid")}async function Hh(e,t){let r=Ko.resolve(t,e),i=await ak.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(Th(await ak.readFile(r,"utf8")))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return SO(n)}function EO(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 xO(e){return e.kind.startsWith("supervisor-")}function CO(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 sk(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 jh(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 RO(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 $h(e){let t=await Se(D(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 Dh(e){let t=await qn({paths:e.paths,state:e.state});if(t.status==="incompatible")throw new Error(t.message);let r=t.status==="repairable-legacy-overlay"?null:await O(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 je({paths:e.paths,state:e.state}),o=(i||n)&&r?r.integration.worktree:e.projectRoot;if(xO(e.input)&&r===null)throw new Error("Native Supervisor Runner input requires a current Supervisor state");if(r&&EO(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(RO(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&&Ye(o,e.input.verification_checks);return}if(e.input.kind==="dispatch-verifier"){if(sk(e.state),i&&e.input.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");Ye(o,e.input.checks);return}if(e.input.kind==="retry-checks"){if(sk(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 Se(D(e.paths,e.name));for(let l of e.input.check_ids){let u=c?.checks.find(f=>f.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"){jh(e.state);let c=await $h({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");Ye(o,CO(e.input));return}if(e.input.kind==="verifier-started"){jh(e.state);let c=await $h({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"){jh(e.state);let c=await $h({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)<cr)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");Ye(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");Ye(r.integration.worktree,c.checks)}}function ck(e){return`${Ne}:${e}:${dk()}`}function lk(e,t,r,i){if(Ko.resolve(I(e.projectRoot,["rev-parse","--show-toplevel"]))!==Ko.resolve(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree identity is invalid`);if(I(e.projectRoot,["branch","--show-current"])!==i)throw new Error(`Native Supervisor ${r} result came from the wrong Child worktree branch`);if(!zt(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree must be clean before returning a commit`);if(I(e.projectRoot,["rev-parse","HEAD"])!==t)throw new Error(`Native Supervisor ${r} result is not bound to the worktree HEAD`);try{I(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 PO(e,t){let r=ie(e.projectRoot),i=Ko.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==Ko.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=I(e.projectRoot,["rev-parse","HEAD"]);if(e.role==="verifier"){if(!zt(e.projectRoot)||n!==e.baseCommit)throw new Error("Native Supervisor Verifier task worktree is not at its candidate commit");return}try{I(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 Vn(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==Ne)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 _O(e){return[...e.history].reverse().find(({outcome:t})=>t==="recovery")?.summary}function uk(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=Vn(r),s=_O(r),c=r.acceptance.filter(({result:l})=>l==="pending").map(({id:l})=>l);return{coordination:Ne,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:se(t,r.name),supervisorStateRef:a?wi(t,r.name):null,briefRef:r.brief,specRefs:r.spec_changes.map(({capability:l,operation:u,source:f})=>({capability:l,operation:u,ref:f})),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 Oh(e){Vn(e.state);let t=await Se(D(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 fk(e){let t=e.input,r=await $(e.paths,e.name),i=await qn({paths:e.paths,state:r});if(i.status==="incompatible")throw new Error(i.message);let n=i.status==="repairable-legacy-overlay"?null:await O(e.paths,e.name),a=n!==null&&r?.phase==="verify"&&n.children.every(({status:m})=>m==="integrated"||m==="archived"),o=n!==null&&r?.phase==="build"&&n.children.every(({status:m})=>m==="integrated"||m==="archived");if(n&&t.kind==="supervisor-checks"){let m=await Mp({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}}),h=await O(e.paths,e.name),g=h?.children.find(({name:v})=>v===t.child)?.task;return{state:r,supervisorState:h,supervisorTask:g&&g.runId===t.runId?Lr(g,e.name,e.paths.projectRoot):null,checks:[],checkExecution:m,requestChecks:null,verifierDispatch:null,continuation:K(r)}}if(n&&t.kind==="supervisor-builder-result")return _(e.paths,`apply Native Supervisor Builder result ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=m.children.find(({name:b})=>b===t.child);if(!h?.task||h.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${t.child}`);try{lk(h.task,t.candidateCommit,"builder",`comet/supervisor/${m.parent}/${t.child}`)}catch(b){throw await q(e.paths,Ua(m,{child:t.child,runId:t.runId,reason:b.message})),b}let g=h.task.projectRoot,v=If(m,t),w=Ga(v,{role:"verifier",child:t.child,projectRoot:g,runId:dk()});await q(e.paths,w.state);let y=await $(e.paths,e.name);return{state:y,supervisorTask:Lr(w.task,e.name,e.paths.projectRoot),checks:[],requestChecks:null,verifierDispatch:null,continuation:K(y)}});if(n&&t.kind==="supervisor-builder-failure")return _(e.paths,`cancel Native Supervisor Builder task ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=m.children.find(({name:w})=>w===t.child);if(!h?.task||h.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${t.child}`);let g=jc(m,{child:t.child,runId:t.runId,reason:t.reason});await q(e.paths,g);let v=await $(e.paths,e.name);return{state:v,supervisorState:g,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(v)}});if(n&&t.kind==="supervisor-retry-builder")return _(e.paths,`retry Native Supervisor Builder task ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=jf(m,{child:t.child,expectedStateVersion:t.stateVersion});await q(e.paths,h);let g=await $(e.paths,e.name);return{state:g,supervisorState:h,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(g)}});if(n&&t.kind==="supervisor-reconnect")return _(e.paths,`reconnect Native Supervisor task ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=m.children.find(({name:w})=>w===t.child)?.task;if(!h||h.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);try{PO(h,`comet/supervisor/${m.parent}/${t.child}`)}catch(w){throw await q(e.paths,Ua(m,{child:t.child,runId:t.runId,reason:w.message})),w}let g=Af(m,{child:t.child,runId:t.runId});await q(e.paths,g.state);let v=await $(e.paths,e.name);return{state:v,supervisorState:g.state,supervisorTask:Lr(g.task,e.name,e.paths.projectRoot),checks:[],requestChecks:null,verifierDispatch:null,continuation:K(v)}});if(n&&t.kind==="supervisor-cancel")return _(e.paths,`cancel Native Supervisor task ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=jc(m,{child:t.child,runId:t.runId,reason:t.reason});await q(e.paths,h);let g=await $(e.paths,e.name);return{state:g,supervisorState:h,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(g)}});if(n&&t.kind==="supervisor-verifier-result")return _(e.paths,`apply Native Supervisor Verifier result ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=m.children.find(({name:y})=>y===t.child);if(!h?.task||h.task.role!=="verifier"||!h.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${t.child}`);try{lk(h.task,h.candidateCommit,"verifier",`comet/supervisor/${m.parent}/${t.child}`)}catch(y){throw await q(e.paths,Ua(m,{child:t.child,runId:t.runId,reason:y.message})),y}let g=t.evidence.receiptRef||t.verdict==="pass"?await _n({paths:e.paths,parent:e.name,task:h.task,receiptRef:t.evidence.receiptRef??""}):null;if(t.verdict==="pass"&&(!g||g.checks.some(({status:y,exitCode:b})=>y!=="passed"||b!==0)))throw new Error("Native Supervisor verification cannot pass before every Runtime check succeeds");let v=Tf(m,{...t,evidence:{...t.evidence,checks:g?.checks.map(({name:y,status:b})=>`${y}: ${b}`)??[],execution:structuredClone(h.task)}});await q(e.paths,v);let w=await $(e.paths,e.name);return{state:w,supervisorState:v,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(w)}});if(n&&t.kind==="supervisor-integrate"){let m=await Gp({paths:e.paths,state:n,name:t.child,checks:[],checkPlans:t.checks,...t.retry_check_ids===void 0?{}:{retryCheckIds:t.retry_check_ids}}),h=await Go({paths:e.paths,name:e.name,trigger:"v2-integrate"}),g=h.state;return{state:g,supervisorState:m,supervisorTask:null,checks:t.checks,requestChecks:null,verifierDispatch:null,parentAdvance:h.parentAdvance,continuation:K(g)}}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 h=Cf().captureExecutionIdentity({identityProvider:Ne,executionRef:ck("builder")}),g=await yh({paths:e.paths,name:e.name,input:{identity:h,summary:t.summary,addressedAcceptanceIds:t.addressed_acceptance_ids,checks:t.checks,knownLimits:t.known_limits,review:t.review?{status:t.review.status,summary:t.review.summary,reviewerExecutionRef:t.review.reviewer_execution_ref}:null}});if(t.verification_checks!==void 0){let v=await zo({paths:e.paths,name:e.name,plans:t.verification_checks,...o&&n?{projectRoot:n.integration.worktree}:{}}),w=v.checks.filter(({status:S})=>S==="failed").map(({id:S})=>S),y=v.checks.filter(({status:S})=>S==="interrupted").map(({id:S})=>S),b=t.verification_checks.filter(({id:S,repeatable:N})=>y.includes(S)&&!N).map(({id:S})=>S);if(w.length>0||b.length>0){let S=w.length>0?`Builder handoff Runtime checks failed: ${w.join(", ")}`:`Builder handoff Runtime checks were interrupted and cannot be repeated: ${b.join(", ")}`,N=await Hi({paths:e.paths,name:e.name,reason:S,failureBudget:{maxVerifyFailures:e.maxVerifyFailures}});return{state:N,checks:v.checks,runtimeCheckExecution:{disposition:v.disposition},requestChecks:null,verifierDispatch:null,continuation:K(N)}}return{state:v.state,checks:v.checks,runtimeCheckExecution:{disposition:v.disposition},continuationCheckPlans:t.verification_checks,...y.length>0?{continuationRetryCheckIds:y}:{},requestChecks:null,verifierDispatch:null,continuation:K(v.state,void 0,{...y.length>0?{retryCheckIds:y}:{verificationCheckPlans:t.verification_checks}})}}return{state:g,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(g)}}if(t.kind==="retry-checks"){if(n&&!a)throw new Error("Native Supervisor check retry is only valid after every Child is integrated");let m=await $(e.paths,e.name);Vn(m);let h=await gh({paths:e.paths,name:e.name,checkIds:t.check_ids,...a&&n?{projectRoot:n.integration.worktree}:{}}),g=h.checks.filter(({status:v})=>v==="interrupted").map(({id:v})=>v);if(g.length>0){let w=((await Se(D(e.paths,e.name)))?.checks??[]).filter(({id:y,status:b,executionCount:S})=>g.includes(y)&&b==="interrupted"&&S>=3).map(({id:y})=>y);if(w.length>0){let y=await Hi({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:y,checks:h.checks,requestChecks:null,verifierDispatch:null,continuation:K(y)}}}return{state:h.state,checks:h.checks,...g.length>0?{continuationRetryCheckIds:g}:{},requestChecks:null,verifierDispatch:null,continuation:K(h.state,void 0,{retryCheckIds:g.length>0?g: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 m=await $(e.paths,e.name);if(m.builder_handoff!==null&&m.builder_handoff.identity_provider!==Ne){let b=await Hi({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:K(b)}}Vn(m);let h=await zo({paths:e.paths,name:e.name,plans:t.checks,...a&&n?{projectRoot:n.integration.worktree}:{}}),g=h.checks,v=g.filter(({status:b})=>b==="interrupted").map(({id:b})=>b);if(v.length>0){let b=t.checks.filter(({id:N,repeatable:x})=>v.includes(N)&&!x).map(({id:N})=>N);if(b.length>0)throw new Error(`Native non-repeatable checks were interrupted and require a new Builder candidate: ${b.join(", ")}`);let S=await $(e.paths,e.name);return{state:S,checks:g,runtimeCheckExecution:{disposition:h.disposition},continuationRetryCheckIds:v,requestChecks:null,verifierDispatch:null,continuation:K(S,void 0,{retryCheckIds:v})}}let w=ck("verifier"),y=await Nh({paths:e.paths,name:e.name,checks:g,verifierExecutionId:w,...a&&n?{projectRoot:n.integration.worktree}:{}});return{state:y,checks:g,runtimeCheckExecution:{disposition:h.disposition},requestChecks:null,verifierDispatch:uk({paths:e.paths,state:y,checks:g,verifierExecutionRef:w,supervisor:a?n:null}),continuation:K(y,void 0,{verifierExecutionRef:w})}}if(t.kind==="verifier-started"){let m=await bh({paths:e.paths,name:e.name,candidateId:t.candidateId,verifierExecutionRef:t.verifierExecutionRef});return{state:m,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(m)}}if(t.kind==="verifier-execution-error"){let m=await $(e.paths,e.name);Vn(m),await Oh({paths:e.paths,state:m});let h=await Sh({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:h,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(h)}}if(t.kind==="verifier-unavailable"){let m=await Eh({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:m,checks:m.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:K(m)}}if(t.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let s=await $(e.paths,e.name),c=Vn(s),l=await Oh({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=Cf(),f=u.captureExecutionIdentity({identityProvider:Ne,executionRef:l}),d=null;if(a&&typeof t.response=="object"&&t.response!==null&&"kind"in t.response&&t.response.kind==="final-result"){let m=await O(e.paths,e.name);if(!m)throw new Error("Native Supervisor state disappeared before final verification");d=Ii(m)}let p=await kh({paths:e.paths,name:e.name,envelope:u.envelopeVerifierResponse({candidateId:c.candidate_id,identity:f,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:g})=>g!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let m=d??await O(e.paths,e.name);if(!m)throw new Error("Native Supervisor state disappeared during verification");let h=Ti(m,p.state);return await q(e.paths,h),{...p,supervisorState:h,verifierDispatch:null,continuation:K(p.state)}}return{...p,verifierDispatch:p.requestChecks===null?null:uk({paths:e.paths,state:p.state,checks:p.checks,verifierExecutionRef:await Oh({paths:e.paths,state:p.state}),supervisor:a?n:null}),continuation:K(p.state,void 0,{verifierExecutionRef:l})}}mi();cn();Ta();import Xo from"path";import{realpathSync as h0}from"fs";function pk(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 wr={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function hk(e){return e?e.command?`${wr.next} ${e.command}`:e.ask_user?`${wr.next} ${e.ask_user}`:null:null}function mk(e,t){let r=[e.summary],i=hk(e.next);return i&&r.push(i),e.user_message&&r.push("",wr.relay,e.user_message),t!==void 0&&r.push("",wr.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
289
|
+
`)}async function fh(e){let t=se(e.paths,e.state.name),r=[...(await lh(t,e.state.brief,{strict:!0})).findings],i="";try{i=(await Q({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&&!F$(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 f=(await Q({root:t,ref:u,maxBytes:null,includeHash:!1})).text;r.push(...db(f,u).findings)}catch(f){r.push({code:"spec-document-missing",message:`Target Spec cannot be read: ${f.message}. Restore the complete file at ${u}.`,path:u})}}return{valid:r.length===0,findings:r}}async function Gl(e){let t=await fh(e);if(!t.valid)throw new Error(gb(t.findings,{change:e.state.name,phase:e.state.phase}))}function Tt(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 Ul(e){let t=se(e.paths,e.state.name),r=$i.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await zl.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(!rh.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=$i.join(t,...s.split("/")),l=await zl.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=$i.join(e.paths.specsDir,o.name,"spec.md"),f="create",d=null;try{let g=await zl.lstat(u);if(!g.isFile()||g.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);f="modify",d=ur((await Q({root:e.paths.specsDir,ref:`${o.name}/spec.md`,maxBytes:null,includeHash:!1})).text)}catch(g){if(g.code!=="ENOENT")throw g}let p=`specs/${o.name}/${Ww}`,m=$i.join(t,...p.split("/")),h={};try{let g=await zl.lstat(m);if(!g.isFile()||g.isSymbolicLink())throw new Error(`Native delta manifest must be a regular file: ${p}`);let v=await Q({root:t,ref:p,maxBytes:null,includeHash:!1}),w=io(v.text);if(w.capability!==o.name)throw new Error(`Native delta capability ${w.capability} does not match directory ${o.name}`);let y=d??ur(""),b=e.state.spec_changes.find(S=>S.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!==y)throw new Error(`Native delta base_hash does not match the current total Spec for ${o.name}`);h={delta_source:p,base_hash:w.base_hash}}catch(g){if(g.code!=="ENOENT")throw g}a.push({capability:o.name,operation:f,source:s,...h})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Kl(e){let t=se(e.paths,e.state.name),r=await Q({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(ch(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 Q({root:t,ref:o.source,maxBytes:null,includeHash:!1}),c=s.text,l=null;if(o.delta_source){let u=await Q({root:t,ref:o.delta_source,maxBytes:null,includeHash:!1}),f=io(u.text);c=Uw(s.text,f);let d="";try{d=(await Q({root:e.paths.specsDir,ref:`${o.capability}/spec.md`,maxBytes:null,includeHash:!1})).text}catch(p){if(p.code!=="ENOENT")throw p}if(ur(d)===f.base_hash){let p=Yw({baselineMarkdown:d,delta:f,allowAlreadyApplied:!0});if(ur(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=T("comet.native.shape-artifact-content.v1",Jl(u.text))}i.push({capability:o.capability,source:s.ref,markdown:c}),n.push({...o,contentHash:T("comet.native.shape-artifact-content.v1",Jl(s.text)),...l===null?{}:{deltaContentHash:l}})}let a=null;try{let o=await Q({root:t,ref:vb,maxBytes:65536,includeHash:!1}),s=mb(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=$i.relative(e.paths.projectRoot,$i.join(e.paths.specsDir,s.capability,"spec.md")).replaceAll($i.sep,"/");if(s.current_spec!==l)throw new Error(`Native capability association points to ${s.current_spec}, expected ${l}`);a=T("comet.native.shape-artifact-content.v1",Jl(o.text))}catch(o){if(o.code!=="ENOENT")throw o}return{acceptance:rl({briefMarkdown:r.text,specs:i}),formalHash:T("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:T("comet.native.shape-artifact-content.v1",Jl(r.text))},specs:n,association:{source:vb,contentHash:a}})}}function Yl(e){return T("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function ph(e){return _(e.paths,`prepare portable shape confirmation ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(Tt({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 Ul({paths:e.paths,state:t});e.enforceDocumentConstraints===!0&&await Gl({paths:e.paths,state:t,specChanges:r});let i=await Kl({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Fe({changeDir:se(e.paths,t.name),acceptanceIds:n.map(({id:d})=>d),validation:dt({...t,acceptance:n})}),o=t;if(a&&t.workspace.change_branch===null){await Hc(e.paths,t.name);let d=Fl(t.workspace,e.paths.projectRoot);if(d===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=ye({...t,workspace:d},{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(`Native workspace bound to branch ${d.change_branch} at the Supervisor Shape confirmation boundary`),completed_at:new Date().toISOString()})}let s=await _o(se(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:Yl({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=FN({state:l,acceptance:n.map(d=>({...d}))});e.enforceDocumentConstraints===!0&&(u.document_constraints_version=1),a&&(u.children_contract_hash=An({acceptance:u.acceptance,children:a.contract}));let f=await ce({paths:e.paths,previous:t,next:u});return await F(D(e.paths,t.name),re({portableState:f,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),f})}async function Bo(e){if(e.state.document_constraints_version===1){let l=await fh(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 Ul(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 f=e.state.spec_changes[u];return f!==void 0&&l.capability===f.capability&&l.source===f.source&&l.delta_source===f.delta_source&&l.base_hash===f.base_hash&&(l.operation===f.operation||r?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await Kl({...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(!my(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await Fe({changeDir:se(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:dt({...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&&Yl({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?An({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 Je(e){let t=await Bo(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await qo({paths:e.paths,state:e.state,reason:r,keepFailureBudget:!0}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function Lo(e){return _(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await $(e.paths,e.name);if(Tt({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:qo({paths:e.paths,state:t,reason:e.reason,...e.keepFailureBudget?{keepFailureBudget:!0}:{}})})}async function qo(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...ye(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(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 ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),re({portableState:n,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}function eu(e,t){let r=j.relative(j.resolve(e),j.resolve(t));if(j.isAbsolute(r)||r===".."||r.startsWith(`..${j.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(j.sep).join("/");return Za(e,i),i}function V$(e){return e.split("\0").some(t=>t.startsWith("160000 "))}function Xl(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return vn({id:e.id,name:e.name,executable:r,argv:i,cwdRef:eu(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function Sb(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:eu(t,r.cwd),timeoutMs:r.timeoutMs,repeatable:r.repeatable}})}function Eb(e,t,r,i,n,a){return e.candidateId!==i.builder_handoff?.candidate_id||e.inputFingerprint!==n||j.resolve(e.workspace.projectRoot)!==j.resolve(r)||j.resolve(e.workspace.worktreeRoot)!==j.resolve(r)||e.workspace.branch!==a||e.workspace.machineId!==Zr.hostname()||e.checks.length!==t.length?!1:e.checks.every((o,s)=>Xl(o,r)===vn(t[s]))}function wb(e,t,r){return e.checks.length===t.length&&e.checks.every((i,n)=>Xl(i,r)===vn(t[n]))}async function Ql(e){let t=e.execution;if(t===null||t.status!=="running")return"not-running";if(t.ownerPid===void 0)return"unknown";let r=await hn(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 hn(a.pid,a.identity);if(o==="alive")return"running";o==="unknown"&&(i=!0)}return i?"unknown":"orphaned"}function yb(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 Zl(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:Za(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`,activeProcess:null}}function xb(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 Cb(e,t,r,i)}function Cb(e,t,r,i){return{...Zl(t,r,i),executionCount:e.executionCount}}function Rb(e){return bb("sha256").update(e).digest("hex")}async function Mo(e){let t=await Qt.lstat(e);if(!t.isFile())throw new Error("Native check input must be a regular file");let r=bb("sha256"),i=await Qt.open(e,"r"),n=0;try{let o=Buffer.allocUnsafe(M$);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 Qt.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 Pb=2e4,_b=1024*1024*1024,M$=65535,Ab=["build","dist","gen","generated","out","target",".next",".nuxt",".output",".svelte-kit"],W$=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"]),hh=[":(exclude).comet/runtime/**",":(exclude).comet/current-change.json"],Ib=new Set(["comet-state.yaml","children.yaml","verification.md"]);function Bn(e,t){if(!t)return[...hh];let r=j.relative(e,t).replaceAll("\\","/");if(j.isAbsolute(r)||r===".."||r.startsWith("../"))return[...hh];let i=r===""?"":`${r}/`;return[...hh,...["changes","archive"].flatMap(n=>[...Ib].map(a=>`:(exclude)${i}comet/${n}/**/${a}`))]}function mh(e,t,r){let i=e.replaceAll("\\","/").replace(/^\.\//u,"");if(i===".comet/current-change.json"||i.startsWith(".comet/runtime/"))return!0;if(!t||!r||!Ib.has(j.basename(i)))return!1;let n=j.resolve(t,...i.split("/")),a=j.relative(j.resolve(r),n);if(j.isAbsolute(a)||a===".."||a.startsWith(`..${j.sep}`))return!1;let[,o]=a.split(j.sep);return a.startsWith(`comet${j.sep}`)&&(o==="changes"||o==="archive")}function Dn(){return{complete:!1,files:[]}}function z$(e){let t=e==="."?"":`${e}/`;return Ab.flatMap(r=>[`:(glob)${t}${r}/**`,`:(glob)${t}**/${r}/**`])}function Tb(e){return/(?:^|\/)(?:\.env(?:\..*)?|[^/]+\.(?:key|pem|p12|pfx))$/iu.test(e)}async function jb(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(I(e,["ls-files","--others","--ignored","--exclude-standard","-z","--",...i.flatMap(z$)]).split("\0").filter(Boolean).map(s=>s.replaceAll("\\","/")))].sort()}catch{return Dn()}if(n.length>Pb)return Dn();let a=[],o=0;for(let s of n){if(mh(s,e,r))continue;let c=j.resolve(e,...s.split("/"));if(!be(e,c)||Tb(s))return Dn();try{let l=await Qt.lstat(c);if(!l.isFile()||o+l.size>_b)return Dn();let{digest:u,size:f}=await Mo(c);o+=f,a.push({path:s,digest:u,size:f})}catch{return Dn()}}return{complete:!0,files:a}}async function J$(e,t,r){let i=[...new Set(t.map(({cwdRef:c})=>c))],n=new Map,a=0,o=c=>Ab.includes(c),s=async(c,l,u)=>{let f;try{f=await Qt.readdir(c,{withFileTypes:!0})}catch{return!1}f.sort((d,p)=>d.name.localeCompare(p.name,"en"));for(let d of f){let p=l?`${l}/${d.name}`:d.name;if(mh(p,e,r)||d.isDirectory()&&W$.has(d.name))continue;let m=j.join(c,d.name);if(d.isDirectory()){if(!await s(m,p,u||o(d.name)))return!1;continue}if(u){if(Tb(p)||!d.isFile())return!1;try{let h=await Qt.lstat(m);if(a+h.size>_b)return!1;let{digest:g,size:v}=await Mo(m);if(a+=v,n.set(p,{path:p,digest:g,size:v}),n.size>Pb)return!1}catch{return!1}}}return!0};for(let c of i){let l=Za(e,c);if(!await s(l,c==="."?"":c,o(j.basename(l))))return Dn()}return{complete:!0,files:[...n.values()].sort((c,l)=>c.path.localeCompare(l.path,"en"))}}function vh(e,t){return T("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:j.resolve(e.cwd),exitCode:e.exitCode,startedAt:e.startedAt,completedAt:e.completedAt,log:e.log,logDigest:Rb(t)})}async function G$(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=I(e.projectRoot,["rev-parse","HEAD"]),r=!0,t.branch=I(e.projectRoot,["branch","--show-current"]),t.status=I(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--",...Bn(e.projectRoot,e.managedArtifactRoot)]);let i=I(e.projectRoot,["diff","--name-only","-z","HEAD","--",...Bn(e.projectRoot,e.managedArtifactRoot)]).split("\0").filter(Boolean).sort();t.diff=await th(i,4,async o=>{let s=j.resolve(e.projectRoot,...o.split("/"));try{let{digest:c}=await Mo(s);return{path:o,digest:c}}catch{return{path:o,digest:null}}}),t.diff.some(({digest:o})=>o===null)&&(t.complete=!1);let n=I(e.projectRoot,["ls-files","--stage","-z","--",...Bn(e.projectRoot,e.managedArtifactRoot)]);t.stagedDiff=Rb(n),t.submodules=V$(n)?I(e.projectRoot,["submodule","status","--recursive"]):"";let a=I(e.projectRoot,["ls-files","--others","--exclude-standard","-z","--",...Bn(e.projectRoot,e.managedArtifactRoot)]).split("\0").filter(Boolean).sort();t.untracked=await th(a,4,async o=>{let s=j.resolve(e.projectRoot,...o.split("/"));try{let{digest:c,size:l}=await Mo(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 jb(e.projectRoot,e.plans,e.managedArtifactRoot),t.ignored.complete||(t.complete=!1)}catch{r?t.complete=!1:(t.capture="physical-tree",t.physical=await J$(e.projectRoot,e.plans,e.managedArtifactRoot),t.complete=t.physical.complete)}return T("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:j.resolve(e.projectRoot),machineId:Zr.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])=>$b.has(i.toUpperCase())).map(([i,n])=>[i,n??null]).sort(([i],[n])=>i.localeCompare(n))})}var $b=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 U$(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function K$(){return Object.entries(process.env).filter(([e])=>$b.has(e.toUpperCase())).map(([e,t])=>[e,t??null]).sort(([e],[t])=>e.localeCompare(t))}async function Nb(e){try{let t=I(e.projectRoot,["rev-parse","HEAD"]),r=I(e.projectRoot,["branch","--show-current"]),i=I(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none","--",...Bn(e.projectRoot,e.managedArtifactRoot)]),n=I(e.projectRoot,["ls-files","--stage","-z","--",...Bn(e.projectRoot,e.managedArtifactRoot)]);if(t===null||i===null)return null;let a=[];for(let s of ka(e.projectRoot).filter(c=>!mh(c,e.projectRoot,e.managedArtifactRoot))){let c=j.resolve(e.projectRoot,...s.split("/")),l=null;try{l=(await Mo(c)).digest}catch{return null}a.push({path:s,digest:l})}a.sort((s,c)=>s.path.localeCompare(c.path,"en"));let o=await jb(e.projectRoot,e.plans??[],e.managedArtifactRoot);return o.complete?T("comet.native.check-input-gate.v1",{candidateId:e.candidateId,head:t,branch:r,status:i,staged:n,workingTree:a,ignored:o,projectRoot:j.resolve(e.projectRoot),machineId:Zr.hostname(),execPath:process.execPath,node:process.version,platform:process.platform,arch:process.arch,boundEnvironment:K$()}):null}catch{return null}}function ei(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:J(i),argv_display:eo(r.argv.slice(1)).map(n=>J(n)),argv_truncated:!1,cwd_ref:eu(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:U$(r)}})}function Y$(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function Oi(e){if(e.local===null||e.local.change!==e.state.name)return re({portableState:e.state,projectRoot:e.projectRoot,branch:ve(e.projectRoot)});let t=e.local.execution?.operationId??kb();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 ti(e){try{let t=await Se(D(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 Wo(e){let t=await ti({paths:e.paths,state:e.state}),r=KN({state:e.state,summary:e.summary}),i=await ce({paths:e.paths,previous:e.state,next:r});return await F(D(e.paths,e.state.name),Oi({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}async function X$(e,t){for(let r of e.checks)if(r.status==="passed"){if(r.evidence!=="runtime")return!1;try{let i=await z(t,j.resolve(t,...r.log.split(/[\\/]/u)));if(!(await Qt.stat(i)).isFile())return!1;let n=await Qt.readFile(i,"utf8");if(!r.evidenceDigest||r.evidenceDigest!==vh(r,n))return!1}catch{return!1}}return!0}async function Q$(e){return _(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(await Je({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let r=ve(e.projectRoot),i=D(e.paths,t.name),n=(await Ll({file:i,portableState:t,projectRoot:e.projectRoot,branch:r,containedRoot:e.paths.runtimeDir})).state,a=await Nb({projectRoot:e.projectRoot,candidateId:t.builder_handoff?.candidate_id??null,plans:e.plans,managedArtifactRoot:e.paths.artifactRoot}),o=await Nb({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&&j.resolve(n.workspace.projectRoot)===j.resolve(e.projectRoot)&&j.resolve(n.workspace.worktreeRoot)===j.resolve(e.projectRoot)&&n.workspace.machineId===Zr.hostname()?n.inputFingerprint:await G$({state:t,projectRoot:e.projectRoot,plans:e.plans,managedArtifactRoot:e.paths.artifactRoot}),u=pe(e.paths,t.name),f=await X$(n,u),d=n.checks.every(k=>k.status==="passed"),p=e.retryCheckIds===void 0?null:new Set(e.retryCheckIds),m=n.candidateId===t.builder_handoff?.candidate_id&&j.resolve(n.workspace.projectRoot)===j.resolve(e.projectRoot)&&j.resolve(n.workspace.worktreeRoot)===j.resolve(e.projectRoot)&&n.workspace.branch===r&&n.workspace.machineId===Zr.hostname()&&n.inputFingerprint===l,h=o!==null&&n.candidateInputFingerprintGate===o&&n.candidateId===t.builder_handoff?.candidate_id&&j.resolve(n.workspace.projectRoot)===j.resolve(e.projectRoot)&&j.resolve(n.workspace.worktreeRoot)===j.resolve(e.projectRoot)&&n.workspace.branch===r&&n.workspace.machineId===Zr.hostname(),g=h&&n.inputFingerprint!==null&&n.inputFingerprint!==l,v=Eb(n,e.plans,e.projectRoot,t,l,r)||h&&wb(n,e.plans,e.projectRoot),w=n.candidateId===t.builder_handoff?.candidate_id&&j.resolve(n.workspace.projectRoot)===j.resolve(e.projectRoot)&&j.resolve(n.workspace.worktreeRoot)===j.resolve(e.projectRoot)&&n.workspace.branch===r&&n.workspace.machineId===Zr.hostname(),y=m&&d&&!f;if(p&&p.size===0)throw new Error("Native check retry list must contain at least one ID");if(!m&&n.execution?.stage==="checking"&&n.execution.actor==="runtime"&&n.execution.status==="running"){let k=await Ql(n);if(k!=="orphaned")throw new Error(k==="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=yb(n),await F(i,n,{containedRoot:e.paths.runtimeDir})}if(!m&&w&&n.inputFingerprint!==null&&(n.execution!==null||n.checks.length>0)){let k=n.inputFingerprint!==l;if(!(s&&!k||g)){let E=Yr({state:t,reason:"Native check input changed after the candidate was built; a new Builder candidate is required before checks can run again."}),C=await ce({paths:e.paths,previous:t,next:E});throw await F(i,re({portableState:C,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(!m&&!h){let k=re({portableState:t,projectRoot:e.projectRoot,branch:r});await F(i,k,{containedRoot:e.paths.runtimeDir}),n=k}let b=wb(n,e.plans,e.projectRoot);if(n.execution?.stage==="checking"&&n.execution.actor==="runtime"&&b&&v){let k=n.execution;if(k.status==="running"){let C=await Ql(n);if(C!=="orphaned")throw new Error(C==="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=yb(n),await F(i,n,{containedRoot:e.paths.runtimeDir}),k=n.execution}let E=n.checks.filter(C=>C.status==="interrupted");if(E.length===0&&k.status==="completed"&&d&&!y&&!g){let C=new Map(e.plans.map(({id:H,name:P})=>[H,P]));return{kind:"reuse",state:t,checks:ei({local:n,projectRoot:e.projectRoot,supplied:[],requestedNames:C})}}if(E.length===0&&k.status==="completed"&&!d&&!y&&!g)throw new Error(`Native check plan contains a failed check (${n.checks.filter(({status:C})=>C==="failed").map(({id:C})=>C).join(", ")}); submit a new Builder candidate`);if(E.length>0&&E.some(C=>!C.repeatable)&&!y){let C=Yr({state:t,reason:`A non-repeatable Runtime check was interrupted (${E.filter(P=>!P.repeatable).map(({id:P})=>P).join(", ")}); a new Builder candidate is required before it can run again.`}),H=await ce({paths:e.paths,previous:t,next:C});throw await F(D(e.paths,t.name),re({portableState:H,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${E.find(P=>!P.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}if(E.length>0&&p===null&&!y&&!g){let C=new Map(e.plans.map(({id:H,name:P})=>[H,P]));return{kind:"reuse",state:t,checks:ei({local:n,projectRoot:e.projectRoot,supplied:[],requestedNames:C})}}if(p){let C=[...p].filter(P=>!E.some(W=>W.id===P));if(C.length>0)throw new Error(`Native check retry IDs must refer to interrupted checks: ${C.join(", ")}`);let H=E.filter(P=>p.has(P.id)&&P.executionCount>=3);if(H.length>0)throw new Error(`Native check retry limit (3) reached: ${H.map(({id:P})=>P).join(", ")}`)}}if(n.execution!==null&&n.checks.length>0){if(!(n.execution.stage==="checking"&&n.execution.actor==="runtime"&&n.checks.some(E=>E.status==="interrupted")&&b)&&!y&&!g)throw new Error("Native check plan was already resolved with a different plan")}else if((n.execution!==null||n.checks.length>0)&&!y&&!g)throw new Error("Native check plan was already resolved with a different plan");let S=kb(),N=await Ke(process.pid),x={...n,candidateId:t.builder_handoff?.candidate_id??null,inputFingerprint:l,inputFingerprintGate:a,candidateInputFingerprintGate:o,workspace:{...n.workspace,projectRoot:j.resolve(e.projectRoot),worktreeRoot:j.resolve(e.projectRoot),branch:ve(e.projectRoot),machineId:Zr.hostname()},execution:{operationId:S,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0,ownerPid:process.pid,...N?{ownerIdentity:N}:{}},checks:e.plans.map(k=>{let E=n.checks.find(C=>C.id===k.id);return g&&E?Zl(k,S,e.projectRoot):y&&E?Cb(E,k,S,e.projectRoot):E?.status==="interrupted"&&(p===null||p.has(E.id))?xb(E,k,S,e.projectRoot):E?{...E,operationId:S,activeProcess:null}:Zl(k,S,e.projectRoot)})};return await F(i,x,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:x,plans:e.plans.filter(k=>{let E=n.checks.find(C=>C.id===k.id);return y||g||E===void 0||E.status==="interrupted"&&(p===null||p.has(E.id))})}})}async function Fo(e){return _(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await $(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=D(e.paths,t.name),i=await Se(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 F(r,n,{containedRoot:e.paths.runtimeDir}),n})}async function zo(e){let t=e.projectRoot??e.paths.projectRoot;Ye(t,e.plans);let r=[],i=new Set;for(let c of e.plans){to(t,c);let l=vn(c);i.has(l)||(i.add(l),r.push(c))}let n=await Q$({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return{...n,disposition:"reused"};let a=n.local.execution.operationId,o=pe(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await Fo({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(p=>p.id===c.id?{...p,status:"running",executionCount:p.executionCount+1,startedAt:l,activeProcess:{status:"starting"}}:p)})});let u=await Ni({projectRoot:t,runtimeDir:o,operationId:a,plan:c,onSpawn:async({pid:d})=>{let p=await Ke(d);await Fo({paths:e.paths,state:n.state,operationId:a,update:m=>({...m,checks:m.checks.map(h=>h.id===c.id?{...h,activeProcess:{status:"running",pid:d,...p?{identity:p}:{}}}:h)})})}}),f=await Qt.readFile(j.resolve(o,...u.logRef.split("/")),"utf8");await Fo({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(p=>{if(p.id!==c.id)return p;let m={...p,status:u.status,exitCode:u.exitCode,startedAt:u.startedAt,completedAt:u.completedAt,log:u.logRef,activeProcess:null,evidence:"runtime"};return{...m,evidenceDigest:vh(m,f)}})})})}await Fo({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await Fo({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 Se(D(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:ei({local:s,projectRoot:t,supplied:[]}),disposition:"executed"}}async function gh(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 $(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 Se(D(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:eu(t,c.cwd),timeoutMs:c.timeoutMs,repeatable:c.repeatable}});return zo({paths:e.paths,name:e.name,plans:s,projectRoot:t,retryCheckIds:e.checkIds})}async function Ob(e){let t=D(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>=Yp)throw new Error(`Native Verifier request-checks exceeded ${Yp} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let p of r.checks){let m=Xl(p,e.projectRoot);n.set(m,p),p.status!=="interrupted"&&i.set(m,p),a.set(p.id,m)}let o=new Map,s=new Map;for(let p of e.response.checks){let m=Y$(p);to(e.projectRoot,m);let h=vn(m),g=s.get(m.id);if(g!==void 0&&g!==h)throw new Error(`Native Verifier check ID ${m.id} refers to conflicting commands`);let v=a.get(m.id);if(v!==void 0&&v!==h)throw new Error(`Native Verifier check ID ${m.id} conflicts with a Runtime check`);s.set(m.id,h);let w=n.get(h);if(w?.status==="interrupted"&&!w.repeatable)throw new Error(`Native check ${w.id} was interrupted and is not repeatable; user resolution is required`);if(w?.status==="interrupted"&&w.executionCount>=3)throw new Error(`Native check retry limit (3) reached: ${w.id}`);o.has(h)||o.set(h,m)}Ye(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,f=new Map(c.map(([,p])=>[p.id,p.name])),d={...r,execution:{...r.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:u},checks:[...r.checks.map(p=>{let m=Xl(p,e.projectRoot),h=o.get(m);return h&&p.status==="interrupted"?xb(p,h,r.execution.operationId,e.projectRoot):p}),...l.filter(([p])=>!n.has(p)).map(([,p])=>Zl(p,r.execution.operationId,e.projectRoot))]};return await F(t,d,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:d,verifierExecutionRef:e.envelope.verifierExecutionRef,round:u,novelPlans:l.map(([,p])=>p),requestedNames:f,reusedCheckIds:c.filter(([p])=>i.has(p)).map(([,p])=>p.id),suppliedChecks:e.suppliedChecks}}async function Vo(e){return _(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await $(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=D(e.paths,t.name),i=await Se(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 F(r,a,{containedRoot:e.paths.runtimeDir}),a})}async function Hb(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await Vo({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=pe(e.paths,e.reservation.state.name),a=await Ni({projectRoot:e.projectRoot,runtimeDir:n,operationId:e.reservation.local.execution.operationId,plan:r,onSpawn:async({pid:s})=>{let c=await Ke(s);await Vo({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 Qt.readFile(await z(n,j.resolve(n,...a.logRef.split(/[\\/]/u))),"utf8");t=await Vo({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:vh(l,o)}})})})}t=await Vo({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await Vo({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:ei({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)}}}ne();Bc();rt();import{accessSync as yJ,constants as NJ,promises as qb}from"node:fs";import Mb from"node:path";st();le();st();le();gi();lr();ut();Fr();async function wh(e){return _(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(Tt({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 Je({paths:e.paths,state:t});let r=await Ul({paths:e.paths,state:t}),i=await Kl({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Fe({changeDir:se(e.paths,t.name),acceptanceIds:n.map(({id:v})=>v),validation:dt({...t,acceptance:n})}),o=t;if(a&&t.workspace.change_branch===null){await Hc(e.paths,t.name);let v=Fl(t.workspace,e.paths.projectRoot);if(v===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=ye({...t,workspace:v},{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(`Native workspace bound to branch ${v.change_branch} at the Supervisor Shape confirmation boundary`),completed_at:new Date().toISOString()})}let s=await _o(se(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=Yl({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:c});if(t.shape_confirmation_hash===void 0||l!==t.shape_confirmation_hash){let v=t.shape_confirmation_hash===void 0?"Native Shape confirmation fingerprint is missing":"Native Shape artifacts changed";throw await qo({paths:e.paths,state:t,reason:v,keepFailureBudget:!0}),new Error(`${v}; Native change returned to Shape and requires confirmation`)}let u=qN({state:{...o,spec_changes:r},acceptance:n.map(v=>({...v}))});if(delete u.children_contract_hash,delete u.coordination_mode,a){u.children_contract_hash=An({acceptance:u.acceptance,children:a.contract}),s&&(u.coordination_mode=c);let v=[...t.history].reverse().find(({outcome:w})=>w==="pass"||w==="fail");if(v?.outcome==="fail"&&v.unresolved_ids.length>0){let w=await je({paths:e.paths,state:u}),y=new Map((w?.children??[]).map(({name:N,status:x})=>[N,x])),b=new Set(a.contract.children.filter(({name:N})=>{let x=y.get(N);return x!=="done"&&x!=="integrated"&&x!=="archived"}).flatMap(({covers:N})=>N)),S=v.unresolved_ids.filter(N=>!b.has(N));if(S.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${S.join(", ")}`)}}let f=null,d=a?.contract.schema==="comet.native.children.v2"?await O(e.paths,t.name):null,p=null,m=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(m=ar(e.paths.projectRoot,p),!m)throw new Error(`Native Supervisor target branch has no commit: ${p}`);d||(d=await Po({paths:e.paths,parent:t.name,targetBranch:p,contract:a.contract})),d||(f=await zp({projectRoot:e.paths.projectRoot,parent:t.name,targetBranch:p,sourceConfig:await _e(e.paths.projectRoot)}))}let h=a?.contract.schema==="comet.native.children.v2"&&p&&m?d?_f({state:d,contract:a.contract}):f?Ja({parent:u.name,targetBranch:p,targetCommit:m,integrationBranch:f.binding.changeBranch,integrationWorktree:f.projectRoot,contract:a.contract}):null:null;if(a?.contract.schema==="comet.native.children.v2"&&!h)throw new Error("Native Supervisor integration state is unavailable");let g=await ce({paths:e.paths,previous:t,next:u});return await F(D(e.paths,t.name),re({portableState:g,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),h&&await q(e.paths,h),g})}import{randomUUID as Z$}from"node:crypto";import tu from"node:path";le();Ma();mi();function Db(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 eO(e){let{state:t,local:r,envelope:i}=e;if(!Ac(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 tO(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function yh(e){return _(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(await Je({paths:e.paths,state:t}),await Fe({changeDir:se(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a),validation:dt(t)})||t.children_contract_hash){let a=await je({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=VN({state:t,input:e.input}),n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),re({portableState:n,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function Nh(e){return _(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await Je({paths:e.paths,state:t});let i=(await Ll({file:D(e.paths,t.name),portableState:t,projectRoot:r,branch:ve(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");ei({local:i,projectRoot:r,supplied:e.checks});let n=MN(t),a=await ce({paths:e.paths,previous:t,next:n}),o=D(e.paths,t.name),s=Z$();return await F(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 bh(e){return _(e.paths,`confirm portable verifier start ${e.name}`,async()=>{let t=await $(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=D(e.paths,e.name),i=await Se(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 F(r,{...i,execution:{...n,verifierStartedAt:new Date().toISOString()}},{containedRoot:e.paths.runtimeDir}),t})}async function kh(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await _(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await $(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await Je({paths:e.paths,state:r});let n=await ti({paths:e.paths,state:r}),a=eO({state:r,local:n,envelope:e.envelope}),o;try{o=Va(a.payload)}catch(f){let d=`Native Verifier response was invalid: ${f.message}`,p=await Wo({paths:e.paths,state:r,summary:d});throw new Error(`${d}; execution error ${p.loop.execution_failure_count}/${Ao} was recorded`,{cause:f})}let s=tO(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=ei({local:n,projectRoot:i,supplied:e.checks}));let f=WN({state:r,envelope:a,checks:c,maxVerifyFailures:e.maxVerifyFailures});if(f.response.kind==="request-checks"){if(n===null)throw new Error("Native Verifier request-checks has no active local execution");let d=await Ob({paths:e.paths,projectRoot:i,state:r,local:n,envelope:a,response:f.response,suppliedChecks:c});return{kind:"request-checks",state:r,response:f.response,reservation:d}}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=f}catch(f){let d=`Native Verifier response was invalid: ${f.message}`,p=await Wo({paths:e.paths,state:r,summary:d});throw new Error(`${d}; execution error ${p.loop.execution_failure_count}/${Ao} was recorded`,{cause:f})}let u=await ce({paths:e.paths,previous:r,next:l.state});return await F(D(e.paths,r.name),u.loop.next_action==="resolve-verifier-blocker"||u.loop.next_action==="run-final-full-verification"?Oi({local:n,state:u,projectRoot:i}):re({portableState:u,projectRoot:i,branch:ve(i)}),{containedRoot:e.paths.runtimeDir}),u.verification!==null&&await Xr({file:tu.join(se(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 Hb({paths:e.paths,projectRoot:e.projectRoot??e.paths.projectRoot,reservation:t.reservation});return{state:t.state,response:t.response,checks:r.checks,requestChecks:r.requestChecks}}catch(r){let i=`Native Verifier response was invalid: ${r.message}`,n=await _(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await $(e.paths,e.name);return a.state_version!==t.state.state_version?null:Wo({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${Ao} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function Sh(e){return _(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await $(e.paths,e.name),r=await ti({paths:e.paths,state:t});if(Db({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 Wo({paths:e.paths,state:t,summary:e.summary})})}async function Eh(e){return _(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name);await Je({paths:e.paths,state:t});let r=await ti({paths:e.paths,state:t}),i=Db({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=ei({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=JN({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await ce({paths:e.paths,previous:t,next:a});return await F(D(e.paths,t.name),Oi({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await Xr({file:tu.join(se(e.paths,t.name),"verification.md"),state:o}),o})}async function xh(e){return _(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name);Tt({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await Je({paths:e.paths,state:t});let r=GN({state:t,summary:e.summary}),i=await ce({paths:e.paths,previous:t,next:r});return await F(D(e.paths,t.name),re({portableState:i,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Xr({file:tu.join(se(e.paths,t.name),"verification.md"),state:i}),i})}async function Ch(e){return _(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await $(e.paths,e.name);Tt({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await Je({paths:e.paths,state:t});let r=await ti({paths:e.paths,state:t}),i=UN(t,{reason:e.reason}),n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),Oi({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Rh(e){return _(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name);Tt({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await ti({paths:e.paths,state:t}),i=YN(t),n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),Oi({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Hi(e){return _(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await $(e.paths,e.name);if(Tt({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=e.preserveLocalChecks?await ti({paths:e.paths,state:t}):null,i=Yr({state:t,reason:e.reason,...e.failureBudget?{failureBudget:e.failureBudget}:{}}),n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),e.preserveLocalChecks?Oi({local:r,state:n,projectRoot:e.paths.projectRoot}):re({portableState:n,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function Jo(e){if(e.state.verification===null)return"not-applicable";let t=tu.join(se(e.paths,e.state.name),"verification.md");return await fb({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await Xr({file:t,state:e.state}),"rebuilt")}import rO from"node:path";lr();le();async function Ph(e){return _(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await $(e.paths,e.name);Tt({state:t,expected:e.expectedContinuation,action:"accept-result"}),await Je({paths:e.paths,state:t});let r=await O(e.paths,e.name);if(r?.finalVerification.status==="pending"){if(Ii(r).stateVersion!==r.stateVersion)return Hn({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; rerun the final full verification."});await q(e.paths,Ti(r,t))}let i=zN(t),n=await ce({paths:e.paths,previous:t,next:i});return await F(D(e.paths,t.name),re({portableState:n,projectRoot:e.paths.projectRoot,branch:ve(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Xr({file:rO.join(se(e.paths,t.name),"verification.md"),state:n}),n})}import{promises as Bb}from"node:fs";lr();le();cl();async function Go(e){let t=await $(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 je({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 Lb(e){let t=await $(e.paths,e.name),r=await sl(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 O(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 Bb.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=Ii(n);if(i||a.stateVersion!==n.stateVersion){let o=await Hn({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 Bb.rm(i.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await q(e.paths,Ti(n,t)),{state:t,action:"recorded-final-verification"}}async function ru(e){return _(e.paths,`recover Supervisor final verification ${e.name}`,()=>Lb(e),{allowedPortableTransaction:{kind:"archive",change:e.name}})}var uJ=16*1024;kn();Bc();var Fb="comet.native.workspace-finish.v1",iO="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Wb=new RegExp(`^${iO}$`,"u"),nO=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;function aO(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==Fb||typeof t.name!="string"||!Wb.test(t.name)||typeof t.transactionId!="string"||!nO.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!Mb.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:Fb,name:t.name,transactionId:t.transactionId,archiveDir:t.archiveDir,status:t.status,result:t.result,updatedAt:t.updatedAt}}function oO(e,t){if(!Wb.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return Mb.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function zb(e,t,r={}){let i=oO(e,t);try{let n=await qb.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=aO(JSON.parse(await qb.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}}import{randomUUID as sO}from"node:crypto";import{promises as Uo}from"node:fs";import cO from"node:path";ne();nt();le();lp();cl();il();ut();te();var Jb=["evidence.md","repair.md","archive.md","checkpoint.md"],lO="verification.md";async function uO(e,t){let r=await sl(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function Gb(e,t){await Uo.mkdir(e.transactionsDir,{recursive:!0}),await we(ol(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Ub(e,t,r={}){let i=r.removeVerificationReport===!1?Jb:[...Jb,lO];await Promise.all([Uo.rm(pe(e,t),{recursive:!0,force:!0}),Uo.rm(gf(e,t),{recursive:!0,force:!0}),...i.map(n=>Uo.rm(cO.join(At(e,t),n),{force:!0}))])}async function Kb(e,t){await F(D(e,t.name),re({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function Yb(e,t){try{let r=await Oo(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 Xb(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 dO(e){let t=At(e.paths,e.state.name),r=await Q({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 Q({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return rl({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Qb(e,t){let r=await sb(e,t);if(r.status==="runtime-incompatible")throw new Vt(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function Zb(e){return _(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await uO(e.paths,e.name),r=await $n(e.paths,e.name)?await lt(Qe(e.paths,e.name)):null;if(!t&&r)return await Ub(e.paths,e.name,{removeVerificationReport:!1}),await Kb(e.paths,r),r;let i=null,n=null;for(t||(i=await Qb(e.paths,e.name),n=await Yb(e.paths,e.name),Xb(e.paths,n),t={schema:nl,id:sO(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Gb(e.paths,t));;){let a=gy(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await Qb(e.paths,e.name),n??=await Yb(e.paths,e.name),Xb(e.paths,n),r=vy({state:i,acceptance:await dO({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await La(Qe(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Ub(e.paths,e.name):a.action==="commit-transaction"&&(r??=await lt(Qe(e.paths,e.name)),await Kb(e.paths,r)),t={...t,status:a.nextStatus},await Gb(e.paths,t)}return await Uo.rm(ol(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??lt(Qe(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as tk}from"node:fs";import rk from"node:path";le();import{promises as _h}from"node:fs";import fO from"node:path";fe();var pO=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),hO=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),mO=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task","builderFailureCount"]),vO=new Set(["status","summary"]);function iu(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function nu(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 gO(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function Di(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function wO(e,t,r,i){let n=iu(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=nu(n,pO,"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=iu(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=nu(o,hO,"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=iu(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=nu(c,vO,"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,f]of n.children.entries()){let d=iu(f,`Native Supervisor child ${u}`);if(!d)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:p,contractHash:m,...h}=d,g=nu(h,mO,`Native Supervisor child ${u}`,new Set(["builderFailureCount"]));if(g)return g;let v=r.children[u],w=v.covers.length>0?v.covers.map(b=>({id:b,source:r.acceptance_index?.[b]?.source??"brief.md",text:r.acceptance_index?.[b]?.text??b})):[{id:`child:${v.name}`,source:"children.yaml",text:v.summary??v.name}];if(p!==void 0&&JSON.stringify(p)!==JSON.stringify(w)||m!==void 0&&m!==T("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${v.name} acceptance scope does not match the legacy contract`;if(d.name!==v.name||d.summary!==v.summary||!gO(d.dependsOn,v.depends_on))return`Native Supervisor child ${v.name} does not match the legacy children contract`;let y=v.depends_on.length===0?"ready":"pending";if(d.status!==y)return`Native Supervisor child ${v.name} has progressed beyond its initial ${y} status`;if(d.baseCommit!==null||d.candidateCommit!==null||d.verifiedCommit!==null||d.integrationCommit!==null||d.verification!==null||d.blocker!==null||d.projectRoot!==null||d.task!==null)return`Native Supervisor child ${v.name} contains execution progress`;if((d.builderFailureCount??0)!==0)return`Native Supervisor child ${v.name} contains Builder failure progress`;if(!Array.isArray(d.checks)||d.checks.length!==0)return`Native Supervisor child ${v.name} contains integration checks`}return null}async function qn(e){let t=wi(e.paths,e.state.name),r;try{let c=await _h.lstat(t);if(!c.isFile()||c.isSymbolicLink())return Di(t,"","Native Supervisor overlay is not a regular file");r=await _h.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:Di(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return Di(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=fO.join(e.paths.changesDir,e.state.name),a;try{a=await Fe({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return Di(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 O(e.paths,e.state.name)}catch(c){return Di(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return Di(t,r,"Native Supervisor overlay disappeared during inspection");let s=wO(i,e.state,a.contract,o);return s?Di(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 ek(e){let t=await qn({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 _h.rm(t.file,{force:!1})}ut();Fr();function Ah(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 yO(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function NO(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:ye(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:J(t),completed_at:i});return B({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?yO(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 bO(e){try{let t=await Se(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 Ih(e){return _(e.paths,`recover portable change ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(t.status==="done")return await Jo({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=Ah(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await qn({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 ek({paths:e.paths,state:t,expected:i}),n=!0);let a=D(e.paths,e.name),o=await bO(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 h=o.local.execution,g=await Ql(o.local),v=h.stage==="verifying"&&h.actor==="verifier"&&h.executionId!==null,w=g==="unknown"&&e.recoverUnknownRuntimeCheck===!0&&h.stage==="checking"&&h.actor==="runtime";if(v||g!=="orphaned"&&!w)return{state:t,local:o.local,action:"await-user",reason:"execution-active",message:v?h.verifierStartedAt===void 0&&h.requestCheckRounds===0?`Native Verifier execution ${h.executionId} is registered but never confirmed startup; if the task did not start, record an explicit Verifier failure before retrying it.`:`Native Verifier execution ${h.executionId} remains owned by its host task; record an explicit Verifier failure before retrying it.`:g==="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(h=>h.status==="planned"||h.status==="running"?{...h,status:"interrupted"}:h)},await F(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await Jo({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(h=>h.status==="interrupted"&&!h.repeatable):void 0;if(l){let h=Yr({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await dn({file:Qe(e.paths,t.name),expectedStateVersion:t.state_version,next:h,containedRoot:e.paths.nativeRoot}),await tk.rm(rk.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let g=re({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await F(a,g,{containedRoot:e.paths.runtimeDir}),{state:t,local:g,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",f=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",d=u||f;if(d){let h=NO(t,f?"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.",f);t=await dn({file:Qe(e.paths,t.name),expectedStateVersion:t.state_version,next:h,containedRoot:e.paths.nativeRoot})}let p=re({portableState:t,projectRoot:e.paths.projectRoot,branch:ie(e.paths.projectRoot).currentBranch});await tk.mkdir(rk.dirname(D(e.paths,t.name)),{recursive:!0}),await F(a,p,{containedRoot:e.paths.runtimeDir}),await Jo({paths:e.paths,state:t});let m=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:d?"reverify":"resume-stable-boundary",reason:s,message:m??(d?"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.`)}})}import ik from"node:path";function nk(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function xe(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:nk(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:nk(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=>ik.relative(t.projectRoot,ik.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}_c();function Th(e){return e.charCodeAt(0)===65279?e.slice(1):e}kn();rt();import{randomUUID as dk}from"node:crypto";import{promises as ak}from"node:fs";import Ko from"node:path";gn();Wp();Ma();le();mi();function Mn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function V(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 Fn(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>V(r,`${t}[${i}]`))}function kO(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=Mn(t,`Native Builder check ${r}`);if(ee(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:V(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function au(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=Mn(t,`Native Runtime check ${r}`);if(ee(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:V(i.id,`Native Runtime check ${r} id`),name:V(i.name,`Native Runtime check ${r} name`),executable:V(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:V(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function ok(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:V(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function SO(e){let t=Mn(e,"Native Supervisor evidence");return ee(t,["summary","checks","acceptance","receiptRef"],"Native Supervisor evidence","/evidence"),{summary:V(t.summary,"Native Supervisor evidence summary"),checks:Fn(t.checks,"Native Supervisor evidence checks"),acceptance:Tc(t.acceptance,"/evidence/acceptance"),...t.receiptRef===null?{}:{receiptRef:V(t.receiptRef,"Native Supervisor receipt ref")}}}function EO(e){let t=Mn(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"),ee(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=Mn(t.review,"Native Builder review");if(ee(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:V(n.summary,"Native Builder review summary"),reviewer_execution_ref:V(n.reviewer_execution_ref,"Native Builder reviewer execution ref")}}return{kind:"builder-handoff",summary:V(t.summary,"Native Builder summary"),addressed_acceptance_ids:Fn(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:kO(t.checks),...Object.hasOwn(t,"verification_checks")?{verification_checks:au(t.verification_checks)}:{},known_limits:Fn(t.known_limits,"Native Builder known limits"),review:i}}if(t.kind==="dispatch-verifier")return ee(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:au(t.checks)};if(t.kind==="retry-checks")return ee(t,["kind","check_ids"],"Native Runner check retry input"),{kind:"retry-checks",check_ids:Fn(t.check_ids,"Native check retry IDs")};if(t.kind==="verifier-response")return ee(t,["kind","candidateId","verifierExecutionRef","response"],"Native Runner Verifier input"),{kind:"verifier-response",candidateId:V(t.candidateId,"Native Runner Verifier candidateId"),verifierExecutionRef:V(t.verifierExecutionRef,"Native Runner Verifier verifierExecutionRef"),response:Va(t.response,"/response")};if(t.kind==="verifier-started")return ee(t,["kind","candidateId","verifierExecutionRef"],"Native Runner started input"),{kind:"verifier-started",candidateId:V(t.candidateId,"Native Runner started candidateId"),verifierExecutionRef:V(t.verifierExecutionRef,"Native Runner started verifierExecutionRef")};if(t.kind==="verifier-execution-error")return ee(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:V(t.summary,"Native Verifier execution error summary"),...ok(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return ee(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:V(t.summary,"Native unavailable Verifier summary"),...ok(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return ee(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId"),candidateCommit:V(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return ee(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId"),reason:V(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-retry-builder"){if(ee(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:V(t.child,"Native Supervisor child"),stateVersion:t.stateVersion}}if(t.kind==="supervisor-reconnect")return ee(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return ee(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId"),reason:V(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(ee(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:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:SO(t.evidence)}}if(t.kind==="supervisor-checks"){let r=["kind","child","runId","checks","materials"];if(ee(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:V(t.child,"Native Supervisor child"),runId:V(t.runId,"Native Supervisor runId"),checks:au(t.checks),...t.retry_check_ids===void 0?{}:{retry_check_ids:Fn(t.retry_check_ids,"Native Supervisor retry IDs")},materials:t.materials.map((i,n)=>{let a=Mn(i,"Native Supervisor material");return ee(a,["name","content"],"Native Supervisor material",`/materials/${n}`),{name:V(a.name,"Native Supervisor material name"),content:V(a.content,"Native Supervisor material content")}})}}if(t.kind==="supervisor-integrate"){let r=["kind","child","checks"];return ee(t,Object.hasOwn(t,"retry_check_ids")?[...r,"retry_check_ids"]:r,"Native Supervisor integration input"),{kind:"supervisor-integrate",child:V(t.child,"Native Supervisor child"),checks:au(t.checks),...t.retry_check_ids===void 0?{}:{retry_check_ids:Fn(t.retry_check_ids,"Native Supervisor retry IDs")}}}throw new Error("Native Runner input kind is invalid")}async function Hh(e,t){let r=Ko.resolve(t,e),i=await ak.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(Th(await ak.readFile(r,"utf8")))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return EO(n)}function xO(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 CO(e){return e.kind.startsWith("supervisor-")}function RO(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 sk(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 jh(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 PO(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 $h(e){let t=await Se(D(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 Dh(e){let t=await qn({paths:e.paths,state:e.state});if(t.status==="incompatible")throw new Error(t.message);let r=t.status==="repairable-legacy-overlay"?null:await O(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 je({paths:e.paths,state:e.state}),o=(i||n)&&r?r.integration.worktree:e.projectRoot;if(CO(e.input)&&r===null)throw new Error("Native Supervisor Runner input requires a current Supervisor state");if(r&&xO(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(PO(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&&Ye(o,e.input.verification_checks);return}if(e.input.kind==="dispatch-verifier"){if(sk(e.state),i&&e.input.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");Ye(o,e.input.checks);return}if(e.input.kind==="retry-checks"){if(sk(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 Se(D(e.paths,e.name));for(let l of e.input.check_ids){let u=c?.checks.find(f=>f.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"){jh(e.state);let c=await $h({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");Ye(o,RO(e.input));return}if(e.input.kind==="verifier-started"){jh(e.state);let c=await $h({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"){jh(e.state);let c=await $h({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)<cr)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");Ye(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");Ye(r.integration.worktree,c.checks)}}function ck(e){return`${Ne}:${e}:${dk()}`}function lk(e,t,r,i){if(Ko.resolve(I(e.projectRoot,["rev-parse","--show-toplevel"]))!==Ko.resolve(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree identity is invalid`);if(I(e.projectRoot,["branch","--show-current"])!==i)throw new Error(`Native Supervisor ${r} result came from the wrong Child worktree branch`);if(!zt(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree must be clean before returning a commit`);if(I(e.projectRoot,["rev-parse","HEAD"])!==t)throw new Error(`Native Supervisor ${r} result is not bound to the worktree HEAD`);try{I(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 _O(e,t){let r=ie(e.projectRoot),i=Ko.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==Ko.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=I(e.projectRoot,["rev-parse","HEAD"]);if(e.role==="verifier"){if(!zt(e.projectRoot)||n!==e.baseCommit)throw new Error("Native Supervisor Verifier task worktree is not at its candidate commit");return}try{I(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 Vn(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==Ne)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 AO(e){return[...e.history].reverse().find(({outcome:t})=>t==="recovery")?.summary}function uk(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=Vn(r),s=AO(r),c=r.acceptance.filter(({result:l})=>l==="pending").map(({id:l})=>l);return{coordination:Ne,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:se(t,r.name),supervisorStateRef:a?wi(t,r.name):null,briefRef:r.brief,specRefs:r.spec_changes.map(({capability:l,operation:u,source:f})=>({capability:l,operation:u,ref:f})),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 Oh(e){Vn(e.state);let t=await Se(D(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 fk(e){let t=e.input,r=await $(e.paths,e.name),i=await qn({paths:e.paths,state:r});if(i.status==="incompatible")throw new Error(i.message);let n=i.status==="repairable-legacy-overlay"?null:await O(e.paths,e.name),a=n!==null&&r?.phase==="verify"&&n.children.every(({status:m})=>m==="integrated"||m==="archived"),o=n!==null&&r?.phase==="build"&&n.children.every(({status:m})=>m==="integrated"||m==="archived");if(n&&t.kind==="supervisor-checks"){let m=await Mp({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}}),h=await O(e.paths,e.name),g=h?.children.find(({name:v})=>v===t.child)?.task;return{state:r,supervisorState:h,supervisorTask:g&&g.runId===t.runId?Lr(g,e.name,e.paths.projectRoot):null,checks:[],checkExecution:m,requestChecks:null,verifierDispatch:null,continuation:K(r)}}if(n&&t.kind==="supervisor-builder-result")return _(e.paths,`apply Native Supervisor Builder result ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=m.children.find(({name:b})=>b===t.child);if(!h?.task||h.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${t.child}`);try{lk(h.task,t.candidateCommit,"builder",`comet/supervisor/${m.parent}/${t.child}`)}catch(b){throw await q(e.paths,Ua(m,{child:t.child,runId:t.runId,reason:b.message})),b}let g=h.task.projectRoot,v=If(m,t),w=Ga(v,{role:"verifier",child:t.child,projectRoot:g,runId:dk()});await q(e.paths,w.state);let y=await $(e.paths,e.name);return{state:y,supervisorTask:Lr(w.task,e.name,e.paths.projectRoot),checks:[],requestChecks:null,verifierDispatch:null,continuation:K(y)}});if(n&&t.kind==="supervisor-builder-failure")return _(e.paths,`cancel Native Supervisor Builder task ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=m.children.find(({name:w})=>w===t.child);if(!h?.task||h.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${t.child}`);let g=jc(m,{child:t.child,runId:t.runId,reason:t.reason});await q(e.paths,g);let v=await $(e.paths,e.name);return{state:v,supervisorState:g,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(v)}});if(n&&t.kind==="supervisor-retry-builder")return _(e.paths,`retry Native Supervisor Builder task ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=jf(m,{child:t.child,expectedStateVersion:t.stateVersion});await q(e.paths,h);let g=await $(e.paths,e.name);return{state:g,supervisorState:h,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(g)}});if(n&&t.kind==="supervisor-reconnect")return _(e.paths,`reconnect Native Supervisor task ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=m.children.find(({name:w})=>w===t.child)?.task;if(!h||h.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);try{_O(h,`comet/supervisor/${m.parent}/${t.child}`)}catch(w){throw await q(e.paths,Ua(m,{child:t.child,runId:t.runId,reason:w.message})),w}let g=Af(m,{child:t.child,runId:t.runId});await q(e.paths,g.state);let v=await $(e.paths,e.name);return{state:v,supervisorState:g.state,supervisorTask:Lr(g.task,e.name,e.paths.projectRoot),checks:[],requestChecks:null,verifierDispatch:null,continuation:K(v)}});if(n&&t.kind==="supervisor-cancel")return _(e.paths,`cancel Native Supervisor task ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=jc(m,{child:t.child,runId:t.runId,reason:t.reason});await q(e.paths,h);let g=await $(e.paths,e.name);return{state:g,supervisorState:h,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(g)}});if(n&&t.kind==="supervisor-verifier-result")return _(e.paths,`apply Native Supervisor Verifier result ${t.child}`,async()=>{let m=await O(e.paths,e.name);if(!m)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=m.children.find(({name:y})=>y===t.child);if(!h?.task||h.task.role!=="verifier"||!h.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${t.child}`);try{lk(h.task,h.candidateCommit,"verifier",`comet/supervisor/${m.parent}/${t.child}`)}catch(y){throw await q(e.paths,Ua(m,{child:t.child,runId:t.runId,reason:y.message})),y}let g=t.evidence.receiptRef||t.verdict==="pass"?await _n({paths:e.paths,parent:e.name,task:h.task,receiptRef:t.evidence.receiptRef??""}):null;if(t.verdict==="pass"&&(!g||g.checks.some(({status:y,exitCode:b})=>y!=="passed"||b!==0)))throw new Error("Native Supervisor verification cannot pass before every Runtime check succeeds");let v=Tf(m,{...t,evidence:{...t.evidence,checks:g?.checks.map(({name:y,status:b})=>`${y}: ${b}`)??[],execution:structuredClone(h.task)}});await q(e.paths,v);let w=await $(e.paths,e.name);return{state:w,supervisorState:v,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(w)}});if(n&&t.kind==="supervisor-integrate"){let m=await Gp({paths:e.paths,state:n,name:t.child,checks:[],checkPlans:t.checks,...t.retry_check_ids===void 0?{}:{retryCheckIds:t.retry_check_ids}}),h=await Go({paths:e.paths,name:e.name,trigger:"v2-integrate"}),g=h.state;return{state:g,supervisorState:m,supervisorTask:null,checks:t.checks,requestChecks:null,verifierDispatch:null,parentAdvance:h.parentAdvance,continuation:K(g)}}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 h=Cf().captureExecutionIdentity({identityProvider:Ne,executionRef:ck("builder")}),g=await yh({paths:e.paths,name:e.name,input:{identity:h,summary:t.summary,addressedAcceptanceIds:t.addressed_acceptance_ids,checks:t.checks,knownLimits:t.known_limits,review:t.review?{status:t.review.status,summary:t.review.summary,reviewerExecutionRef:t.review.reviewer_execution_ref}:null}});if(t.verification_checks!==void 0){let v=await zo({paths:e.paths,name:e.name,plans:t.verification_checks,...o&&n?{projectRoot:n.integration.worktree}:{}}),w=v.checks.filter(({status:S})=>S==="failed").map(({id:S})=>S),y=v.checks.filter(({status:S})=>S==="interrupted").map(({id:S})=>S),b=t.verification_checks.filter(({id:S,repeatable:N})=>y.includes(S)&&!N).map(({id:S})=>S);if(w.length>0||b.length>0){let S=w.length>0?`Builder handoff Runtime checks failed: ${w.join(", ")}`:`Builder handoff Runtime checks were interrupted and cannot be repeated: ${b.join(", ")}`,N=await Hi({paths:e.paths,name:e.name,reason:S,failureBudget:{maxVerifyFailures:e.maxVerifyFailures}});return{state:N,checks:v.checks,runtimeCheckExecution:{disposition:v.disposition},requestChecks:null,verifierDispatch:null,continuation:K(N)}}return{state:v.state,checks:v.checks,runtimeCheckExecution:{disposition:v.disposition},continuationCheckPlans:t.verification_checks,...y.length>0?{continuationRetryCheckIds:y}:{},requestChecks:null,verifierDispatch:null,continuation:K(v.state,void 0,{...y.length>0?{retryCheckIds:y}:{verificationCheckPlans:t.verification_checks}})}}return{state:g,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(g)}}if(t.kind==="retry-checks"){if(n&&!a)throw new Error("Native Supervisor check retry is only valid after every Child is integrated");let m=await $(e.paths,e.name);Vn(m);let h=await gh({paths:e.paths,name:e.name,checkIds:t.check_ids,...a&&n?{projectRoot:n.integration.worktree}:{}}),g=h.checks.filter(({status:v})=>v==="interrupted").map(({id:v})=>v);if(g.length>0){let w=((await Se(D(e.paths,e.name)))?.checks??[]).filter(({id:y,status:b,executionCount:S})=>g.includes(y)&&b==="interrupted"&&S>=3).map(({id:y})=>y);if(w.length>0){let y=await Hi({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:y,checks:h.checks,requestChecks:null,verifierDispatch:null,continuation:K(y)}}}return{state:h.state,checks:h.checks,...g.length>0?{continuationRetryCheckIds:g}:{},requestChecks:null,verifierDispatch:null,continuation:K(h.state,void 0,{retryCheckIds:g.length>0?g: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 m=await $(e.paths,e.name);if(m.builder_handoff!==null&&m.builder_handoff.identity_provider!==Ne){let b=await Hi({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:K(b)}}Vn(m);let h=await zo({paths:e.paths,name:e.name,plans:t.checks,...a&&n?{projectRoot:n.integration.worktree}:{}}),g=h.checks,v=g.filter(({status:b})=>b==="interrupted").map(({id:b})=>b);if(v.length>0){let b=t.checks.filter(({id:N,repeatable:x})=>v.includes(N)&&!x).map(({id:N})=>N);if(b.length>0)throw new Error(`Native non-repeatable checks were interrupted and require a new Builder candidate: ${b.join(", ")}`);let S=await $(e.paths,e.name);return{state:S,checks:g,runtimeCheckExecution:{disposition:h.disposition},continuationRetryCheckIds:v,requestChecks:null,verifierDispatch:null,continuation:K(S,void 0,{retryCheckIds:v})}}let w=ck("verifier"),y=await Nh({paths:e.paths,name:e.name,checks:g,verifierExecutionId:w,...a&&n?{projectRoot:n.integration.worktree}:{}});return{state:y,checks:g,runtimeCheckExecution:{disposition:h.disposition},requestChecks:null,verifierDispatch:uk({paths:e.paths,state:y,checks:g,verifierExecutionRef:w,supervisor:a?n:null}),continuation:K(y,void 0,{verifierExecutionRef:w})}}if(t.kind==="verifier-started"){let m=await bh({paths:e.paths,name:e.name,candidateId:t.candidateId,verifierExecutionRef:t.verifierExecutionRef});return{state:m,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(m)}}if(t.kind==="verifier-execution-error"){let m=await $(e.paths,e.name);Vn(m),await Oh({paths:e.paths,state:m});let h=await Sh({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:h,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(h)}}if(t.kind==="verifier-unavailable"){let m=await Eh({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:m,checks:m.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:K(m)}}if(t.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let s=await $(e.paths,e.name),c=Vn(s),l=await Oh({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=Cf(),f=u.captureExecutionIdentity({identityProvider:Ne,executionRef:l}),d=null;if(a&&typeof t.response=="object"&&t.response!==null&&"kind"in t.response&&t.response.kind==="final-result"){let m=await O(e.paths,e.name);if(!m)throw new Error("Native Supervisor state disappeared before final verification");d=Ii(m)}let p=await kh({paths:e.paths,name:e.name,envelope:u.envelopeVerifierResponse({candidateId:c.candidate_id,identity:f,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:g})=>g!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let m=d??await O(e.paths,e.name);if(!m)throw new Error("Native Supervisor state disappeared during verification");let h=Ti(m,p.state);return await q(e.paths,h),{...p,supervisorState:h,verifierDispatch:null,continuation:K(p.state)}}return{...p,verifierDispatch:p.requestChecks===null?null:uk({paths:e.paths,state:p.state,checks:p.checks,verifierExecutionRef:await Oh({paths:e.paths,state:p.state}),supervisor:a?n:null}),continuation:K(p.state,void 0,{verifierExecutionRef:l})}}mi();cn();Ta();import Xo from"path";import{realpathSync as m0}from"fs";function pk(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 wr={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function hk(e){return e?e.command?`${wr.next} ${e.command}`:e.ask_user?`${wr.next} ${e.ask_user}`:null:null}function mk(e,t){let r=[e.summary],i=hk(e.next);return i&&r.push(i),e.user_message&&r.push("",wr.relay,e.user_message),t!==void 0&&r.push("",wr.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
290
290
|
`)}
|
|
291
291
|
`}function vk(e,t,r){let i=[e.summary],n=hk(e.next);return n&&i.push(n),e.user_message&&i.push("",wr.relay,e.user_message),i.push("",`${wr.detail} ${t}`),r!==void 0&&i.push("",wr.details,JSON.stringify(r,null,2)),i.join(`
|
|
292
|
-
`)}fe();nt();fe();var
|
|
293
|
-
`)}}let r=t.continuation;if(Sk(r)){let i=qh(r),n=
|
|
292
|
+
`)}fe();nt();fe();var IO=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});Gr();Mt();st();te();ne();Jt();ro();le();te();Mt();qr();fe();fe();Al();Cn();Jt();var gk={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:[]},TO=Xe("comet-native-runtime:v3:scope-reopen"),kU=[{skillVersion:"3",skillHash:Xe("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:Xe("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:Xe("comet-native-runtime:v1")}];Jt();Jt();no();var yk=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],rK=new Set(yk),LO=new Set([...yk,"minimum_runtime_version","revision"]),iK=new Set([...LO,"operation"]),qO=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),nK=new Set([...qO,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);tl();nt();nt();tl();fe();var lK={maxAcceptanceCriteria:el.maxCriteria};Gr();po();Cn();Al();import{execFile as KO}from"node:child_process";Dc();Vf();import{promisify as YO}from"node:util";ne();Jt();te();Mt();Sa();qr();le();ne();Ip();te();Dt();Gr();le();qr();var Yo=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};po();Tl();Cn();var lY=64*1024;var uY=3600*1e3;var dY=YO(KO);Tl();var ou=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}};Jt();Mt();ne();Dt();te();Mt();ml();ne();xi();Gr();var o6=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});Jt();ro();le();te();Mt();ml();var su=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"},cu=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"};te();st();function L(e,t,r){return e==="zh-CN"?r:t}var Bh={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function bk(e,t){return typeof e=="string"&&Bh[e]?L(t,Bh[e].en,Bh[e].zh):typeof e=="string"?e:""}function Lh(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 e0(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 kk(e,t){let r=[];e.failed>0&&r.push(L(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(L(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(L(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=L(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function Sk(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 qh(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function t0(e,t,r){return e==="done"?L(r,"complete","已完成"):e==="await-user"?L(r,"waiting for a user decision","等待用户决定"):e==="blocked"?L(r,"paused: needs attention","已暂停,需要处理"):t?L(r,"waiting for a user decision","等待用户决定"):L(r,"ready to continue","可继续推进")}function r0(e,t,r){let i=qh(e),n=[];r&&n.push(r);let a=L(i,`Change ${e.change}`,`需求 ${e.change}`),o=bk(e.phase,i),s=t0(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(kk(t,i));let c=e.userCommunication,l=Ek(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function Ek(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:L(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:L(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:L(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function i0(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function n0(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=bk(e.phase,t),n=e.status==="await-user"?L(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?L(t,"paused","已暂停"):e.status==="done"?L(t,"complete","已完成"):L(t,"in progress","进行中"),a=Lh(e.acceptance)?`${L(t,", ",",")}${kk(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function a0(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 o0(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 s0(e){if(e.healthy){let i=e.repaired?L("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):L("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=c0(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:L("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:L("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function c0(e){return Sk(e)?Ek(e,qh(e)):void 0}function xk(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(o0(t))return s0(t);if(i0(t)){let i=a0(t.items);return{summary:[t.total===t.items.length?L(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):L(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>n0(a,i))].join(`
|
|
293
|
+
`)}}let r=t.continuation;if(Sk(r)){let i=qh(r),n=r0(r,l0(t),d0(t,i));return u0(t)==="unconfirmed"?{...n,summary:`${n.summary}${L(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:L(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 l0(e){if(Lh(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Lh(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return e0(r.acceptance)}return null}function u0(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 d0(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return L(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?L(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function Ck(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:L("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:L("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:L("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:L("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:L("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:L("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:L("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:L("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:L("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}_c();var Rk=["--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."],Fh=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:Rk,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
|
|
294
294
|
comet native spec remove <change-name> <capability>
|
|
295
295
|
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>]
|
|
296
296
|
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>]
|
|
297
297
|
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]
|
|
298
298
|
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 lu(e,t){return`${e}:
|
|
299
299
|
${t.map(r=>` ${r}`).join(`
|
|
300
|
-
`)}`}function
|
|
300
|
+
`)}`}function f0(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return Fh[r]||t.length>1&&Fh[t[0]]?.subcommands?r:t[0]}function p0(e=[]){let t=f0(e),r=Fh[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&i.push("",lu("Agent Quick Start",r.agentQuickStart)),r.subcommands&&i.push("",lu("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...Rk];return n&&n.length>0&&i.push("",lu("Options",n)),i.push("",`Output:
|
|
301
301
|
${r.output}`),r.examples&&i.push("",lu("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
|
|
302
302
|
`)}
|
|
303
|
-
`}}var p0
|
|
304
|
-
`}function Ze(e,t,r){return{command:e,exitCode:0,data:t,text:r??jk(t)}}function
|
|
303
|
+
`}}var h0=p0().usage;var p9=10*1024*1024,X=class extends Error{};function jt(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new X(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function yr(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new X(`${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 X(`${t} requires a value`);return e.splice(i,2),n}function _k(e){if(e.length>0)throw new X(`Unexpected argument: ${e[0]}`)}function Ak(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new X(`${t} is required`);return r}function Vh(e,t){let r=Xo.normalize(Pk(e)),i=Xo.normalize(Pk(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Pk(e){let t=Xo.resolve(e);try{return m0.native(t)}catch{return t}}function v0(e){let t=Xo.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||!Vh(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||Vh(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:Vh(process.cwd(),r.currentWorktreeRoot)?Xo.resolve(process.cwd()):r.currentWorktreeRoot}async function Ik(e){return e?v0(e):mc(process.cwd())}async function Tk(e){let t=await rw({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function jk(e){return JSON.stringify(e,null,2)+`
|
|
304
|
+
`}function Ze(e,t,r){return{command:e,exitCode:0,data:t,text:r??jk(t)}}function g0(e,t){if(t instanceof qa)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof X)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof su)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 cu)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Vl)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 Do)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 Vr)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Ml)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 ou)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof Yo)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 Wn(e,t){let r=g0(e,t),i=r.error;if(!i)return r;let n=Ck({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function w0(e,t,r=!1){let i=e.envelope??xk(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:pk(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}})+`
|
|
305
305
|
`}:e.error?{exitCode:e.exitCode,stderr:i?vk(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:mk(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==jk(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
306
306
|
${wr.details}
|
|
307
307
|
${JSON.stringify(e.data,null,2)}
|
|
308
|
-
`}:{exitCode:e.exitCode,stdout:e.text}}function w0(e,t,r=!1){let i=g0(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}}function $k(e,t,r=!1){return w0(e,t,r).output}var y0=new Set(["prepare-shape-confirmation","confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function N0(e){let t=yr(e,"--expected-state-version"),r=yr(e,"--expected-action");if(!(t===void 0&&r===void 0)){if(t===void 0||r===void 0)throw new X("--expected-state-version and --expected-action must be provided together");if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new X("--expected-state-version must be a positive integer");if(!y0.has(r))throw new X("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function Nr(e,t,r,i,n){let a=await ih({paths:e,name:t.name});a.local&&(r??=QN(t,a.local),i===void 0&&(i=Sb(a.local,a.local.workspace.projectRoot)));let o=await je({paths:e,state:t}),s=o?.confirmed?await O(e,t.name,{diagnostics:!0}):null,c=s?.children.flatMap(({task:f})=>f?[f.child]:[])??[],l=s?.integration.checkExecution,u=l?.status==="interrupted"?(l.checkStates??[]).filter(({status:f})=>f==="interrupted").map(({id:f})=>f):void 0;return{...o?{childSummary:o.children.reduce((f,d)=>({...f,[d.status]:(f[d.status]??0)+1}),{total:o.children.length}),readyChildren:c.length>0?c:o.readyChildren}:{},continuation:K(t,o,{verifierExecutionRef:r,verificationCheckPlans:i,retryCheckIds:n,supervisorIntegrationRetryIds:u})}}function b0(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"&&t!=="continuationCheckPlans"&&t!=="continuationRetryCheckIds"))}function Ok(e){return{action:e.action,reason:e.reason,message:e.message}}async function Dk(e,t){let r=Ak(e,"change name"),i=yr(e,"--summary"),n=yr(e,"--runner-input"),a=jt(e,"--validate-only"),o=jt(e,"--confirmed"),s=jt(e,"--accept-result"),c=jt(e,"--revise-implementation"),l=jt(e,"--revise-requirements"),u=jt(e,"--retry-verifier"),f=jt(e,"--resolve-verifier-blocker"),d=yr(e,"--coordination-mode"),p=d;if(d!==void 0&&!Nc.includes(d))throw new X("--coordination-mode must be multi-session or single-session");if(a&&n===void 0)throw new X("--validate-only requires --runner-input");let m=yr(e,"--max-parallel"),h=m===void 0?2:Number(m);if(!Number.isSafeInteger(h)||h<1)throw new X("--max-parallel must be a positive integer");let g=N0(e);if([o,s,c,l,u,f].filter(Boolean).length>1)throw new X("--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||f||n!==void 0))throw new X("--coordination-mode is only valid when preparing a Supervisor Shape confirmation");_k(e);let v=await Tk(t),w=await zb(v.paths,r);if(!await $n(v.paths,r)){if(w){let H={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:H},error:{code:"conflict",message:w.result?.message??"Native Archive completed, but workspace finish is still pending"}}}if(n)throw new X("--runner-input is only valid for portable Native changes");if(!i)throw new X("--summary is required");let C=await Zb({paths:v.paths,name:r});return Ze("next",{state:xe(C,v.paths),migration:{completed:!0,summary:i},continuation:K(C)})}let y=await $(v.paths,r);if(a){if(i||o||s||c||l||u||f||g||p!==void 0)throw new X("--validate-only cannot be combined with --summary, continuation expectations, or coordination mode");let C;try{C=await Hh(n,t)}catch(H){return{...Wn("next",H),data:{state:xe(y,v.paths),continuation:K(y)}}}try{await Dh({paths:v.paths,name:r,state:y,input:C,projectRoot:t})}catch(H){return{...Wn("next",H),data:{state:xe(y,v.paths),continuation:K(y)}}}return Ze("next",{validation:{valid:!0,kind:C.kind},state:xe(y,v.paths),continuation:K(y)})}if(n!==void 0||!i||y.phase==="verify"||y.phase==="archive"||y.verification_result==="pass"){let C=Ah(v.paths,y);if(C)return Hk(v.paths,y,r,C)}if(n){if(i||o||s||c||l||u||f||p!==void 0||g)throw new X("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let C;try{C=await Hh(n,t),await Dh({paths:v.paths,name:r,state:y,input:C,projectRoot:t}),y.document_constraints_version===1&&await Gl({paths:v.paths,state:y})}catch(Ce){return{...Wn("next",Ce),data:{state:xe(y,v.paths),continuation:K(y)}}}let H=await ru({paths:v.paths,name:r});if(H.action==="rerun-final-verification")return Ze("next",{state:xe(H.state,v.paths),...await Nr(v.paths,H.state)});let P=await Ih({paths:v.paths,name:r,preserveRunningExecution:!0}),W=P.state;if(P.action==="await-user"||P.action==="done"||P.reason!=="available")return Ze("next",{state:xe(W,v.paths),recovery:Ok(P),...await Nr(v.paths,W)});if(W.phase==="build"){let Ce=await Bo({paths:v.paths,state:W});if(Ce.drifted){let zn=await Lo({paths:v.paths,name:r,reason:Ce.reason??"Native confirmed requirements changed",keepFailureBudget:!0});return Ze("next",{state:xe(zn,v.paths),...await Nr(v.paths,zn)})}let Zt=await O(v.paths,r),et=await je({paths:v.paths,state:W});if(et&&!et.allDone&&!Zt)throw new X("Native parent Build advances child changes and does not accept a Builder handoff")}let ue=await fk({paths:v.paths,name:r,input:C,maxVerifyFailures:v.config.native.max_verify_failures}),$t="continuationCheckPlans"in ue?ue.continuationCheckPlans:void 0,ri="continuationRetryCheckIds"in ue?ue.continuationRetryCheckIds:void 0;return Ze("next",{...b0(ue),state:xe(ue.state,v.paths),...await Nr(v.paths,ue.state,ue.verifierDispatch?.verifierExecutionRef,$t,ri),coordination:Ne})}if(!i)throw new X("--summary is required");let S=await ru({paths:v.paths,name:r});if(S.action==="rerun-final-verification")return Ze("next",{state:xe(S.state,v.paths),...await Nr(v.paths,S.state)});let N=await Ih({paths:v.paths,name:r}),x=N.state;if(N.reason==="workspace-mismatch")return Hk(v.paths,x,r,N.message);if(p!==void 0&&x.phase!=="shape")throw new X("--coordination-mode is only valid when confirming Shape");let k,E=null;if(o)if(x.phase==="shape"&&x.status==="await-user"&&x.loop.next_action==="confirm-shape"){if(!g)throw new X("--expected-state-version and --expected-action are required for Shape confirmation");k=await wh({paths:v.paths,name:r,expectedContinuation:g})}else{if(x.phase==="shape")throw new X("--confirmed is only valid from the persisted Shape user confirmation boundary");if(x.phase==="verify"&&x.status==="await-user"&&x.loop.next_action==="confirm-verifier-unavailable")k=await xh({paths:v.paths,name:r,summary:i,expectedContinuation:g});else throw new X("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback")}else if(s){if(!g&&(x.phase!=="verify"||x.status!=="await-user"||x.loop.next_action!=="confirm-skill-coordinated-pass"))throw new X("--accept-result is only valid for a pending Verify pass decision");k=await Ph({paths:v.paths,name:r,expectedContinuation:g})}else if(c){if(x.phase!=="verify")throw new X("--revise-implementation is only valid from Verify");k=await Hi({paths:v.paths,name:r,reason:i,expectedContinuation:g})}else if(l){if(!g&&x.phase!=="verify"&&x.phase!=="archive")throw new X("--revise-requirements is only valid from Verify or Archive");k=await Lo({paths:v.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:g})}else if(u)k=await Rh({paths:v.paths,name:r,expectedContinuation:g});else if(f)k=await Ch({paths:v.paths,name:r,reason:i,expectedContinuation:g});else{if(N.reason!=="available"){let W=((await je({paths:v.paths,state:x}))?.confirmed?await O(v.paths,x.name,{diagnostics:!0}):null)?.children.flatMap(({task:ue})=>ue?[Lr(ue,x.name,v.paths.projectRoot)]:[])??[];return Ze("next",{state:xe(x,v.paths),recovery:Ok(N),...await Nr(v.paths,x),...W.length>0?{supervisorTasks:W}:{}})}if(x.phase==="build"){let H=await Bo({paths:v.paths,state:x});if(H.drifted)k=await Lo({paths:v.paths,name:r,reason:H.reason??"Native confirmed requirements changed",keepFailureBudget:!0});else{let P=await je({paths:v.paths,state:x});if(P){let W=P,ue=[],$t=[],ri=null,Ce=await O(v.paths,r);if(Ce&&!P.allDone){let Zt=await Up({paths:v.paths,parent:r,maxParallel:x.coordination_mode==="single-session"?1:h});ue=Zt.state.children.flatMap(({task:et})=>et?[Lr(et,r,v.paths.projectRoot)]:[]),ri=Zt.tasks.map(({child:et})=>et),$t=Zt.state.children.flatMap(({name:et,blocker:zn})=>zn?[{child:et,message:zn}]:[]),(ue.length>0||Zt.state.stateVersion!==Ce.stateVersion)&&(W=await je({paths:v.paths,state:x})??W)}if(W.allDone&&!(x.loop.stage==="repairing"&&x.verification_result==="fail"))E=await Go({paths:v.paths,name:r,trigger:"recovery"}),k=E.state;else return Ze("next",{state:xe(x,v.paths),childSummary:W.children.reduce((Zt,et)=>({...Zt,[et.status]:(Zt[et.status]??0)+1}),{total:W.children.length}),readyChildren:ri??W.readyChildren,...ue.length>0?{supervisorTasks:ue}:{},...$t.length>0?{supervisorBlockers:$t}:{},continuation:K(x,W)})}}}if(x.phase==="shape"&&(k=await ph({paths:v.paths,name:r,enforceDocumentConstraints:!0,...p===void 0?{}:{coordinationMode:p},expectedContinuation:g})),k)return Ze("next",{state:xe(k,v.paths),...E?{parentAdvance:E.parentAdvance}:{},...await Nr(v.paths,k)});let C=x.phase==="shape"?await je({paths:v.paths,state:x}):null;return{command:"next",exitCode:65,data:{state:xe(x,v.paths),continuation:K(x,C)},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 Ze("next",{state:xe(k,v.paths),...p===void 0?{}:{coordinationMode:p},...await Nr(v.paths,k)})}async function Hk(e,t,r,i){let n=K(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 Ze("next",{state:xe(t,e),...await Nr(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}}})}async function Bk(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{jt(n,"--json"),jt(n,"--verbose"),c=yr(n,"--project-root");let f=[...n,...a],d=await Ik(c);l={executionCwd:d,...await t(f,d)}}catch(f){l=Wn(e,f)}let u=$k(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
|
|
308
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}function y0(e,t,r=!1){let i=w0(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}}function $k(e,t,r=!1){return y0(e,t,r).output}var N0=new Set(["prepare-shape-confirmation","confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function b0(e){let t=yr(e,"--expected-state-version"),r=yr(e,"--expected-action");if(!(t===void 0&&r===void 0)){if(t===void 0||r===void 0)throw new X("--expected-state-version and --expected-action must be provided together");if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new X("--expected-state-version must be a positive integer");if(!N0.has(r))throw new X("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function Nr(e,t,r,i,n){let a=await ih({paths:e,name:t.name});a.local&&(r??=QN(t,a.local),i===void 0&&(i=Sb(a.local,a.local.workspace.projectRoot)));let o=await je({paths:e,state:t}),s=o?.confirmed?await O(e,t.name,{diagnostics:!0}):null,c=s?.children.flatMap(({task:f})=>f?[f.child]:[])??[],l=s?.integration.checkExecution,u=l?.status==="interrupted"?(l.checkStates??[]).filter(({status:f})=>f==="interrupted").map(({id:f})=>f):void 0;return{...o?{childSummary:o.children.reduce((f,d)=>({...f,[d.status]:(f[d.status]??0)+1}),{total:o.children.length}),readyChildren:c.length>0?c:o.readyChildren}:{},continuation:K(t,o,{verifierExecutionRef:r,verificationCheckPlans:i,retryCheckIds:n,supervisorIntegrationRetryIds:u})}}function k0(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"&&t!=="continuationCheckPlans"&&t!=="continuationRetryCheckIds"))}function Ok(e){return{action:e.action,reason:e.reason,message:e.message}}async function Dk(e,t){let r=Ak(e,"change name"),i=yr(e,"--summary"),n=yr(e,"--runner-input"),a=jt(e,"--validate-only"),o=jt(e,"--confirmed"),s=jt(e,"--accept-result"),c=jt(e,"--revise-implementation"),l=jt(e,"--revise-requirements"),u=jt(e,"--retry-verifier"),f=jt(e,"--resolve-verifier-blocker"),d=yr(e,"--coordination-mode"),p=d;if(d!==void 0&&!Nc.includes(d))throw new X("--coordination-mode must be multi-session or single-session");if(a&&n===void 0)throw new X("--validate-only requires --runner-input");let m=yr(e,"--max-parallel"),h=m===void 0?2:Number(m);if(!Number.isSafeInteger(h)||h<1)throw new X("--max-parallel must be a positive integer");let g=b0(e);if([o,s,c,l,u,f].filter(Boolean).length>1)throw new X("--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||f||n!==void 0))throw new X("--coordination-mode is only valid when preparing a Supervisor Shape confirmation");_k(e);let v=await Tk(t),w=await zb(v.paths,r);if(!await $n(v.paths,r)){if(w){let H={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:H},error:{code:"conflict",message:w.result?.message??"Native Archive completed, but workspace finish is still pending"}}}if(n)throw new X("--runner-input is only valid for portable Native changes");if(!i)throw new X("--summary is required");let C=await Zb({paths:v.paths,name:r});return Ze("next",{state:xe(C,v.paths),migration:{completed:!0,summary:i},continuation:K(C)})}let y=await $(v.paths,r);if(a){if(i||o||s||c||l||u||f||g||p!==void 0)throw new X("--validate-only cannot be combined with --summary, continuation expectations, or coordination mode");let C;try{C=await Hh(n,t)}catch(H){return{...Wn("next",H),data:{state:xe(y,v.paths),continuation:K(y)}}}try{await Dh({paths:v.paths,name:r,state:y,input:C,projectRoot:t})}catch(H){return{...Wn("next",H),data:{state:xe(y,v.paths),continuation:K(y)}}}return Ze("next",{validation:{valid:!0,kind:C.kind},state:xe(y,v.paths),continuation:K(y)})}if(n!==void 0||!i||y.phase==="verify"||y.phase==="archive"||y.verification_result==="pass"){let C=Ah(v.paths,y);if(C)return Hk(v.paths,y,r,C)}if(n){if(i||o||s||c||l||u||f||p!==void 0||g)throw new X("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let C;try{C=await Hh(n,t),await Dh({paths:v.paths,name:r,state:y,input:C,projectRoot:t}),y.document_constraints_version===1&&await Gl({paths:v.paths,state:y})}catch(Ce){return{...Wn("next",Ce),data:{state:xe(y,v.paths),continuation:K(y)}}}let H=await ru({paths:v.paths,name:r});if(H.action==="rerun-final-verification")return Ze("next",{state:xe(H.state,v.paths),...await Nr(v.paths,H.state)});let P=await Ih({paths:v.paths,name:r,preserveRunningExecution:!0}),W=P.state;if(P.action==="await-user"||P.action==="done"||P.reason!=="available")return Ze("next",{state:xe(W,v.paths),recovery:Ok(P),...await Nr(v.paths,W)});if(W.phase==="build"){let Ce=await Bo({paths:v.paths,state:W});if(Ce.drifted){let zn=await Lo({paths:v.paths,name:r,reason:Ce.reason??"Native confirmed requirements changed",keepFailureBudget:!0});return Ze("next",{state:xe(zn,v.paths),...await Nr(v.paths,zn)})}let Zt=await O(v.paths,r),et=await je({paths:v.paths,state:W});if(et&&!et.allDone&&!Zt)throw new X("Native parent Build advances child changes and does not accept a Builder handoff")}let ue=await fk({paths:v.paths,name:r,input:C,maxVerifyFailures:v.config.native.max_verify_failures}),$t="continuationCheckPlans"in ue?ue.continuationCheckPlans:void 0,ri="continuationRetryCheckIds"in ue?ue.continuationRetryCheckIds:void 0;return Ze("next",{...k0(ue),state:xe(ue.state,v.paths),...await Nr(v.paths,ue.state,ue.verifierDispatch?.verifierExecutionRef,$t,ri),coordination:Ne})}if(!i)throw new X("--summary is required");let S=await ru({paths:v.paths,name:r});if(S.action==="rerun-final-verification")return Ze("next",{state:xe(S.state,v.paths),...await Nr(v.paths,S.state)});let N=await Ih({paths:v.paths,name:r}),x=N.state;if(N.reason==="workspace-mismatch")return Hk(v.paths,x,r,N.message);if(p!==void 0&&x.phase!=="shape")throw new X("--coordination-mode is only valid when confirming Shape");let k,E=null;if(o)if(x.phase==="shape"&&x.status==="await-user"&&x.loop.next_action==="confirm-shape"){if(!g)throw new X("--expected-state-version and --expected-action are required for Shape confirmation");k=await wh({paths:v.paths,name:r,expectedContinuation:g})}else{if(x.phase==="shape")throw new X("--confirmed is only valid from the persisted Shape user confirmation boundary");if(x.phase==="verify"&&x.status==="await-user"&&x.loop.next_action==="confirm-verifier-unavailable")k=await xh({paths:v.paths,name:r,summary:i,expectedContinuation:g});else throw new X("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback")}else if(s){if(!g&&(x.phase!=="verify"||x.status!=="await-user"||x.loop.next_action!=="confirm-skill-coordinated-pass"))throw new X("--accept-result is only valid for a pending Verify pass decision");k=await Ph({paths:v.paths,name:r,expectedContinuation:g})}else if(c){if(x.phase!=="verify")throw new X("--revise-implementation is only valid from Verify");k=await Hi({paths:v.paths,name:r,reason:i,expectedContinuation:g})}else if(l){if(!g&&x.phase!=="verify"&&x.phase!=="archive")throw new X("--revise-requirements is only valid from Verify or Archive");k=await Lo({paths:v.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:g})}else if(u)k=await Rh({paths:v.paths,name:r,expectedContinuation:g});else if(f)k=await Ch({paths:v.paths,name:r,reason:i,expectedContinuation:g});else{if(N.reason!=="available"){let W=((await je({paths:v.paths,state:x}))?.confirmed?await O(v.paths,x.name,{diagnostics:!0}):null)?.children.flatMap(({task:ue})=>ue?[Lr(ue,x.name,v.paths.projectRoot)]:[])??[];return Ze("next",{state:xe(x,v.paths),recovery:Ok(N),...await Nr(v.paths,x),...W.length>0?{supervisorTasks:W}:{}})}if(x.phase==="build"){let H=await Bo({paths:v.paths,state:x});if(H.drifted)k=await Lo({paths:v.paths,name:r,reason:H.reason??"Native confirmed requirements changed",keepFailureBudget:!0});else{let P=await je({paths:v.paths,state:x});if(P){let W=P,ue=[],$t=[],ri=null,Ce=await O(v.paths,r);if(Ce&&!P.allDone){let Zt=await Up({paths:v.paths,parent:r,maxParallel:x.coordination_mode==="single-session"?1:h});ue=Zt.state.children.flatMap(({task:et})=>et?[Lr(et,r,v.paths.projectRoot)]:[]),ri=Zt.tasks.map(({child:et})=>et),$t=Zt.state.children.flatMap(({name:et,blocker:zn})=>zn?[{child:et,message:zn}]:[]),(ue.length>0||Zt.state.stateVersion!==Ce.stateVersion)&&(W=await je({paths:v.paths,state:x})??W)}if(W.allDone&&!(x.loop.stage==="repairing"&&x.verification_result==="fail"))E=await Go({paths:v.paths,name:r,trigger:"recovery"}),k=E.state;else return Ze("next",{state:xe(x,v.paths),childSummary:W.children.reduce((Zt,et)=>({...Zt,[et.status]:(Zt[et.status]??0)+1}),{total:W.children.length}),readyChildren:ri??W.readyChildren,...ue.length>0?{supervisorTasks:ue}:{},...$t.length>0?{supervisorBlockers:$t}:{},continuation:K(x,W)})}}}if(x.phase==="shape"&&(k=await ph({paths:v.paths,name:r,enforceDocumentConstraints:!0,...p===void 0?{}:{coordinationMode:p},expectedContinuation:g})),k)return Ze("next",{state:xe(k,v.paths),...E?{parentAdvance:E.parentAdvance}:{},...await Nr(v.paths,k)});let C=x.phase==="shape"?await je({paths:v.paths,state:x}):null;return{command:"next",exitCode:65,data:{state:xe(x,v.paths),continuation:K(x,C)},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 Ze("next",{state:xe(k,v.paths),...p===void 0?{}:{coordinationMode:p},...await Nr(v.paths,k)})}async function Hk(e,t,r,i){let n=K(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 Ze("next",{state:xe(t,e),...await Nr(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}}})}async function Bk(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{jt(n,"--json"),jt(n,"--verbose"),c=yr(n,"--project-root");let f=[...n,...a],d=await Ik(c);l={executionCwd:d,...await t(f,d)}}catch(f){l=Wn(e,f)}let u=$k(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
|
|
309
309
|
`)?"":`
|
|
310
310
|
`)),u.exitCode}process.exitCode=await Bk("next",Dk);
|