@rpamis/comet 0.4.0-rc.6 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +332 -333
- package/assets/manifest.json +1 -1
- package/assets/skills/comet/scripts/comet-archive.mjs +56 -51
- package/assets/skills/comet/scripts/comet-entry-runtime.mjs +22 -20
- package/assets/skills/comet/scripts/comet-guard.mjs +93 -88
- package/assets/skills/comet/scripts/comet-handoff.mjs +111 -106
- package/assets/skills/comet/scripts/comet-hook-guard.mjs +54 -49
- package/assets/skills/comet/scripts/comet-hook-router.mjs +106 -106
- package/assets/skills/comet/scripts/comet-intent.mjs +12 -7
- package/assets/skills/comet/scripts/comet-resume-probe.mjs +50 -45
- package/assets/skills/comet/scripts/comet-runtime.mjs +180 -175
- package/assets/skills/comet/scripts/comet-state.mjs +80 -75
- package/assets/skills/comet/scripts/comet-yaml-validate.mjs +57 -52
- package/assets/skills/comet-classic/reference/scripts.md +1 -1
- package/assets/skills/comet-native/SKILL.md +3 -3
- package/assets/skills/comet-native/scripts/comet-native-archive.mjs +31 -31
- package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +51 -51
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +3 -3
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +37 -37
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +33 -33
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +43 -43
- package/assets/skills/comet-native/scripts/comet-native-root.mjs +3 -3
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +71 -71
- package/assets/skills/comet-native/scripts/comet-native-select.mjs +36 -36
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +27 -27
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +23 -23
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +39 -39
- package/assets/skills-zh/comet-classic/reference/scripts.md +1 -1
- package/assets/skills-zh/comet-native/SKILL.md +3 -3
- package/bin/fast-runtime-router.js +1 -1
- package/dist/app/cli/index.js +7 -1
- package/dist/app/cli/index.js.map +1 -1
- package/dist/app/commands/classic.js +4 -0
- package/dist/app/commands/classic.js.map +1 -1
- package/dist/app/commands/doctor.d.ts +1 -1
- package/dist/app/commands/doctor.d.ts.map +1 -1
- package/dist/app/commands/doctor.js +2 -1
- package/dist/app/commands/doctor.js.map +1 -1
- package/dist/app/commands/eval.js +2 -2
- package/dist/app/commands/eval.js.map +1 -1
- package/dist/app/commands/init.d.ts.map +1 -1
- package/dist/app/commands/init.js +16 -5
- package/dist/app/commands/init.js.map +1 -1
- package/dist/app/commands/personal-memory.d.ts.map +1 -1
- package/dist/app/commands/personal-memory.js +5 -0
- package/dist/app/commands/personal-memory.js.map +1 -1
- package/dist/app/commands/project-knowledge.d.ts.map +1 -1
- package/dist/app/commands/project-knowledge.js +26 -2
- package/dist/app/commands/project-knowledge.js.map +1 -1
- package/dist/app/commands/status.d.ts.map +1 -1
- package/dist/app/commands/status.js +17 -10
- package/dist/app/commands/status.js.map +1 -1
- package/dist/app/commands/uninstall.d.ts.map +1 -1
- package/dist/app/commands/uninstall.js +5 -1
- package/dist/app/commands/uninstall.js.map +1 -1
- package/dist/app/commands/update.d.ts.map +1 -1
- package/dist/app/commands/update.js +10 -4
- package/dist/app/commands/update.js.map +1 -1
- package/dist/domains/agent-learning/context-director.d.ts.map +1 -1
- package/dist/domains/agent-learning/context-director.js +14 -10
- package/dist/domains/agent-learning/context-director.js.map +1 -1
- package/dist/domains/comet-classic/classic-archive.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-archive.js +3 -0
- package/dist/domains/comet-classic/classic-archive.js.map +1 -1
- package/dist/domains/comet-classic/classic-cli-help.d.ts +3 -0
- package/dist/domains/comet-classic/classic-cli-help.d.ts.map +1 -0
- package/dist/domains/comet-classic/classic-cli-help.js +40 -0
- package/dist/domains/comet-classic/classic-cli-help.js.map +1 -0
- package/dist/domains/comet-classic/classic-cli.d.ts +1 -0
- package/dist/domains/comet-classic/classic-cli.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-cli.js +5 -0
- package/dist/domains/comet-classic/classic-cli.js.map +1 -1
- package/dist/domains/comet-classic/classic-guard.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-guard.js +12 -2
- package/dist/domains/comet-classic/classic-guard.js.map +1 -1
- package/dist/domains/comet-classic/classic-handoff.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-handoff.js +11 -10
- package/dist/domains/comet-classic/classic-handoff.js.map +1 -1
- package/dist/domains/comet-classic/classic-script-entry.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-script-entry.js +4 -1
- package/dist/domains/comet-classic/classic-script-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-state-command.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-state-command.js +37 -18
- package/dist/domains/comet-classic/classic-state-command.js.map +1 -1
- package/dist/domains/comet-classic/classic-validate-command.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-validate-command.js +2 -0
- package/dist/domains/comet-classic/classic-validate-command.js.map +1 -1
- package/dist/domains/comet-classic/classic-workspace.d.ts +1 -0
- package/dist/domains/comet-classic/classic-workspace.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-workspace.js +2 -1
- package/dist/domains/comet-classic/classic-workspace.js.map +1 -1
- package/dist/domains/comet-entry/entry-runtime.d.ts.map +1 -1
- package/dist/domains/comet-entry/entry-runtime.js +13 -3
- package/dist/domains/comet-entry/entry-runtime.js.map +1 -1
- package/dist/domains/comet-memory/plugin.js +4 -9
- package/dist/domains/comet-memory/plugin.js.map +1 -1
- package/dist/domains/comet-memory/repository.d.ts +3 -0
- package/dist/domains/comet-memory/repository.d.ts.map +1 -1
- package/dist/domains/comet-memory/repository.js +117 -25
- package/dist/domains/comet-memory/repository.js.map +1 -1
- package/dist/domains/comet-memory/review-contract.d.ts.map +1 -1
- package/dist/domains/comet-memory/review-contract.js +4 -2
- package/dist/domains/comet-memory/review-contract.js.map +1 -1
- package/dist/domains/comet-native/native-check-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-check-command.js +5 -1
- package/dist/domains/comet-native/native-check-command.js.map +1 -1
- package/dist/domains/comet-native/native-cli-help.d.ts.map +1 -1
- package/dist/domains/comet-native/native-cli-help.js +7 -2
- package/dist/domains/comet-native/native-cli-help.js.map +1 -1
- package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-next-command.js +22 -1
- package/dist/domains/comet-native/native-next-command.js.map +1 -1
- package/dist/domains/comet-native/native-output-language.d.ts.map +1 -1
- package/dist/domains/comet-native/native-output-language.js +3 -1
- package/dist/domains/comet-native/native-output-language.js.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.js +11 -0
- package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
- package/dist/domains/comet-plugin/integration.d.ts.map +1 -1
- package/dist/domains/comet-plugin/integration.js +14 -8
- package/dist/domains/comet-plugin/integration.js.map +1 -1
- package/dist/domains/comet-plugin/plugin-runtime.d.ts +2 -2
- package/dist/domains/comet-plugin/plugin-runtime.d.ts.map +1 -1
- package/dist/domains/comet-plugin/plugin-runtime.js +89 -77
- package/dist/domains/comet-plugin/plugin-runtime.js.map +1 -1
- package/dist/domains/comet-plugin/types.d.ts +2 -0
- package/dist/domains/comet-plugin/types.d.ts.map +1 -1
- package/dist/domains/dashboard/server.d.ts.map +1 -1
- package/dist/domains/dashboard/server.js +20 -0
- package/dist/domains/dashboard/server.js.map +1 -1
- package/dist/domains/dashboard/web/index.html +14 -14
- package/dist/domains/integrations/openspec.d.ts.map +1 -1
- package/dist/domains/integrations/openspec.js +4 -3
- package/dist/domains/integrations/openspec.js.map +1 -1
- package/dist/domains/integrations/superpowers.js +2 -2
- package/dist/domains/integrations/superpowers.js.map +1 -1
- package/dist/domains/project-knowledge/corpus.d.ts.map +1 -1
- package/dist/domains/project-knowledge/corpus.js +5 -2
- package/dist/domains/project-knowledge/corpus.js.map +1 -1
- package/dist/domains/skill/languages.d.ts +3 -1
- package/dist/domains/skill/languages.d.ts.map +1 -1
- package/dist/domains/skill/languages.js +26 -1
- package/dist/domains/skill/languages.js.map +1 -1
- package/dist/domains/skill/uninstall.d.ts.map +1 -1
- package/dist/domains/skill/uninstall.js +16 -0
- package/dist/domains/skill/uninstall.js.map +1 -1
- package/dist/platform/process/git-environment.d.ts +3 -0
- package/dist/platform/process/git-environment.d.ts.map +1 -0
- package/dist/platform/process/git-environment.js +26 -0
- package/dist/platform/process/git-environment.js.map +1 -0
- package/eval/langsmith/tests/tasks/test_tasks.py +6 -0
- package/eval/local/tests/scaffold/test_langsmith_conftest.py +10 -0
- package/package.json +2 -2
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
3
|
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
-
var Hv=Object.create;var es=Object.defineProperty;var Dv=Object.getOwnPropertyDescriptor;var Bv=Object.getOwnPropertyNames;var Lv=Object.getPrototypeOf,qv=Object.prototype.hasOwnProperty;var An=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var E=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var S=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Pu=(e,t)=>{for(var r in t)es(e,r,{get:t[r],enumerable:!0})},Fv=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Bv(t))!qv.call(e,n)&&n!==r&&es(e,n,{get:()=>t[n],enumerable:!(i=Dv(t,n))||i.enumerable});return e};var ri=(e,t,r)=>(r=e!=null?Hv(Lv(e)):{},Fv(t||!e||!e.__esModule?es(r,"default",{value:e,enumerable:!0}):r,e));import{execFileSync as Vv}from"child_process";import ii from"path";function yt(e,t){return Vv("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Mv(e,t){let r=ii.normalize(e),i=ii.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function $(e){try{let t=ii.resolve(yt(e,["rev-parse","--show-toplevel"])),i=yt(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?ii.resolve(i.slice(9)):t,a=null;try{a=yt(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Mv(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function xu(e){try{yt(e,["rev-parse","--is-inside-work-tree"]);let t=yt(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:ii.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 ge(e){return xu(e).map(t=>t.root)}function ni(e,t){try{return yt(e,["check-ref-format","--branch",t]),yt(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function Jt(e,t){try{let r=yt(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}var ke=E(()=>{"use strict"});function Nt(e){return e!==0&&e!==0n&&e!=="0"}function
|
|
5
|
-
`,r)}var q=E(()=>{"use strict";Me()});function Zv(e){return e.toLowerCase().startsWith(".env")}function oi(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>Zv(i))?"environment-file":r.some(i=>Qv.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>Xv.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var Xv,Qv,si=E(()=>{"use strict";Xv=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Qv=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});import{createHash as eg}from"node:crypto";import{promises as je}from"node:fs";import Se from"node:path";import{TextDecoder as tg}from"node:util";function ts(e,t){let r=Se.relative(e,t);return r===""||!Se.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Se.sep}`)}function rg(e){let t=Se.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||Se.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=oi(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function ig(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function ng(e,t){return O({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Tn(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Ve(r,i)?O(r,i):O(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Ru(e){let t=await je.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await je.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function ag(e,t){let r=Se.resolve(e),i=Se.resolve(t);if(!ts(r,i))throw new Error("Native artifact path is outside its root");let n=[await Ru(r)],a=r;for(let o of Se.relative(r,i).split(Se.sep).filter(Boolean)){a=Se.join(a,o);let s=await Ru(a);if(!ts(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Au(e){for(let t of e){let r=await je.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!ng(t,r)||await je.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function F(e){let t=rg(e.ref),r=e.maxBytes===null?null:ig(e.maxBytes??jn),i=Se.resolve(e.root,...t.split("/")),n=await ag(e.root,Se.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await je.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await je.realpath(i);if(!ts(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await je.open(i,"r");try{let[c,l,f]=await Promise.all([s.stat(),je.lstat(i),je.realpath(i)]);if(await Au(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!Tn(a,c)||!Tn(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],u=0,p=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let b=r===null?p.length:r+1-u,w=await s.read(p,0,Math.min(p.length,b),null);if(w.bytesRead===0)break;if(u+=w.bytesRead,r!==null&&u>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,w.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[g,h,m]=await Promise.all([s.stat(),je.lstat(i),je.realpath(i)]);if(await Au(n),!h.isFile()||h.isSymbolicLink()||m!==o||!Tn(c,g)||!Tn(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let v=Buffer.concat(d,u),y;try{y=new tg("utf-8",{fatal:!0}).decode(v)}catch(b){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:b})}return{ref:t,size:u,hash:e.includeHash===!1?null:eg("sha256").update(v).digest("hex"),text:y}}finally{await s.close()}}var jn,Ee=E(()=>{"use strict";si();Me();jn=1024*1024});var A=S(ee=>{"use strict";var rs=Symbol.for("yaml.alias"),_u=Symbol.for("yaml.document"),$n=Symbol.for("yaml.map"),Iu=Symbol.for("yaml.pair"),is=Symbol.for("yaml.scalar"),On=Symbol.for("yaml.seq"),at=Symbol.for("yaml.node.type"),og=e=>!!e&&typeof e=="object"&&e[at]===rs,sg=e=>!!e&&typeof e=="object"&&e[at]===_u,cg=e=>!!e&&typeof e=="object"&&e[at]===$n,lg=e=>!!e&&typeof e=="object"&&e[at]===Iu,Tu=e=>!!e&&typeof e=="object"&&e[at]===is,ug=e=>!!e&&typeof e=="object"&&e[at]===On;function ju(e){if(e&&typeof e=="object")switch(e[at]){case $n:case On:return!0}return!1}function dg(e){if(e&&typeof e=="object")switch(e[at]){case rs:case $n:case is:case On:return!0}return!1}var fg=e=>(Tu(e)||ju(e))&&!!e.anchor;ee.ALIAS=rs;ee.DOC=_u;ee.MAP=$n;ee.NODE_TYPE=at;ee.PAIR=Iu;ee.SCALAR=is;ee.SEQ=On;ee.hasAnchor=fg;ee.isAlias=og;ee.isCollection=ju;ee.isDocument=sg;ee.isMap=cg;ee.isNode=dg;ee.isPair=lg;ee.isScalar=Tu;ee.isSeq=ug});var ci=S(ns=>{"use strict";var z=A(),fe=Symbol("break visit"),$u=Symbol("skip children"),We=Symbol("remove node");function Hn(e,t){let r=Ou(t);z.isDocument(e)?kr(null,e.contents,r,Object.freeze([e]))===We&&(e.contents=null):kr(null,e,r,Object.freeze([]))}Hn.BREAK=fe;Hn.SKIP=$u;Hn.REMOVE=We;function kr(e,t,r,i){let n=Hu(e,t,r,i);if(z.isNode(n)||z.isPair(n))return Du(e,i,n),kr(e,n,r,i);if(typeof n!="symbol"){if(z.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=kr(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===fe)return fe;o===We&&(t.items.splice(a,1),a-=1)}}}else if(z.isPair(t)){i=Object.freeze(i.concat(t));let a=kr("key",t.key,r,i);if(a===fe)return fe;a===We&&(t.key=null);let o=kr("value",t.value,r,i);if(o===fe)return fe;o===We&&(t.value=null)}}return n}async function Dn(e,t){let r=Ou(t);z.isDocument(e)?await Sr(null,e.contents,r,Object.freeze([e]))===We&&(e.contents=null):await Sr(null,e,r,Object.freeze([]))}Dn.BREAK=fe;Dn.SKIP=$u;Dn.REMOVE=We;async function Sr(e,t,r,i){let n=await Hu(e,t,r,i);if(z.isNode(n)||z.isPair(n))return Du(e,i,n),Sr(e,n,r,i);if(typeof n!="symbol"){if(z.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await Sr(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===fe)return fe;o===We&&(t.items.splice(a,1),a-=1)}}}else if(z.isPair(t)){i=Object.freeze(i.concat(t));let a=await Sr("key",t.key,r,i);if(a===fe)return fe;a===We&&(t.key=null);let o=await Sr("value",t.value,r,i);if(o===fe)return fe;o===We&&(t.value=null)}}return n}function Ou(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Hu(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(z.isMap(t))return r.Map?.(e,t,i);if(z.isSeq(t))return r.Seq?.(e,t,i);if(z.isPair(t))return r.Pair?.(e,t,i);if(z.isScalar(t))return r.Scalar?.(e,t,i);if(z.isAlias(t))return r.Alias?.(e,t,i)}function Du(e,t,r){let i=t[t.length-1];if(z.isCollection(i))i.items[e]=r;else if(z.isPair(i))e==="key"?i.key=r:i.value=r;else if(z.isDocument(i))i.contents=r;else{let n=z.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}ns.visit=Hn;ns.visitAsync=Dn});var as=S(Lu=>{"use strict";var Bu=A(),hg=ci(),pg={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},mg=e=>e.replace(/[!,[\]{}]/g,t=>pg[t]),li=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+mg(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&Bu.isNode(t.contents)){let a={};hg.visit(t.contents,(o,s)=>{Bu.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
|
|
6
|
-
`)}};li.defaultYaml={explicit:!1,version:"1.2"};li.defaultTags={"!!":"tag:yaml.org,2002:"};Lu.Directives=li});var Bn=S(ui=>{"use strict";var qu=A(),vg=ci();function gg(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function Fu(e){let t=new Set;return vg.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function Vu(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function wg(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Fu(e));let o=Vu(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(qu.isScalar(o.node)||qu.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:i}}ui.anchorIsValid=gg;ui.anchorNames=Fu;ui.createNodeAnchors=wg;ui.findNewAnchor=Vu});var os=S(Mu=>{"use strict";function di(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=di(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=di(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=di(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=di(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}Mu.applyReviver=di});var bt=S(zu=>{"use strict";var yg=A();function Wu(e,t,r){if(Array.isArray(e))return e.map((i,n)=>Wu(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!yg.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}zu.toJS=Wu});var Ln=S(Gu=>{"use strict";var Ng=os(),Ju=A(),bg=bt(),ss=class{constructor(t){Object.defineProperty(this,Ju.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!Ju.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=bg.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Ng.applyReviver(a,{"":s},"",s):s}};Gu.NodeBase=ss});var fi=S(Uu=>{"use strict";var kg=Bn(),Sg=ci(),Er=A(),Eg=Ln(),Pg=bt(),cs=class extends Eg.NodeBase{constructor(t){super(Er.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],Sg.visit(t,{Node:(a,o)=>{(Er.isAlias(o)||Er.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(Pg.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=qn(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(kg.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function qn(e,t,r){if(Er.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Er.isCollection(t)){let i=0;for(let n of t.items){let a=qn(e,n,r);a>i&&(i=a)}return i}else if(Er.isPair(t)){let i=qn(e,t.key,r),n=qn(e,t.value,r);return Math.max(i,n)}return 1}Uu.Alias=cs});var M=S(ls=>{"use strict";var xg=A(),Cg=Ln(),Rg=bt(),Ag=e=>!e||typeof e!="function"&&typeof e!="object",kt=class extends Cg.NodeBase{constructor(t){super(xg.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Rg.toJS(this.value,t,r)}toString(){return String(this.value)}};kt.BLOCK_FOLDED="BLOCK_FOLDED";kt.BLOCK_LITERAL="BLOCK_LITERAL";kt.PLAIN="PLAIN";kt.QUOTE_DOUBLE="QUOTE_DOUBLE";kt.QUOTE_SINGLE="QUOTE_SINGLE";ls.Scalar=kt;ls.isScalarValue=Ag});var hi=S(Yu=>{"use strict";var _g=fi(),Gt=A(),Ku=M(),Ig="tag:yaml.org,2002:";function Tg(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function jg(e,t,r){if(Gt.isDocument(e)&&(e=e.contents),Gt.isNode(e))return e;if(Gt.isPair(e)){let d=r.schema[Gt.MAP].createNode?.(r.schema,null,r);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new _g.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Ig+t.slice(2));let l=Tg(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Ku.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Gt.MAP]:Symbol.iterator in Object(e)?o[Gt.SEQ]:o[Gt.MAP]}a&&(a(l),delete r.onTagObj);let f=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new Ku.Scalar(e);return t?f.tag=t:l.default||(f.tag=l.tag),c&&(c.node=f),f}Yu.createNode=jg});var Vn=S(Fn=>{"use strict";var $g=hi(),
|
|
4
|
+
var Hv=Object.create;var es=Object.defineProperty;var Dv=Object.getOwnPropertyDescriptor;var Bv=Object.getOwnPropertyNames;var Lv=Object.getPrototypeOf,qv=Object.prototype.hasOwnProperty;var An=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var E=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var S=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Pu=(e,t)=>{for(var r in t)es(e,r,{get:t[r],enumerable:!0})},Fv=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Bv(t))!qv.call(e,n)&&n!==r&&es(e,n,{get:()=>t[n],enumerable:!(i=Dv(t,n))||i.enumerable});return e};var ri=(e,t,r)=>(r=e!=null?Hv(Lv(e)):{},Fv(t||!e||!e.__esModule?es(r,"default",{value:e,enumerable:!0}):r,e));import{execFileSync as Vv}from"child_process";import ii from"path";function yt(e,t){return Vv("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Mv(e,t){let r=ii.normalize(e),i=ii.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function $(e){try{let t=ii.resolve(yt(e,["rev-parse","--show-toplevel"])),i=yt(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?ii.resolve(i.slice(9)):t,a=null;try{a=yt(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Mv(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function xu(e){try{yt(e,["rev-parse","--is-inside-work-tree"]);let t=yt(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:ii.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 ge(e){return xu(e).map(t=>t.root)}function ni(e,t){try{return yt(e,["check-ref-format","--branch",t]),yt(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function Jt(e,t){try{let r=yt(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}var ke=E(()=>{"use strict"});function Nt(e){return e!==0&&e!==0n&&e!=="0"}function Me(e,t){return Nt(e.dev)&&Nt(t.dev)&&Nt(e.ino)&&Nt(t.ino)}function O(e,t){let r=Nt(e.dev)&&Nt(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Nt(e.ino)&&Nt(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var ai=E(()=>{"use strict"});var We=E(()=>{"use strict";ai()});import{randomUUID as Wv}from"crypto";import{promises as G}from"fs";import je from"path";function _n(e,t){let r=je.relative(e,t);return r===""||!je.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${je.sep}`)}function zv(e,t){return O({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function In(e,t){return O({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function Jv(e,t){return In(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Cu(e){let t=await G.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 G.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function br(e){for(let t of e){let r=await G.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!zv(t,r)||await G.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function Gv(e,t,r){let[i,n]=await Promise.all([G.lstat(e),G.realpath(e),r?br(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!In(i,t)||r&&!_n(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function Uv(e,t){let r=je.resolve(e),i=je.resolve(t);if(!_n(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Cu(r)],a=je.relative(r,i).split(je.sep).filter(Boolean),o=r;for(let s of a){await br(n),o=je.join(o,s);try{await G.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Cu(o);if(!_n(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await br(n),n}async function Kv(e){let t;try{t=await G.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 Yv(e,t,r={}){let i=je.dirname(e),n=r.containedRoot?await Uv(r.containedRoot,i):null;n||await G.mkdir(i,{recursive:!0});let a=je.join(i,`.${je.basename(e)}.${Wv()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await G.open(a,"wx"),s=await o.stat(),n){let[l,f]=await Promise.all([G.lstat(a),G.realpath(a)]);if(await br(n),!l.isFile()||l.isSymbolicLink()||!In(s,l)||!_n(n[0].realPath,f))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(),!In(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 Gv(a,c,n),await r.beforeCommit?.(),n){await br(n);let l=await G.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!Jv(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await G.link(a,e),await G.unlink(a)):await G.rename(a,e),await Kv(i)}catch(l){if(await o?.close(),!n)await G.rm(a,{force:!0});else try{await br(n),await G.rm(a,{force:!0})}catch{}throw l}}async function de(e,t,r={}){await Yv(e,t,r)}async function U(e,t,r={}){await de(e,JSON.stringify(t,null,2)+`
|
|
5
|
+
`,r)}var q=E(()=>{"use strict";We()});function Zv(e){return e.toLowerCase().startsWith(".env")}function oi(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>Zv(i))?"environment-file":r.some(i=>Qv.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>Xv.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var Xv,Qv,si=E(()=>{"use strict";Xv=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Qv=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});import{createHash as eg}from"node:crypto";import{promises as $e}from"node:fs";import Se from"node:path";import{TextDecoder as tg}from"node:util";function ts(e,t){let r=Se.relative(e,t);return r===""||!Se.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Se.sep}`)}function rg(e){let t=Se.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||Se.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=oi(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function ig(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function ng(e,t){return O({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Tn(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Me(r,i)?O(r,i):O(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Ru(e){let t=await $e.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await $e.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function ag(e,t){let r=Se.resolve(e),i=Se.resolve(t);if(!ts(r,i))throw new Error("Native artifact path is outside its root");let n=[await Ru(r)],a=r;for(let o of Se.relative(r,i).split(Se.sep).filter(Boolean)){a=Se.join(a,o);let s=await Ru(a);if(!ts(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Au(e){for(let t of e){let r=await $e.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!ng(t,r)||await $e.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function F(e){let t=rg(e.ref),r=e.maxBytes===null?null:ig(e.maxBytes??jn),i=Se.resolve(e.root,...t.split("/")),n=await ag(e.root,Se.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await $e.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await $e.realpath(i);if(!ts(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await $e.open(i,"r");try{let[c,l,f]=await Promise.all([s.stat(),$e.lstat(i),$e.realpath(i)]);if(await Au(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!Tn(a,c)||!Tn(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],u=0,p=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let b=r===null?p.length:r+1-u,w=await s.read(p,0,Math.min(p.length,b),null);if(w.bytesRead===0)break;if(u+=w.bytesRead,r!==null&&u>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,w.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[g,h,m]=await Promise.all([s.stat(),$e.lstat(i),$e.realpath(i)]);if(await Au(n),!h.isFile()||h.isSymbolicLink()||m!==o||!Tn(c,g)||!Tn(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let v=Buffer.concat(d,u),y;try{y=new tg("utf-8",{fatal:!0}).decode(v)}catch(b){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:b})}return{ref:t,size:u,hash:e.includeHash===!1?null:eg("sha256").update(v).digest("hex"),text:y}}finally{await s.close()}}var jn,Ee=E(()=>{"use strict";si();We();jn=1024*1024});var A=S(ee=>{"use strict";var rs=Symbol.for("yaml.alias"),_u=Symbol.for("yaml.document"),$n=Symbol.for("yaml.map"),Iu=Symbol.for("yaml.pair"),is=Symbol.for("yaml.scalar"),On=Symbol.for("yaml.seq"),ot=Symbol.for("yaml.node.type"),og=e=>!!e&&typeof e=="object"&&e[ot]===rs,sg=e=>!!e&&typeof e=="object"&&e[ot]===_u,cg=e=>!!e&&typeof e=="object"&&e[ot]===$n,lg=e=>!!e&&typeof e=="object"&&e[ot]===Iu,Tu=e=>!!e&&typeof e=="object"&&e[ot]===is,ug=e=>!!e&&typeof e=="object"&&e[ot]===On;function ju(e){if(e&&typeof e=="object")switch(e[ot]){case $n:case On:return!0}return!1}function dg(e){if(e&&typeof e=="object")switch(e[ot]){case rs:case $n:case is:case On:return!0}return!1}var fg=e=>(Tu(e)||ju(e))&&!!e.anchor;ee.ALIAS=rs;ee.DOC=_u;ee.MAP=$n;ee.NODE_TYPE=ot;ee.PAIR=Iu;ee.SCALAR=is;ee.SEQ=On;ee.hasAnchor=fg;ee.isAlias=og;ee.isCollection=ju;ee.isDocument=sg;ee.isMap=cg;ee.isNode=dg;ee.isPair=lg;ee.isScalar=Tu;ee.isSeq=ug});var ci=S(ns=>{"use strict";var z=A(),fe=Symbol("break visit"),$u=Symbol("skip children"),ze=Symbol("remove node");function Hn(e,t){let r=Ou(t);z.isDocument(e)?kr(null,e.contents,r,Object.freeze([e]))===ze&&(e.contents=null):kr(null,e,r,Object.freeze([]))}Hn.BREAK=fe;Hn.SKIP=$u;Hn.REMOVE=ze;function kr(e,t,r,i){let n=Hu(e,t,r,i);if(z.isNode(n)||z.isPair(n))return Du(e,i,n),kr(e,n,r,i);if(typeof n!="symbol"){if(z.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=kr(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===fe)return fe;o===ze&&(t.items.splice(a,1),a-=1)}}}else if(z.isPair(t)){i=Object.freeze(i.concat(t));let a=kr("key",t.key,r,i);if(a===fe)return fe;a===ze&&(t.key=null);let o=kr("value",t.value,r,i);if(o===fe)return fe;o===ze&&(t.value=null)}}return n}async function Dn(e,t){let r=Ou(t);z.isDocument(e)?await Sr(null,e.contents,r,Object.freeze([e]))===ze&&(e.contents=null):await Sr(null,e,r,Object.freeze([]))}Dn.BREAK=fe;Dn.SKIP=$u;Dn.REMOVE=ze;async function Sr(e,t,r,i){let n=await Hu(e,t,r,i);if(z.isNode(n)||z.isPair(n))return Du(e,i,n),Sr(e,n,r,i);if(typeof n!="symbol"){if(z.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await Sr(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===fe)return fe;o===ze&&(t.items.splice(a,1),a-=1)}}}else if(z.isPair(t)){i=Object.freeze(i.concat(t));let a=await Sr("key",t.key,r,i);if(a===fe)return fe;a===ze&&(t.key=null);let o=await Sr("value",t.value,r,i);if(o===fe)return fe;o===ze&&(t.value=null)}}return n}function Ou(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Hu(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(z.isMap(t))return r.Map?.(e,t,i);if(z.isSeq(t))return r.Seq?.(e,t,i);if(z.isPair(t))return r.Pair?.(e,t,i);if(z.isScalar(t))return r.Scalar?.(e,t,i);if(z.isAlias(t))return r.Alias?.(e,t,i)}function Du(e,t,r){let i=t[t.length-1];if(z.isCollection(i))i.items[e]=r;else if(z.isPair(i))e==="key"?i.key=r:i.value=r;else if(z.isDocument(i))i.contents=r;else{let n=z.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}ns.visit=Hn;ns.visitAsync=Dn});var as=S(Lu=>{"use strict";var Bu=A(),hg=ci(),pg={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},mg=e=>e.replace(/[!,[\]{}]/g,t=>pg[t]),li=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+mg(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&Bu.isNode(t.contents)){let a={};hg.visit(t.contents,(o,s)=>{Bu.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
|
|
6
|
+
`)}};li.defaultYaml={explicit:!1,version:"1.2"};li.defaultTags={"!!":"tag:yaml.org,2002:"};Lu.Directives=li});var Bn=S(ui=>{"use strict";var qu=A(),vg=ci();function gg(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function Fu(e){let t=new Set;return vg.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function Vu(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function wg(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Fu(e));let o=Vu(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(qu.isScalar(o.node)||qu.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:i}}ui.anchorIsValid=gg;ui.anchorNames=Fu;ui.createNodeAnchors=wg;ui.findNewAnchor=Vu});var os=S(Mu=>{"use strict";function di(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=di(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=di(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=di(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=di(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}Mu.applyReviver=di});var bt=S(zu=>{"use strict";var yg=A();function Wu(e,t,r){if(Array.isArray(e))return e.map((i,n)=>Wu(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!yg.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}zu.toJS=Wu});var Ln=S(Gu=>{"use strict";var Ng=os(),Ju=A(),bg=bt(),ss=class{constructor(t){Object.defineProperty(this,Ju.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!Ju.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=bg.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Ng.applyReviver(a,{"":s},"",s):s}};Gu.NodeBase=ss});var fi=S(Uu=>{"use strict";var kg=Bn(),Sg=ci(),Er=A(),Eg=Ln(),Pg=bt(),cs=class extends Eg.NodeBase{constructor(t){super(Er.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],Sg.visit(t,{Node:(a,o)=>{(Er.isAlias(o)||Er.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(Pg.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=qn(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(kg.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function qn(e,t,r){if(Er.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Er.isCollection(t)){let i=0;for(let n of t.items){let a=qn(e,n,r);a>i&&(i=a)}return i}else if(Er.isPair(t)){let i=qn(e,t.key,r),n=qn(e,t.value,r);return Math.max(i,n)}return 1}Uu.Alias=cs});var M=S(ls=>{"use strict";var xg=A(),Cg=Ln(),Rg=bt(),Ag=e=>!e||typeof e!="function"&&typeof e!="object",kt=class extends Cg.NodeBase{constructor(t){super(xg.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Rg.toJS(this.value,t,r)}toString(){return String(this.value)}};kt.BLOCK_FOLDED="BLOCK_FOLDED";kt.BLOCK_LITERAL="BLOCK_LITERAL";kt.PLAIN="PLAIN";kt.QUOTE_DOUBLE="QUOTE_DOUBLE";kt.QUOTE_SINGLE="QUOTE_SINGLE";ls.Scalar=kt;ls.isScalarValue=Ag});var hi=S(Yu=>{"use strict";var _g=fi(),Gt=A(),Ku=M(),Ig="tag:yaml.org,2002:";function Tg(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function jg(e,t,r){if(Gt.isDocument(e)&&(e=e.contents),Gt.isNode(e))return e;if(Gt.isPair(e)){let d=r.schema[Gt.MAP].createNode?.(r.schema,null,r);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new _g.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Ig+t.slice(2));let l=Tg(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Ku.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Gt.MAP]:Symbol.iterator in Object(e)?o[Gt.SEQ]:o[Gt.MAP]}a&&(a(l),delete r.onTagObj);let f=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new Ku.Scalar(e);return t?f.tag=t:l.default||(f.tag=l.tag),c&&(c.node=f),f}Yu.createNode=jg});var Vn=S(Fn=>{"use strict";var $g=hi(),Je=A(),Og=Ln();function us(e,t,r){let i=r;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return $g.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Xu=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,ds=class extends Og.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>Je.isNode(i)||Je.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(Xu(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(Je.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,us(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(Je.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&Je.isScalar(a)?a.value:a:Je.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Je.isPair(r))return!1;let i=r.value;return i==null||t&&Je.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return Je.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(Je.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,us(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};Fn.Collection=ds;Fn.collectionFromPath=us;Fn.isEmptyPath=Xu});var pi=S(Mn=>{"use strict";var Hg=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function fs(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Dg=(e,t,r)=>e.endsWith(`
|
|
7
7
|
`)?fs(r,t):r.includes(`
|
|
8
8
|
`)?`
|
|
9
9
|
`+fs(r,t):(e.endsWith(" ")?"":" ")+r;Mn.indentComment=fs;Mn.lineComment=Dg;Mn.stringifyComment=Hg});var Zu=S(mi=>{"use strict";var Bg="flow",hs="block",Wn="quoted";function Lg(e,t,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],f={},d=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):d=n-i);let u,p,g=!1,h=-1,m=-1,v=-1;r===hs&&(h=Qu(e,h,t.length),h!==-1&&(d=h+c));for(let b;b=e[h+=1];){if(r===Wn&&b==="\\"){switch(m=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}v=h}if(b===`
|
|
@@ -12,7 +12,7 @@ var Hv=Object.create;var es=Object.defineProperty;var Dv=Object.getOwnPropertyDe
|
|
|
12
12
|
`&&w!==" "&&(u=h)}if(h>=d)if(u)l.push(u),d=u+c,u=void 0;else if(r===Wn){for(;p===" "||p===" ";)p=b,b=e[h+=1],g=!0;let w=h>v+1?h-2:m-1;if(f[w])return e;l.push(w),f[w]=!0,d=w+c,u=void 0}else g=!0}p=b}if(g&&s&&s(),l.length===0)return e;o&&o();let y=e.slice(0,l[0]);for(let b=0;b<l.length;++b){let w=l[b],N=l[b+1]||e.length;w===0?y=`
|
|
13
13
|
${t}${e.slice(0,N)}`:(r===Wn&&f[w]&&(y+=`${e[w]}\\`),y+=`
|
|
14
14
|
${t}${e.slice(w+1,N)}`)}return y}function Qu(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
15
|
-
`);i=t,n=t+1,a=e[n]}return i}mi.FOLD_BLOCK=hs;mi.FOLD_FLOW=Bg;mi.FOLD_QUOTED=Wn;mi.foldFlowLines=Lg});var gi=S(ed=>{"use strict";var
|
|
15
|
+
`);i=t,n=t+1,a=e[n]}return i}mi.FOLD_BLOCK=hs;mi.FOLD_FLOW=Bg;mi.FOLD_QUOTED=Wn;mi.foldFlowLines=Lg});var gi=S(ed=>{"use strict";var Oe=M(),St=Zu(),Jn=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Gn=e=>/^(%|---|\.\.\.)/m.test(e);function qg(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
|
|
16
16
|
`){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function vi(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Gn(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let f=r.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
|
|
17
17
|
|
|
18
18
|
`;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
|
|
@@ -21,28 +21,28 @@ ${t}${e.slice(w+1,N)}`)}return y}function Qu(e,t,r){let i=t,n=t+1,a=e[n];for(;a=
|
|
|
21
21
|
${r}`)+"'";return t.implicitKey?i:St.foldFlowLines(i,r,St.FOLD_FLOW,Jn(t,!1))}function Pr(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=vi;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=ps:a&&!n?i=vi:i=r?ps:vi}return i(e,t)}var ms;try{ms=new RegExp(`(^|(?<!
|
|
22
22
|
))
|
|
23
23
|
+(?!
|
|
24
|
-
|$)`,"g")}catch{ms=/\n+(?!\n|$)/g}function zn({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return Pr(r,i);let l=i.indent||(i.forceBlockIndent||Gn(r)?" ":""),f=o==="literal"?!0:o==="folded"||t
|
|
24
|
+
|$)`,"g")}catch{ms=/\n+(?!\n|$)/g}function zn({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return Pr(r,i);let l=i.indent||(i.forceBlockIndent||Gn(r)?" ":""),f=o==="literal"?!0:o==="folded"||t===Oe.Scalar.BLOCK_FOLDED?!1:t===Oe.Scalar.BLOCK_LITERAL?!0:!qg(r,c,l.length);if(!r)return f?`|
|
|
25
25
|
`:`>
|
|
26
26
|
`;let d,u;for(u=r.length;u>0;--u){let N=r[u-1];if(N!==`
|
|
27
27
|
`&&N!==" "&&N!==" ")break}let p=r.substring(u),g=p.indexOf(`
|
|
28
28
|
`);g===-1?d="-":r===p||g!==p.length-1?(d="+",a&&a()):d="",p&&(r=r.slice(0,-p.length),p[p.length-1]===`
|
|
29
29
|
`&&(p=p.slice(0,-1)),p=p.replace(ms,`$&${l}`));let h=!1,m,v=-1;for(m=0;m<r.length;++m){let N=r[m];if(N===" ")h=!0;else if(N===`
|
|
30
30
|
`)v=m;else break}let y=r.substring(0,v<m?v+1:m);y&&(r=r.substring(y.length),y=y.replace(/\n+/g,`$&${l}`));let w=(h?l?"2":"1":"")+d;if(e&&(w+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!f){let N=r.replace(/\n+/g,`
|
|
31
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),P=!1,x=Jn(i,!0);o!=="folded"&&t
|
|
31
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),P=!1,x=Jn(i,!0);o!=="folded"&&t!==Oe.Scalar.BLOCK_FOLDED&&(x.onOverflow=()=>{P=!0});let k=St.foldFlowLines(`${y}${N}${p}`,l,St.FOLD_BLOCK,x);if(!P)return`>${w}
|
|
32
32
|
${l}${k}`}return r=r.replace(/\n+/g,`$&${l}`),`|${w}
|
|
33
33
|
${l}${y}${r}${p}`}function Fg(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:f}=t;if(s&&a.includes(`
|
|
34
34
|
`)||f&&/[[\]{},]/.test(a))return Pr(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||f||!a.includes(`
|
|
35
|
-
`)?Pr(a,t):zn(e,t,r,i);if(!s&&!f&&n
|
|
35
|
+
`)?Pr(a,t):zn(e,t,r,i);if(!s&&!f&&n!==Oe.Scalar.PLAIN&&a.includes(`
|
|
36
36
|
`))return zn(e,t,r,i);if(Gn(a)){if(c==="")return t.forceBlockIndent=!0,zn(e,t,r,i);if(s&&c===l)return Pr(a,t)}let d=a.replace(/\n+/g,`$&
|
|
37
|
-
${c}`);if(o){let u=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:g}=t.doc.schema;if(g.some(u)||p?.some(u))return Pr(a,t)}return s?d:St.foldFlowLines(d,c,St.FOLD_FLOW,Jn(t,!1))}function Vg(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s
|
|
38
|
-
${t.indent}${s}`:s}vs.createStringifyContext=Jg;vs.stringify=Kg});var nd=S(id=>{"use strict";var
|
|
39
|
-
${s}:`):(m=`${m}:`,u&&(m+=yi.lineComment(m,r.indent,l(u))));let v,y,b;
|
|
37
|
+
${c}`);if(o){let u=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:g}=t.doc.schema;if(g.some(u)||p?.some(u))return Pr(a,t)}return s?d:St.foldFlowLines(d,c,St.FOLD_FLOW,Jn(t,!1))}function Vg(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==Oe.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Oe.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case Oe.Scalar.BLOCK_FOLDED:case Oe.Scalar.BLOCK_LITERAL:return n||a?Pr(o.value,t):zn(o,t,r,i);case Oe.Scalar.QUOTE_DOUBLE:return vi(o.value,t);case Oe.Scalar.QUOTE_SINGLE:return ps(o.value,t);case Oe.Scalar.PLAIN:return Fg(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:d}=t.options,u=n&&f||d;if(l=c(u),l===null)throw new Error(`Unsupported default string type ${u}`)}return l}ed.stringifyString=Vg});var wi=S(vs=>{"use strict";var Mg=Bn(),Et=A(),Wg=pi(),zg=gi();function Jg(e,t){let r=Object.assign({blockQuote:!0,commentString:Wg.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function Gg(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let r,i;if(Et.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function Ug(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(Et.isScalar(e)||Et.isCollection(e))&&e.anchor;a&&Mg.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function Kg(e,t,r,i){if(Et.isPair(e))return e.toString(t,r,i);if(Et.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=Et.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=Gg(t.doc.schema.tags,a));let o=Ug(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):Et.isScalar(a)?zg.stringifyString(a,t,r,i):a.toString(t,r,i);return o?Et.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
38
|
+
${t.indent}${s}`:s}vs.createStringifyContext=Jg;vs.stringify=Kg});var nd=S(id=>{"use strict";var st=A(),td=M(),rd=wi(),yi=pi();function Yg({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:d}}=r,u=st.isNode(e)&&e.comment||null;if(d){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(st.isCollection(e)||!st.isNode(e)&&typeof e=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let p=!d&&(!e||u&&t==null&&!r.inFlow||st.isCollection(e)||(st.isScalar(e)?e.type===td.Scalar.BLOCK_FOLDED||e.type===td.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let g=!1,h=!1,m=rd.stringify(e,r,()=>g=!0,()=>h=!0);if(!p&&!r.inFlow&&m.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(r.inFlow){if(a||t==null)return g&&i&&i(),m===""?"?":p?`? ${m}`:m}else if(a&&!d||t==null&&p)return m=`? ${m}`,u&&!g?m+=yi.lineComment(m,r.indent,l(u)):h&&n&&n(),m;g&&(u=null),p?(u&&(m+=yi.lineComment(m,r.indent,l(u))),m=`? ${m}
|
|
39
|
+
${s}:`):(m=`${m}:`,u&&(m+=yi.lineComment(m,r.indent,l(u))));let v,y,b;st.isNode(t)?(v=!!t.spaceBefore,y=t.commentBefore,b=t.comment):(v=!1,y=null,b=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!p&&!u&&st.isScalar(t)&&(r.indentAtStart=m.length+1),h=!1,!f&&c.length>=2&&!r.inFlow&&!p&&st.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let w=!1,N=rd.stringify(t,r,()=>w=!0,()=>h=!0),P=" ";if(u||v||y){if(P=v?`
|
|
40
40
|
`:"",y){let x=l(y);P+=`
|
|
41
41
|
${yi.indentComment(x,r.indent)}`}N===""&&!r.inFlow?P===`
|
|
42
42
|
`&&b&&(P=`
|
|
43
43
|
|
|
44
44
|
`):P+=`
|
|
45
|
-
${r.indent}`}else if(!p&&
|
|
45
|
+
${r.indent}`}else if(!p&&st.isCollection(t)){let x=N[0],k=N.indexOf(`
|
|
46
46
|
`),_=k!==-1,ue=r.inFlow??t.flow??t.items.length===0;if(_||!ue){let ae=!1;if(_&&(x==="&"||x==="!")){let j=N.indexOf(" ");x==="&"&&j!==-1&&j<k&&N[j+1]==="!"&&(j=N.indexOf(" ",j+1)),(j===-1||k<j)&&(ae=!0)}ae||(P=`
|
|
47
47
|
${r.indent}`)}}else(N===""||N[0]===`
|
|
48
48
|
`)&&(P="");return m+=P+N,r.inFlow?w&&i&&i():b&&!w?m+=yi.lineComment(m,r.indent,l(b)):h&&n&&n(),m}id.stringifyPair=Yg});var ws=S(gs=>{"use strict";var ad=An("process");function Xg(e,...t){e==="debug"&&console.log(...t)}function Qg(e,t){(e==="debug"||e==="warn")&&(typeof ad.emitWarning=="function"?ad.emitWarning(t):console.warn(t))}gs.debug=Xg;gs.warn=Qg});var Qn=S(Xn=>{"use strict";var Yn=A(),od=M(),Un="<<",Kn={identify:e=>e===Un||typeof e=="symbol"&&e.description===Un,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new od.Scalar(Symbol(Un)),{addToJSMap:sd}),stringify:()=>Un},Zg=(e,t)=>(Kn.identify(t)||Yn.isScalar(t)&&(!t.type||t.type===od.Scalar.PLAIN)&&Kn.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===Kn.tag&&r.default);function sd(e,t,r){let i=cd(e,r);if(Yn.isSeq(i))for(let n of i.items)ys(e,t,n);else if(Array.isArray(i))for(let n of i)ys(e,t,n);else ys(e,t,i)}function ys(e,t,r){let i=cd(e,r);if(!Yn.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function cd(e,t){return e&&Yn.isAlias(t)?t.resolve(e.doc,e):t}Xn.addMergeToJSMap=sd;Xn.isMergeKey=Zg;Xn.merge=Kn});var bs=S(dd=>{"use strict";var ew=ws(),ld=Qn(),tw=wi(),ud=A(),Ns=bt();function rw(e,t,{key:r,value:i}){if(ud.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(ld.isMergeKey(e,r))ld.addMergeToJSMap(e,t,i);else{let n=Ns.toJS(r,"",e);if(t instanceof Map)t.set(n,Ns.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=iw(r,n,e),o=Ns.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function iw(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(ud.isNode(e)&&r?.doc){let i=tw.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),ew.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}dd.addPairToJSMap=rw});var Pt=S(ks=>{"use strict";var fd=hi(),nw=nd(),aw=bs(),Zn=A();function ow(e,t,r){let i=fd.createNode(e,void 0,r),n=fd.createNode(t,void 0,r);return new ea(i,n)}var ea=class e{constructor(t,r=null){Object.defineProperty(this,Zn.NODE_TYPE,{value:Zn.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return Zn.isNode(r)&&(r=r.clone(t)),Zn.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return aw.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?nw.stringifyPair(this,t,r,i):JSON.stringify(this)}};ks.Pair=ea;ks.createPair=ow});var Ss=S(pd=>{"use strict";var Ut=A(),hd=wi(),ta=pi();function sw(e,t,r){return(t.inFlow??e.flow?lw:cw)(e,t,r)}function cw({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,f=Object.assign({},r,{indent:a,type:null}),d=!1,u=[];for(let g=0;g<t.length;++g){let h=t[g],m=null;if(Ut.isNode(h))!d&&h.spaceBefore&&u.push(""),ra(r,u,h.commentBefore,d),h.comment&&(m=h.comment);else if(Ut.isPair(h)){let y=Ut.isNode(h.key)?h.key:null;y&&(!d&&y.spaceBefore&&u.push(""),ra(r,u,y.commentBefore,d))}d=!1;let v=hd.stringify(h,f,()=>m=null,()=>d=!0);m&&(v+=ta.lineComment(v,a,l(m))),d&&m&&(d=!1),u.push(i+v)}let p;if(u.length===0)p=n.start+n.end;else{p=u[0];for(let g=1;g<u.length;++g){let h=u[g];p+=h?`
|
|
@@ -69,7 +69,7 @@ ${l}
|
|
|
69
69
|
`+b.comment:y.comment=b.comment);let w=new wf.Pair(y);r.options.keepSourceTokens&&(w.srcToken=f),s.items.push(w)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}kf.resolveBlockMap=Ky});var Pf=S(Ef=>{"use strict";var Yy=Rt(),Xy=Ti(),Qy=cc();function Zy({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??Yy.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=i.offset,l=null;for(let{start:f,value:d}of i.items){let u=Xy.resolveProps(f,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!u.found)if(u.anchor||u.tag||d)d?.type==="block-seq"?n(u.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=u.end,u.comment&&(s.comment=u.comment);continue}let p=d?e(r,d,u,n):t(r,u.end,f,null,u,n);r.schema.compat&&Qy.flowIndentCheck(i.indent,d,n),c=p.range[2],s.items.push(p)}return s.range=[i.offset,c,l??c],s}Ef.resolveBlockSeq=Zy});var Ir=S(xf=>{"use strict";function eN(e,t,r,i){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";n?n+=o+f:n=f,o="";break}case"newline":n&&(o+=c),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}xf.resolveEnd=eN});var _f=S(Af=>{"use strict";var tN=A(),rN=Pt(),Cf=Ct(),iN=Rt(),nN=Ir(),Rf=Ti(),aN=Sa(),oN=lc(),uc="Block collections are not allowed within flow collections",dc=e=>e&&(e.type==="block-map"||e.type==="block-seq");function sN({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Cf.YAMLMap:iN.YAMLSeq),l=new c(r.schema);l.flow=!0;let f=r.atRoot;f&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let d=i.offset+i.start.source.length;for(let m=0;m<i.items.length;++m){let v=i.items[m],{start:y,key:b,sep:w,value:N}=v,P=Rf.resolveProps(y,{flow:s,indicator:"explicit-key-ind",next:b??w?.[0],offset:d,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!P.found){if(!P.anchor&&!P.tag&&!w&&!N){m===0&&P.comma?n(P.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<i.items.length-1&&n(P.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),P.comment&&(l.comment?l.comment+=`
|
|
70
70
|
`+P.comment:l.comment=P.comment),d=P.end;continue}!o&&r.options.strict&&aN.containsNewline(b)&&n(b,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)P.comma&&n(P.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(P.comma||n(P.start,"MISSING_CHAR",`Missing , between ${s} items`),P.comment){let x="";e:for(let k of y)switch(k.type){case"comma":case"space":break;case"comment":x=k.source.substring(1);break e;default:break e}if(x){let k=l.items[l.items.length-1];tN.isPair(k)&&(k=k.value??k.key),k.comment?k.comment+=`
|
|
71
71
|
`+x:k.comment=x,P.comment=P.comment.substring(x.length+1)}}if(!o&&!w&&!P.found){let x=N?e(r,N,P,n):t(r,P.end,w,null,P,n);l.items.push(x),d=x.range[2],dc(N)&&n(x.range,"BLOCK_IN_FLOW",uc)}else{r.atKey=!0;let x=P.end,k=b?e(r,b,P,n):t(r,x,y,null,P,n);dc(b)&&n(k.range,"BLOCK_IN_FLOW",uc),r.atKey=!1;let _=Rf.resolveProps(w??[],{flow:s,indicator:"map-value-ind",next:N,offset:k.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(_.found){if(!o&&!P.found&&r.options.strict){if(w)for(let j of w){if(j===_.found)break;if(j.type==="newline"){n(j,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}P.start<_.found.offset-1024&&n(_.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else N&&("source"in N&&N.source?.[0]===":"?n(N,"MISSING_CHAR",`Missing space after : in ${s}`):n(_.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let ue=N?e(r,N,_,n):_.found?t(r,_.end,w,null,_,n):null;ue?dc(N)&&n(ue.range,"BLOCK_IN_FLOW",uc):_.comment&&(k.comment?k.comment+=`
|
|
72
|
-
`+_.comment:k.comment=_.comment);let ae=new rN.Pair(k,ue);if(r.options.keepSourceTokens&&(ae.srcToken=v),o){let j=l;oN.mapIncludes(r,j.items,k)&&n(x,"DUPLICATE_KEY","Map keys must be unique"),j.items.push(ae)}else{let j=new Cf.YAMLMap(r.schema);j.flow=!0,j.items.push(ae);let
|
|
72
|
+
`+_.comment:k.comment=_.comment);let ae=new rN.Pair(k,ue);if(r.options.keepSourceTokens&&(ae.srcToken=v),o){let j=l;oN.mapIncludes(r,j.items,k)&&n(x,"DUPLICATE_KEY","Map keys must be unique"),j.items.push(ae)}else{let j=new Cf.YAMLMap(r.schema);j.flow=!0,j.items.push(ae);let at=(ue??k).range;j.range=[k.range[0],at[1],at[2]],l.items.push(j)}d=ue?ue.range[2]:_.end}}let u=o?"}":"]",[p,...g]=i.end,h=d;if(p?.source===u)h=p.offset+p.source.length;else{let m=s[0].toUpperCase()+s.substring(1),v=f?`${m} must end with a ${u}`:`${m} in block collection must be sufficiently indented and end with a ${u}`;n(d,f?"MISSING_CHAR":"BAD_INDENT",v),p&&p.source.length!==1&&g.unshift(p)}if(g.length>0){let m=nN.resolveEnd(g,h,r.options.strict,n);m.comment&&(l.comment?l.comment+=`
|
|
73
73
|
`+m.comment:l.comment=m.comment),l.range=[i.offset,h,m.offset]}else l.range=[i.offset,h,h];return l}Af.resolveFlowCollection=sN});var Tf=S(If=>{"use strict";var cN=A(),lN=M(),uN=Ct(),dN=Rt(),fN=Sf(),hN=Pf(),pN=_f();function fc(e,t,r,i,n,a){let o=r.type==="block-map"?fN.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?hN.resolveBlockSeq(e,t,r,i,a):pN.resolveFlowCollection(e,t,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function mN(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,u=>n(a,"TAG_RESOLVE_FAILED",u)):null;if(r.type==="block-seq"){let{anchor:u,newlineAfterProp:p}=i,g=u&&a?u.offset>a.offset?u:a:u??a;g&&(!p||p.offset<g.offset)&&n(g,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===uN.YAMLMap.tagName&&s==="map"||o===dN.YAMLSeq.tagName&&s==="seq")return fc(e,t,r,n,o);let c=t.schema.tags.find(u=>u.tag===o&&u.collection===s);if(!c){let u=t.schema.knownTags[o];if(u?.collection===s)t.schema.tags.push(Object.assign({},u,{default:!1})),c=u;else return u?n(a,"BAD_COLLECTION_TYPE",`${u.tag} used for ${s} collection, but expects ${u.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),fc(e,t,r,n,o)}let l=fc(e,t,r,n,o,c),f=c.resolve?.(l,u=>n(a,"TAG_RESOLVE_FAILED",u),t.options)??l,d=cN.isNode(f)?f:new lN.Scalar(f);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}If.composeCollection=mN});var pc=S(jf=>{"use strict";var hc=M();function vN(e,t,r){let i=t.offset,n=gN(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?hc.Scalar.BLOCK_FOLDED:hc.Scalar.BLOCK_LITERAL,o=t.source?wN(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
|
|
74
74
|
`.repeat(Math.max(1,o.length-1)):"",m=i+n.length;return t.source&&(m+=t.source.length),{value:h,type:a,comment:n.comment,range:[i,m,m]}}let c=t.indent+n.indent,l=t.offset+n.length,f=0;for(let h=0;h<s;++h){let[m,v]=o[h];if(v===""||v==="\r")n.indent===0&&m.length>c&&(c=m.length);else{m.length<c&&r(l+m.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=m.length),f=h,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=m.length+v.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let d="",u="",p=!1;for(let h=0;h<f;++h)d+=o[h][0].slice(c)+`
|
|
75
75
|
`;for(let h=f;h<s;++h){let[m,v]=o[h];l+=m.length+v.length+1;let y=v[v.length-1]==="\r";if(y&&(v=v.slice(0,-1)),v&&m.length<c){let w=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-v.length-(y?2:1),"BAD_INDENT",w),m=""}a===hc.Scalar.BLOCK_LITERAL?(d+=u+m.slice(c)+v,u=`
|
|
@@ -117,24 +117,24 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
|
|
|
117
117
|
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function Xf(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function bc(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of i)a.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
118
118
|
`};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}Ea.createScalarToken=ZN;Ea.resolveAsScalar=QN;Ea.setScalarValue=eb});var eh=S(Zf=>{"use strict";var rb=e=>"type"in e?xa(e):Pa(e);function xa(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=xa(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Pa(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Pa(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Pa(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function Pa({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=xa(t)),r)for(let a of r)n+=a.source;return i&&(n+=xa(i)),n}Zf.stringify=rb});var nh=S(ih=>{"use strict";var kc=Symbol("break visit"),ib=Symbol("skip children"),th=Symbol("remove item");function Qt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),rh(Object.freeze([]),e,t)}Qt.BREAK=kc;Qt.SKIP=ib;Qt.REMOVE=th;Qt.itemAtPath=(e,t)=>{let r=e;for(let[i,n]of t){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};Qt.parentCollection=(e,t)=>{let r=Qt.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function rh(e,t,r){let i=r(t,e);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=rh(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===kc)return kc;s===th&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}ih.visit=Qt});var Ca=S(he=>{"use strict";var Sc=Qf(),nb=eh(),ab=nh(),Ec="\uFEFF",Pc="",xc="",Cc="",ob=e=>!!e&&"items"in e,sb=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function cb(e){switch(e){case Ec:return"<BOM>";case Pc:return"<DOC>";case xc:return"<FLOW_END>";case Cc:return"<SCALAR>";default:return JSON.stringify(e)}}function lb(e){switch(e){case Ec:return"byte-order-mark";case Pc:return"doc-mode";case xc:return"flow-error-end";case Cc:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
119
119
|
`:case`\r
|
|
120
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}he.createScalarToken=Sc.createScalarToken;he.resolveAsScalar=Sc.resolveAsScalar;he.setScalarValue=Sc.setScalarValue;he.stringify=nb.stringify;he.visit=ab.visit;he.BOM=Ec;he.DOCUMENT=Pc;he.FLOW_END=xc;he.SCALAR=Cc;he.isCollection=ob;he.isScalar=sb;he.prettyToken=cb;he.tokenType=lb});var _c=S(oh=>{"use strict";var Oi=Ca();function
|
|
120
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}he.createScalarToken=Sc.createScalarToken;he.resolveAsScalar=Sc.resolveAsScalar;he.setScalarValue=Sc.setScalarValue;he.stringify=nb.stringify;he.visit=ab.visit;he.BOM=Ec;he.DOCUMENT=Pc;he.FLOW_END=xc;he.SCALAR=Cc;he.isCollection=ob;he.isScalar=sb;he.prettyToken=cb;he.tokenType=lb});var _c=S(oh=>{"use strict";var Oi=Ca();function He(e){switch(e){case void 0:case" ":case`
|
|
121
121
|
`:case"\r":case" ":return!0;default:return!1}}var ah=new Set("0123456789ABCDEFabcdef"),ub=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ra=new Set(",[]{}"),db=new Set(` ,[]{}
|
|
122
122
|
\r `),Rc=e=>!e||db.has(e),Ac=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
|
|
123
123
|
`?!0:r==="\r"?this.buffer[t+1]===`
|
|
124
124
|
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let i=0;for(;r===" ";)r=this.buffer[++i+t];if(r==="\r"){let n=this.buffer[i+t+1];if(n===`
|
|
125
125
|
`||!n&&!this.atEnd)return t+i+1}return r===`
|
|
126
|
-
`||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&
|
|
127
|
-
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Oi.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield Oi.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&
|
|
126
|
+
`||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&He(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
|
|
127
|
+
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Oi.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield Oi.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&He(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!He(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&He(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Rc),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&He(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield Oi.FLOW_END,yield*this.parseLineStart();let a=0;for(;n[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),n[a]){case void 0:return"flow";case"#":return yield*this.pushCount(n.length-a),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Rc),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||He(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
|
|
128
128
|
`,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
|
|
129
|
-
`,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>
|
|
129
|
+
`,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>He(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
|
|
130
130
|
`:t=a,r=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
131
131
|
`)break}default:break e}if(!i&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
|
|
132
132
|
`,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(i=this.buffer[n];i===" ";)i=this.buffer[++n];if(i===" "){for(;i===" "||i===" "||i==="\r"||i===`
|
|
133
133
|
`;)i=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
|
|
134
|
-
`&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield Oi.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(
|
|
134
|
+
`&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield Oi.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(He(a)||t&&Ra.has(a))break;r=i}else if(He(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
|
|
135
135
|
`?(i+=1,n=`
|
|
136
136
|
`,a=this.buffer[i+1]):r=i),a==="#"||t&&Ra.has(a))break;if(n===`
|
|
137
|
-
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&Ra.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Oi.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Rc),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(
|
|
137
|
+
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&Ra.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Oi.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Rc),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(He(i)||r&&Ra.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!He(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(ub.has(r))r=this.buffer[++t];else if(r==="%"&&ah.has(this.buffer[t+1])&&ah.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
|
|
138
138
|
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
139
139
|
`?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};oh.Lexer=Ac});var Tc=S(sh=>{"use strict";var Ic=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<t?r=a+1:i=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let n=this.lineStarts[r-1];return{line:r,col:t-n+1}}}};sh.LineCounter=Ic});var $c=S(fh=>{"use strict";var fb=An("process"),ch=Ca(),hb=_c();function At(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function lh(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function dh(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Aa(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Tr(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function _a(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function uh(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!At(t.start,"explicit-key-ind")&&!At(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,dh(t.value)?t.value.end?_a(t.value.end,t.sep):t.value.end=t.sep:_a(t.start,t.sep),delete t.sep)}var jc=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new hb.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,r))yield*this.next(i);r||(yield*this.end())}*next(t){if(this.source=t,fb.env.LOG_TOKENS&&console.log("|",ch.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=ch.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let i=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in i?i.indent:0:r.type==="flow-collection"&&i.type==="document"&&(r.indent=0),r.type==="flow-collection"&&uh(r),i.type){case"document":i.value=r;break;case"block-scalar":i.props.push(r);break;case"block-map":{let n=i.items[i.items.length-1];if(n.value){i.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=r;else{Object.assign(n,{key:r,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=i.items[i.items.length-1];n.value?i.items.push({start:[],value:r}):n.value=r;break}case"flow-collection":{let n=i.items[i.items.length-1];!n||n.value?i.items.push({start:[],key:r,sep:[]}):n.sep?n.value=r:Object.assign(n,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let n=r.items[r.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&lh(n.start)===-1&&(r.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(i.type==="document"?i.end=n.start:i.items.push({start:n.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{lh(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=Aa(this.peek(2)),i=Tr(r),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
|
|
140
140
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
@@ -142,18 +142,18 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
|
|
|
142
142
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
143
143
|
`,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=Aa(t),i=Tr(r);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=Aa(t),i=Tr(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};fh.Parser=jc});var gh=S(Di=>{"use strict";var hh=Nc(),pb=Ri(),Hi=Ii(),mb=ws(),vb=A(),gb=Tc(),ph=$c();function mh(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new gb.LineCounter||null,prettyErrors:t}}function wb(e,t={}){let{lineCounter:r,prettyErrors:i}=mh(t),n=new ph.Parser(r?.addNewLine),a=new hh.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(Hi.prettifyError(e,r)),s.warnings.forEach(Hi.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function vh(e,t={}){let{lineCounter:r,prettyErrors:i}=mh(t),n=new ph.Parser(r?.addNewLine),a=new hh.Composer(t),o=null;for(let s of a.compose(n.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Hi.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(Hi.prettifyError(e,r)),o.warnings.forEach(Hi.prettifyError(e,r))),o}function yb(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=vh(e,r);if(!n)return null;if(n.warnings.forEach(a=>mb.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:i},r))}function Nb(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return vb.isDocument(e)&&!i?e.toString(r):new pb.Document(e,i,r).toString(r)}Di.parse=yb;Di.parseAllDocuments=wb;Di.parseDocument=vh;Di.stringify=Nb});var jr=S(I=>{"use strict";var bb=Nc(),kb=Ri(),Sb=ec(),Oc=Ii(),Eb=fi(),_t=A(),Pb=Pt(),xb=M(),Cb=Ct(),Rb=Rt(),Ab=Ca(),_b=_c(),Ib=Tc(),Tb=$c(),Ia=gh(),wh=ci();I.Composer=bb.Composer;I.Document=kb.Document;I.Schema=Sb.Schema;I.YAMLError=Oc.YAMLError;I.YAMLParseError=Oc.YAMLParseError;I.YAMLWarning=Oc.YAMLWarning;I.Alias=Eb.Alias;I.isAlias=_t.isAlias;I.isCollection=_t.isCollection;I.isDocument=_t.isDocument;I.isMap=_t.isMap;I.isNode=_t.isNode;I.isPair=_t.isPair;I.isScalar=_t.isScalar;I.isSeq=_t.isSeq;I.Pair=Pb.Pair;I.Scalar=xb.Scalar;I.YAMLMap=Cb.YAMLMap;I.YAMLSeq=Rb.YAMLSeq;I.CST=Ab;I.Lexer=_b.Lexer;I.LineCounter=Ib.LineCounter;I.Parser=Tb.Parser;I.parse=Ia.parse;I.parseAllDocuments=Ia.parseAllDocuments;I.parseDocument=Ia.parseDocument;I.stringify=Ia.stringify;I.visit=wh.visit;I.visitAsync=wh.visitAsync});function jb(e,t){return Hc[e][t]}function Dc(e,t){return Nh[e][t]??bh[e][t]}function Bc(e){return kh.get(e.trim().toLocaleLowerCase("en-US"))??null}function Ta(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${jb(e,r)}
|
|
144
144
|
`).join(`
|
|
145
|
-
`)}function pe(e,t,r){return e==="zh-CN"?r:t}var Hc,Nh,bh,kh,yh,Zt=E(()=>{"use strict";Hc={en:{outcome:"Outcome",scope:"Scope",nonGoals:"Non-goals",acceptanceExamples:"Acceptance examples",constraints:"Constraints and invariants",decisions:"Decisions",openQuestions:"Open questions",verificationExpectations:"Verification expectations"},"zh-CN":{outcome:"目标",scope:"范围",nonGoals:"非目标",acceptanceExamples:"验收示例",constraints:"约束与不变量",decisions:"决策",openQuestions:"待解决问题",verificationExpectations:"验证预期"}},Nh={en:{verification:"Verification",currentResult:"Current result",acceptance:"Acceptance",checks:"Checks",blockers:"Blockers",risks:"Risks and skipped work",previousIterations:"Previous iterations",conclusion:"Conclusion"},"zh-CN":{verification:"验证",currentResult:"当前结果",acceptance:"验收",checks:"检查",blockers:"阻塞项",risks:"风险与跳过的工作",previousIterations:"之前的迭代",conclusion:"结论"}},bh={en:{acceptanceEvidence:"Acceptance evidence",commandsAndResults:"Commands and results",skippedChecks:"Skipped checks",specConsistency:"Spec consistency",knownLimitationsAndRisks:"Known limitations and risks",conclusion:"Conclusion"},"zh-CN":{acceptanceEvidence:"验收证据",commandsAndResults:"命令与结果",skippedChecks:"跳过的检查",specConsistency:"规格一致性",knownLimitationsAndRisks:"已知限制与风险",conclusion:"结论"}},kh=new Map,yh=new Map;for(let e of Object.keys(Hc)){for(let[t,r]of Object.entries(Hc[e]))kh.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Nh[e]))yh.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(bh[e]))yh.set(r.toLocaleLowerCase("en-US"),t)}});import It from"path";function Bb(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||It.posix.isAbsolute(r)||It.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function er(e){let t=Bb(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Rh(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function Ha(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||It.posix.isAbsolute(i)||It.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function st(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Ah(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function Vc(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>$a)throw new Error(`${t} exceeds ${$a} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>Oa)throw new Error(`${t} contains more than ${Oa} wildcard tokens`);return e}function xh(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>Vc(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function Lc(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function Lb(e){if(e===void 0)return{...we,include:[...we.include],exclude:[...we.exclude]};let t=st(e,"native.snapshot");return{include:xh(t.include,"native.snapshot.include",we.include),exclude:xh(t.exclude,"native.snapshot.exclude",we.exclude),max_files:Lc(t.max_files,we.max_files,"native.snapshot.max_files"),max_total_bytes:Lc(t.max_total_bytes,we.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Lc(t.max_duration_ms,we.max_duration_ms,"native.snapshot.max_duration_ms")}}function qb(e){if(e===void 0)return;let t=st(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=st(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,f=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:r,fromArtifactRoot:er(i),toArtifactRoot:er(n),stage:a,...o?{cleanup:o}:{}}}function Fb(e){if(e===void 0)return;let t=st(e,"native.finish");if(t.pull_request===void 0)return{};let r=st(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(It.posix.isAbsolute(i[0])||It.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??$b;if(!Number.isSafeInteger(n)||n<1||n>Ph)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Ph}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function Vb(e,t={}){let r=st(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??Fc;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=qb(r.pending_root_move),c=Fb(r.finish);return{artifact_root:er(i),language:Ah(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:Lb(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function Mb(e){let t=st(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Rh(t.artifact_layout),language:Ah(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function Wb(e){let r=st(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>Ha(i,`hook.allow_paths[${n}]`)))]}}function zb(e){if(e===void 0)return{...ja};let t=st(e,"memory"),r=t.learning??ja.learning,i=t.retrieval??ja.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function Mc(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Jb(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||It.posix.isAbsolute(r)||It.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>Sh)throw new Error(`${t} exceeds ${Sh} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>Eh)throw new Error(`${t} contains more than ${Eh} wildcard tokens`);return r}function Gb(e){let r=Mc(e,"knowledge.local").include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(r.map((i,n)=>Jb(i,`knowledge.local.include[${n}]`)))]}}function Ub(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function Kb(e){let t=Mc(e,"knowledge.remote"),r=Ub(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function Yb(e){if(e===void 0)return{...Ch};let t=Mc(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:Gb(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:Kb(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function Xb(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function Qb(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let f=e.workflows??[e.default_workflow];if(!Array.isArray(f)||f.length===0||f.some(u=>u!=="native"&&u!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(f)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function Li(e,t={}){let r=(0,qc.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=Xb(n.ambient_resume),o=n.hook===void 0?void 0:Wb(n.hook),s=zb(n.memory),c=Yb(n.knowledge),l=n.native===void 0?void 0:Vb(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),f=n.classic===void 0?void 0:Mb(n.classic),d=Qb(n,o,s,c,l,f,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...f?{classic:f}:{}}}function Da(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...ja},knowledge:{...Ch},native:{artifact_root:er(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Fc,snapshot:{...we,include:[...we.include],exclude:[...we.exclude]}}}}var qc,Bi,$a,Oa,Sh,Eh,Fc,ja,Ch,$b,Ph,Ob,Hb,Db,we,Tt=E(()=>{"use strict";qc=ri(jr(),1),Bi=64*1024,$a=1024,Oa=64,Sh=1024,Eh=64,Fc=5,ja={learning:!0,retrieval:!0},Ch={provider:"local"},$b=12e4,Ph=6e5,Ob=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".devin/skills/**",".dsh/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],Hb=["**/.idea/**","**/.vscode/**",".codex/skills/**","**/node_modules/**","**/.next/**","**/.nuxt/**","**/.output/**","**/.svelte-kit/**","**/.vite/**","**/.parcel-cache/**","**/.turbo/**","**/.nx/cache/**","**/dist/**","**/build/**","**/out/**","**/coverage/**","**/.nyc_output/**","**/target/**","**/.gradle/**","**/.cxx/**","**/.externalNativeBuild/**","**/captures/**","**/__pycache__/**","**/.pytest_cache/**","**/.mypy_cache/**","**/.ruff_cache/**","**/.tox/**","**/.nox/**","**/.venv/**","**/venv/**","**/obj/**","**/CMakeFiles/**","**/cmake-build-*/**","**/.cache/**","**/tmp/**","**/temp/**","**/logs/**","**/*.tsbuildinfo","**/*.log","**/.DS_Store","**/Thumbs.db"],Db=[...Ob,...Hb].sort((e,t)=>e.localeCompare(t,"en")),we={include:["**/*"],exclude:[...Db],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});import{constants as Ba,promises as tr}from"fs";function Wc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function _h(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function qi(e){return{dev:e.dev,ino:e.ino,birthtime:Wc(e)}}function La(e,t){let r=qi(e),i=qi(t);return Ve(r,i)?O(r,i):O(r,i)&&Wc(e)===Wc(t)&&_h(e)===_h(t)&&e.size===t.size}async function rr(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 tr.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new He("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new He("too-large",`${i} exceeds ${t} bytes`);let o=await tr.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:qi(a)});let s=process.platform==="win32"?Ba.O_RDONLY:Ba.O_RDONLY|Ba.O_NOFOLLOW|Ba.O_NONBLOCK,c;try{c=await tr.open(e,s)}catch(l){throw l.code==="ELOOP"?new He("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,d]=await Promise.all([c.stat({bigint:n}),tr.lstat(e,{bigint:n}),tr.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||d!==o||!La(a,l)||!La(a,f))throw new He("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:qi(l)}),await r.hooks?.afterOpen?.();let u=[],p=0,g=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-p,{bytesRead:b}=await c.read(g,0,Math.min(g.length,y),null);if(b===0)break;if(p+=b,p>t)throw new He("too-large",`${i} exceeds ${t} bytes`);u.push(Buffer.from(g.subarray(0,b)))}await r.hooks?.beforeFinalCheck?.();let[h,m,v]=await Promise.all([c.stat({bigint:n}),tr.lstat(e,{bigint:n}),tr.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||v!==o||!La(a,h)||!La(a,m))throw new He("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:v,identity:qi(h)}),{bytes:Buffer.concat(u,p),stat:h,realPath:v}}finally{await c.close()}}var He,Fi=E(()=>{"use strict";ai();He=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as qa}from"fs";import jt from"path";function Zb(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function zc(e,t){let r=jt.relative(e,t);return r===""||!jt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${jt.sep}`)}async function Ih(e,t){let r=jt.resolve(e),i=await qa.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return qa.realpath(r)}async function Th(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=jt.join(n,r[a]);let o;try{o=await qa.lstat(n)}catch(f){if(Zb(f))return{exists:!1,kind:"missing"};throw f}let s=jt.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 qa.realpath(n);if(!zc(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 $r(e,t,r){let i=Ha(t,r.label),n=jt.resolve(e),a=await Ih(n,r.label),o=i.split("/"),s=jt.resolve(n,...o);if(!zc(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Th(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function $t(e,t,r,i){let n=await $r(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 Ih(n.projectRoot,i.label);return rr(n.target,r,{...i,verify:async(o,s)=>{if(!zc(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Th(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var ir=E(()=>{"use strict";Fi();Tt()});import{createHash as ek}from"crypto";function tk(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Fa(e,t={}){return(await Va(e,t)).document}async function rk(e){try{return(await $t(e,Vi,Bi,{label:Vi})).bytes}catch(t){if(tk(t))return null;throw t}}function ik(e){return e?{exists:!0,sha256:ek("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Va(e,t={}){let r=await rk(e);return{document:r?Li(r.toString("utf8"),t):null,identity:ik(r)}}async function Jc(e){return(await Fa(e))?.config??null}var Vi,Or=E(()=>{"use strict";Tt();ir();Vi=".comet/config.yaml"});var Hr=E(()=>{"use strict";ai()});var jA,Gc=E(()=>{"use strict";Hr();Or();ir();jA=16*1024});var Yc=E(()=>{"use strict";Hr();Tt();Or();ir();Gc()});import{existsSync as $h,promises as nr}from"fs";import T from"path";import ck from"os";async function Xc(e){try{return await nr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function uk(e){try{let t=await nr.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Br(e,t){let r=T.relative(e,t);return r===""||!T.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${T.sep}`)}async function Dr(e){let t=[],r=e;for(;!await Xc(r);){let n=T.dirname(r);if(n===r)break;t.push(T.basename(r)),r=n}let i=await nr.realpath(r);return T.resolve(i,...t.reverse())}async function Qc(e){try{return(await nr.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Wa(e){let t=T.resolve(e);try{(await nr.stat(t)).isDirectory()||(t=T.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=T.resolve(ck.homedir());for(;;){if(!(t===i&&r!==i)){let o=T.join(t,...Ma.split("/")),s=t===r||await uk(o);if(await Xc(o)&&s)return t}if(await Xc(T.join(t,".git")))return t;let a=T.dirname(t);if(a===t)return r;t=a}}function za(e){return er(e)}async function dk(e,t){let r=za(t),i=T.resolve(e,...r.split("/")),n=await nr.realpath(e),a=await Dr(i);if(!Br(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function ct(e,t){let r=za(t),i=await dk(e,r),n=T.join(i,"comet");if(await Qc(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Dr(i),Dr(n)]);if(!Br(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=T.resolve(e),c=T.join(s,".comet","runtime","native");if(await Qc(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([nr.realpath(s),Dr(c)]);if(!Br(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:T.join(e,...Ma.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:T.join(n,"specs"),changesDir:T.join(n,"changes"),archiveDir:T.join(n,"archive"),runtimeDir:c,changesRuntimeDir:T.join(c,"changes"),locksDir:T.join(c,"locks"),transactionsDir:T.join(c,"transactions")}}function Oh(e){if(!lk.test(e))throw new Error(`Invalid Native change name: ${e}`)}function xe(e,t){Oh(t);let r=T.join(e.changesRuntimeDir,t);if(!J(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Zc(e,t){Oh(t);let r=T.join(e.changesDir,t,"runtime");if(!J(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Je(e,t){let r=xe(e,t);if($h(r))return r;let i=Zc(e,t);return $h(i)?i:r}function Ge(e,t){let r=T.resolve(t);if(J(e.runtimeDir,r))return e.runtimeDir;if(J(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function J(e,t){return Br(T.resolve(e),T.resolve(t))}async function V(e,t){let r=T.resolve(e),i=T.resolve(t);if(!Br(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Qc(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Dr(r),Dr(i)]);if(!Br(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var Ma,lk,B=E(()=>{"use strict";Tt();Ma=".comet/config.yaml",lk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});function hk(e="docs",t="en"){return Da(e,t)}async function ye(e){let t=(await Fa(e))?.config??null;return t?.native?t:null}async function Wi(e){let t=await ye(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 Hh(e){let t=await Wa(e.startPath),r=await ye(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Ma} 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?za(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??hk(i??"docs"),a=await ct(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Ce=E(()=>{"use strict";Tt();Or();Yc();q();B()});import{AsyncLocalStorage as pk}from"async_hooks";import{randomUUID as Lh}from"crypto";import{promises as Re}from"fs";import qh from"os";import oe from"path";function vk(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function gk(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return r}function Vh(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 Ga(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Ve(r,i)?O(r,i):O(r,i)&&e.size===t.size}function el(e,t){return Ga(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function Ue(e){let t,r;try{let i=await rr(e,Dh,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof He?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${Dh} 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:gk(JSON.parse(t.toString("utf8")),e),identity:Vh(r)}}async function wk(e){return(await Ue(e))?.owner??null}function Mh(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==qh.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=Ek(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function yk(e,t){try{await Re.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await Re.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function tl(e,t){let r=await Ue(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!el(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Re.mkdir(t,{recursive:!0});let i=oe.join(t,`${oe.basename(e.file)}.${e.owner.id}.${Lh()}.removed`);try{await Re.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Ue(i);if(!n||n.owner.id!==e.owner.id||!Ga(n.identity,e.identity))throw await yk(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Re.rm(i,{force:!0}),"removed"}function Wh(e){return{id:Lh(),pid:process.pid,hostname:qh.hostname(),createdAt:new Date().toISOString(),operation:e}}async function zh(e,t){let r;try{r=await Re.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await wk(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)+`
|
|
146
|
-
`,"utf8"),await r.sync(),i=Vh(await r.stat({bigint:!0}))}finally{await r.close()}let n=await
|
|
145
|
+
`)}function pe(e,t,r){return e==="zh-CN"?r:t}var Hc,Nh,bh,kh,yh,Zt=E(()=>{"use strict";Hc={en:{outcome:"Outcome",scope:"Scope",nonGoals:"Non-goals",acceptanceExamples:"Acceptance examples",constraints:"Constraints and invariants",decisions:"Decisions",openQuestions:"Open questions",verificationExpectations:"Verification expectations"},"zh-CN":{outcome:"目标",scope:"范围",nonGoals:"非目标",acceptanceExamples:"验收示例",constraints:"约束与不变量",decisions:"决策",openQuestions:"待解决问题",verificationExpectations:"验证预期"}},Nh={en:{verification:"Verification",currentResult:"Current result",acceptance:"Acceptance",checks:"Checks",blockers:"Blockers",risks:"Risks and skipped work",previousIterations:"Previous iterations",conclusion:"Conclusion"},"zh-CN":{verification:"验证",currentResult:"当前结果",acceptance:"验收",checks:"检查",blockers:"阻塞项",risks:"风险与跳过的工作",previousIterations:"之前的迭代",conclusion:"结论"}},bh={en:{acceptanceEvidence:"Acceptance evidence",commandsAndResults:"Commands and results",skippedChecks:"Skipped checks",specConsistency:"Spec consistency",knownLimitationsAndRisks:"Known limitations and risks",conclusion:"Conclusion"},"zh-CN":{acceptanceEvidence:"验收证据",commandsAndResults:"命令与结果",skippedChecks:"跳过的检查",specConsistency:"规格一致性",knownLimitationsAndRisks:"已知限制与风险",conclusion:"结论"}},kh=new Map,yh=new Map;for(let e of Object.keys(Hc)){for(let[t,r]of Object.entries(Hc[e]))kh.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Nh[e]))yh.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(bh[e]))yh.set(r.toLocaleLowerCase("en-US"),t)}});import It from"path";function Bb(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||It.posix.isAbsolute(r)||It.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function er(e){let t=Bb(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Rh(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function Ha(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||It.posix.isAbsolute(i)||It.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function ct(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Ah(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function Vc(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>$a)throw new Error(`${t} exceeds ${$a} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>Oa)throw new Error(`${t} contains more than ${Oa} wildcard tokens`);return e}function xh(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>Vc(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function Lc(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function Lb(e){if(e===void 0)return{...we,include:[...we.include],exclude:[...we.exclude]};let t=ct(e,"native.snapshot");return{include:xh(t.include,"native.snapshot.include",we.include),exclude:xh(t.exclude,"native.snapshot.exclude",we.exclude),max_files:Lc(t.max_files,we.max_files,"native.snapshot.max_files"),max_total_bytes:Lc(t.max_total_bytes,we.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Lc(t.max_duration_ms,we.max_duration_ms,"native.snapshot.max_duration_ms")}}function qb(e){if(e===void 0)return;let t=ct(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=ct(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,f=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:r,fromArtifactRoot:er(i),toArtifactRoot:er(n),stage:a,...o?{cleanup:o}:{}}}function Fb(e){if(e===void 0)return;let t=ct(e,"native.finish");if(t.pull_request===void 0)return{};let r=ct(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(It.posix.isAbsolute(i[0])||It.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??$b;if(!Number.isSafeInteger(n)||n<1||n>Ph)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Ph}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function Vb(e,t={}){let r=ct(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??Fc;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=qb(r.pending_root_move),c=Fb(r.finish);return{artifact_root:er(i),language:Ah(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:Lb(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function Mb(e){let t=ct(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Rh(t.artifact_layout),language:Ah(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function Wb(e){let r=ct(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>Ha(i,`hook.allow_paths[${n}]`)))]}}function zb(e){if(e===void 0)return{...ja};let t=ct(e,"memory"),r=t.learning??ja.learning,i=t.retrieval??ja.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function Mc(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Jb(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||It.posix.isAbsolute(r)||It.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>Sh)throw new Error(`${t} exceeds ${Sh} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>Eh)throw new Error(`${t} contains more than ${Eh} wildcard tokens`);return r}function Gb(e){let r=Mc(e,"knowledge.local").include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(r.map((i,n)=>Jb(i,`knowledge.local.include[${n}]`)))]}}function Ub(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function Kb(e){let t=Mc(e,"knowledge.remote"),r=Ub(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function Yb(e){if(e===void 0)return{...Ch};let t=Mc(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:Gb(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:Kb(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function Xb(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function Qb(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let f=e.workflows??[e.default_workflow];if(!Array.isArray(f)||f.length===0||f.some(u=>u!=="native"&&u!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(f)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function Li(e,t={}){let r=(0,qc.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=Xb(n.ambient_resume),o=n.hook===void 0?void 0:Wb(n.hook),s=zb(n.memory),c=Yb(n.knowledge),l=n.native===void 0?void 0:Vb(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),f=n.classic===void 0?void 0:Mb(n.classic),d=Qb(n,o,s,c,l,f,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...f?{classic:f}:{}}}function Da(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...ja},knowledge:{...Ch},native:{artifact_root:er(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Fc,snapshot:{...we,include:[...we.include],exclude:[...we.exclude]}}}}var qc,Bi,$a,Oa,Sh,Eh,Fc,ja,Ch,$b,Ph,Ob,Hb,Db,we,Tt=E(()=>{"use strict";qc=ri(jr(),1),Bi=64*1024,$a=1024,Oa=64,Sh=1024,Eh=64,Fc=5,ja={learning:!0,retrieval:!0},Ch={provider:"local"},$b=12e4,Ph=6e5,Ob=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".devin/skills/**",".dsh/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],Hb=["**/.idea/**","**/.vscode/**",".codex/skills/**","**/node_modules/**","**/.next/**","**/.nuxt/**","**/.output/**","**/.svelte-kit/**","**/.vite/**","**/.parcel-cache/**","**/.turbo/**","**/.nx/cache/**","**/dist/**","**/build/**","**/out/**","**/coverage/**","**/.nyc_output/**","**/target/**","**/.gradle/**","**/.cxx/**","**/.externalNativeBuild/**","**/captures/**","**/__pycache__/**","**/.pytest_cache/**","**/.mypy_cache/**","**/.ruff_cache/**","**/.tox/**","**/.nox/**","**/.venv/**","**/venv/**","**/obj/**","**/CMakeFiles/**","**/cmake-build-*/**","**/.cache/**","**/tmp/**","**/temp/**","**/logs/**","**/*.tsbuildinfo","**/*.log","**/.DS_Store","**/Thumbs.db"],Db=[...Ob,...Hb].sort((e,t)=>e.localeCompare(t,"en")),we={include:["**/*"],exclude:[...Db],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});import{constants as Ba,promises as tr}from"fs";function Wc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function _h(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function qi(e){return{dev:e.dev,ino:e.ino,birthtime:Wc(e)}}function La(e,t){let r=qi(e),i=qi(t);return Me(r,i)?O(r,i):O(r,i)&&Wc(e)===Wc(t)&&_h(e)===_h(t)&&e.size===t.size}async function rr(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 tr.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new De("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new De("too-large",`${i} exceeds ${t} bytes`);let o=await tr.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:qi(a)});let s=process.platform==="win32"?Ba.O_RDONLY:Ba.O_RDONLY|Ba.O_NOFOLLOW|Ba.O_NONBLOCK,c;try{c=await tr.open(e,s)}catch(l){throw l.code==="ELOOP"?new De("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,d]=await Promise.all([c.stat({bigint:n}),tr.lstat(e,{bigint:n}),tr.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||d!==o||!La(a,l)||!La(a,f))throw new De("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:qi(l)}),await r.hooks?.afterOpen?.();let u=[],p=0,g=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-p,{bytesRead:b}=await c.read(g,0,Math.min(g.length,y),null);if(b===0)break;if(p+=b,p>t)throw new De("too-large",`${i} exceeds ${t} bytes`);u.push(Buffer.from(g.subarray(0,b)))}await r.hooks?.beforeFinalCheck?.();let[h,m,v]=await Promise.all([c.stat({bigint:n}),tr.lstat(e,{bigint:n}),tr.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||v!==o||!La(a,h)||!La(a,m))throw new De("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:v,identity:qi(h)}),{bytes:Buffer.concat(u,p),stat:h,realPath:v}}finally{await c.close()}}var De,Fi=E(()=>{"use strict";ai();De=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as qa}from"fs";import jt from"path";function Zb(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function zc(e,t){let r=jt.relative(e,t);return r===""||!jt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${jt.sep}`)}async function Ih(e,t){let r=jt.resolve(e),i=await qa.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return qa.realpath(r)}async function Th(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=jt.join(n,r[a]);let o;try{o=await qa.lstat(n)}catch(f){if(Zb(f))return{exists:!1,kind:"missing"};throw f}let s=jt.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 qa.realpath(n);if(!zc(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 $r(e,t,r){let i=Ha(t,r.label),n=jt.resolve(e),a=await Ih(n,r.label),o=i.split("/"),s=jt.resolve(n,...o);if(!zc(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Th(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function $t(e,t,r,i){let n=await $r(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 Ih(n.projectRoot,i.label);return rr(n.target,r,{...i,verify:async(o,s)=>{if(!zc(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Th(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var ir=E(()=>{"use strict";Fi();Tt()});import{createHash as ek}from"crypto";function tk(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Fa(e,t={}){return(await Va(e,t)).document}async function rk(e){try{return(await $t(e,Vi,Bi,{label:Vi})).bytes}catch(t){if(tk(t))return null;throw t}}function ik(e){return e?{exists:!0,sha256:ek("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Va(e,t={}){let r=await rk(e);return{document:r?Li(r.toString("utf8"),t):null,identity:ik(r)}}async function Jc(e){return(await Fa(e))?.config??null}var Vi,Or=E(()=>{"use strict";Tt();ir();Vi=".comet/config.yaml"});var Hr=E(()=>{"use strict";ai()});var jA,Gc=E(()=>{"use strict";Hr();Or();ir();jA=16*1024});var Yc=E(()=>{"use strict";Hr();Tt();Or();ir();Gc()});import{existsSync as $h,promises as nr}from"fs";import T from"path";import ck from"os";async function Xc(e){try{return await nr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function uk(e){try{let t=await nr.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Br(e,t){let r=T.relative(e,t);return r===""||!T.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${T.sep}`)}async function Dr(e){let t=[],r=e;for(;!await Xc(r);){let n=T.dirname(r);if(n===r)break;t.push(T.basename(r)),r=n}let i=await nr.realpath(r);return T.resolve(i,...t.reverse())}async function Qc(e){try{return(await nr.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Wa(e){let t=T.resolve(e);try{(await nr.stat(t)).isDirectory()||(t=T.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=T.resolve(ck.homedir());for(;;){if(!(t===i&&r!==i)){let o=T.join(t,...Ma.split("/")),s=t===r||await uk(o);if(await Xc(o)&&s)return t}if(await Xc(T.join(t,".git")))return t;let a=T.dirname(t);if(a===t)return r;t=a}}function za(e){return er(e)}async function dk(e,t){let r=za(t),i=T.resolve(e,...r.split("/")),n=await nr.realpath(e),a=await Dr(i);if(!Br(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function lt(e,t){let r=za(t),i=await dk(e,r),n=T.join(i,"comet");if(await Qc(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Dr(i),Dr(n)]);if(!Br(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=T.resolve(e),c=T.join(s,".comet","runtime","native");if(await Qc(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([nr.realpath(s),Dr(c)]);if(!Br(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:T.join(e,...Ma.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:T.join(n,"specs"),changesDir:T.join(n,"changes"),archiveDir:T.join(n,"archive"),runtimeDir:c,changesRuntimeDir:T.join(c,"changes"),locksDir:T.join(c,"locks"),transactionsDir:T.join(c,"transactions")}}function Oh(e){if(!lk.test(e))throw new Error(`Invalid Native change name: ${e}`)}function xe(e,t){Oh(t);let r=T.join(e.changesRuntimeDir,t);if(!J(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Zc(e,t){Oh(t);let r=T.join(e.changesDir,t,"runtime");if(!J(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Ge(e,t){let r=xe(e,t);if($h(r))return r;let i=Zc(e,t);return $h(i)?i:r}function Ue(e,t){let r=T.resolve(t);if(J(e.runtimeDir,r))return e.runtimeDir;if(J(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function J(e,t){return Br(T.resolve(e),T.resolve(t))}async function V(e,t){let r=T.resolve(e),i=T.resolve(t);if(!Br(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Qc(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Dr(r),Dr(i)]);if(!Br(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var Ma,lk,B=E(()=>{"use strict";Tt();Ma=".comet/config.yaml",lk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});function hk(e="docs",t="en"){return Da(e,t)}async function ye(e){let t=(await Fa(e))?.config??null;return t?.native?t:null}async function Wi(e){let t=await ye(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 Hh(e){let t=await Wa(e.startPath),r=await ye(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Ma} 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?za(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??hk(i??"docs"),a=await lt(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Ce=E(()=>{"use strict";Tt();Or();Yc();q();B()});import{AsyncLocalStorage as pk}from"async_hooks";import{randomUUID as Lh}from"crypto";import{promises as Re}from"fs";import qh from"os";import oe from"path";function vk(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function gk(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return r}function Vh(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 Ga(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Me(r,i)?O(r,i):O(r,i)&&e.size===t.size}function el(e,t){return Ga(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function Ke(e){let t,r;try{let i=await rr(e,Dh,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof De?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${Dh} 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:gk(JSON.parse(t.toString("utf8")),e),identity:Vh(r)}}async function wk(e){return(await Ke(e))?.owner??null}function Mh(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==qh.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=Ek(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function yk(e,t){try{await Re.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await Re.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function tl(e,t){let r=await Ke(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!el(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Re.mkdir(t,{recursive:!0});let i=oe.join(t,`${oe.basename(e.file)}.${e.owner.id}.${Lh()}.removed`);try{await Re.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Ke(i);if(!n||n.owner.id!==e.owner.id||!Ga(n.identity,e.identity))throw await yk(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Re.rm(i,{force:!0}),"removed"}function Wh(e){return{id:Lh(),pid:process.pid,hostname:qh.hostname(),createdAt:new Date().toISOString(),operation:e}}async function zh(e,t){let r;try{r=await Re.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await wk(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)+`
|
|
146
|
+
`,"utf8"),await r.sync(),i=Vh(await r.stat({bigint:!0}))}finally{await r.close()}let n=await Ke(e);if(!i||!n||n.owner.id!==t.id||!Ga(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function Nk(e,t){let r=await V(e.runtimeDir,e.locksDir);await Re.mkdir(r,{recursive:!0});let i=await V(e.runtimeDir,oe.join(r,Fh));await Re.mkdir(i,{recursive:!0});let n=Wh(t),a=oe.join(i,`.${n.id}.tmp`),o=oe.join(i,`${n.id}.claim`);try{let s=await zh(a,n);await Re.rename(a,o);let c=await Ke(o);if(!c||!Ga(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await Re.rm(a,{force:!0})}}async function bk(e){let t=oe.dirname(e.file),r=!1,i=oe.basename(e.file);for(let n of await Re.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=oe.join(t,n.name);if(oe.resolve(a)!==oe.resolve(e.file))try{let o=await Ke(a),s=Mh(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await tl(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function Jh(e){let t=await Ke(e.file);if(t){if(t.owner.id!==e.owner.id||!el(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await tl(t,oe.dirname(e.file))}}async function kk(e,t){let r=Date.now()+mk;for(;;){let i=await Nk(e,t);if(!await bk(i))return i;if(await Jh(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function Sk(e){let t=Ja.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return Ja.set(e,n),await t,()=>{r(),Ja.get(e)===n&&Ja.delete(e)}}async function Gh(e,t,r){let i=oe.resolve(e.locksDir),n=Bh.getStore();if(n?.has(i))return r();let a=await Sk(i);try{let o=await kk(e,t),s=new Map(n??[]);return s.set(i,o),await Bh.run(s,async()=>{try{return await r()}finally{await Jh(o)}})}finally{a()}}async function Ua(e,t,r){return Gh(e,`acquire ${t}`,async()=>{let i=await V(e.runtimeDir,e.locksDir);await Re.mkdir(i,{recursive:!0});let n=await V(e.runtimeDir,oe.join(i,vk(t))),a=Wh(r),o=await zh(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function Ka(e){await Ke(e.file)&&await Gh({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${oe.basename(e.file)}`,async()=>{let t=await Ke(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!el(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=oe.join(e.locksDir,Fh);await tl(t,r)})}function Ek(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function Uh(e){return Mh(await Ke(e))}var Dh,Fh,mk,Bh,Ja,zi=E(()=>{"use strict";Fi();B();We();Dh=16*1024,Fh=".coordinator",mk=5e3,Bh=new pk,Ja=new Map});import{createHash as Pk}from"crypto";function Be(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function xk(e,t){t.has(e)&&Be("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||Be("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&Be("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Be("symbol properties are not supported"),`[${e.map(i=>rl(i,t)).join(",")}]`}finally{t.delete(e)}}function Ck(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&Be("only plain objects are supported"),t.has(e)&&Be("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Be("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&Be("accessor properties are not supported"),`${JSON.stringify(o)}:${rl(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function rl(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||Be("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?xk(e,t):Ck(e,t);case"bigint":case"function":case"symbol":case"undefined":return Be(`${typeof e} values are not supported`)}return Be("unsupported value type")}function il(e){return rl(e,new Set)}function H(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return Pk("sha256").update(`${e}
|
|
147
147
|
${il(t)}`).digest("hex")}var se=E(()=>{"use strict"});function Xh(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function Kh(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function Yh(e){return e.includes("-->")||e.includes("--!>")}function*Ya(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
148
148
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
149
149
|
`,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=Kh(l,t);else if(r)Yh(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let d=Kh(l,null);if(d!==null)t=d;else{let u=l.trimStart();if(u.startsWith("<!--")&&!Yh(u))r=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(u);p&&n.has(p[1].toLowerCase())&&!u.startsWith("</")&&!u.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(u)&&(i=p[1])}}}if(c===-1)break;o=c+1}}function Ji(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function Qh(e,t,r,i=[],n="content-hash"){let a=Ji(r),o=t.replaceAll("\\","/").trim(),s=i.map(Ji);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-${H(Rk,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Zh(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 Ak(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of Ya(e)){n=s+1;let c=o?Xh(a):null;c?.level===1&&(Bc(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 nl(e,t="brief.md",r=Xa.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=Ak(e);if(n===null)return[];let a=null;for(let{line:l,body:f,index:d}of Ya(e)){if(d<n.start||d>=n.end)continue;let u=f?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(u===null)continue;let p=u[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:f,index:d}of Ya(e)){if(d<n.start||d>=n.end)continue;let u=f?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;u&&u[1].length===a?(c(),s=[u[2]]):s!==null&&s.push(l)}return c(),Zh(o.map(l=>Qh("brief-example",t,l.join(`
|
|
150
150
|
`),[],i)),"Brief",i)}function al(e,t="spec.md",r=Xa.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(Qh("spec-scenario",t,[o.title,...o.body].join(`
|
|
151
|
-
`),o.context,i)),o=null}};for(let{line:c,body:l}of Ya(e)){let f=l?Xh(c):null,d=f?/^Scenario\s*:\s*(.*)$/iu.exec(f.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=f.level;)a.pop();let u=Ji(d[1]);if(u.length===0)throw new Error("Scenario title must not be empty");o={level:f.level,title:u,body:[],context:a.map(p=>p.text)}}else if(f){for(o!==null&&f.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f)}else o!==null&&l&&o.body.push(c)}return s(),Zh(n,"Specification",i)}var Rk,h_,Xa,Qa=E(()=>{"use strict";Zt();se();Rk="comet.native.acceptance.v1",h_=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Xa=Object.freeze({maxCriteria:1024})});import ep from"node:path";function tp(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||ep.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||ep.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function Ik(e,t){return e.localeCompare(t,"en")}function Za(e){let t=tp(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>Ik(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=nl(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=tp(a.source,`Native spec source for ${a.capability}`);i.push(...al(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=Ji(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function rp(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(!_k.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function ip(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var _k,eo=E(()=>{"use strict";Qa();_k=/^A[1-9]\d*$/u});function to(){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 ar,Gi,np,Ui=E(()=>{"use strict";ar="comet.native.v4",Gi="comet.native.local-execution.v4",np=["multi-session","single-session"]});var ll={};Pu(ll,{NativePortableStateVersionConflictError:()=>Ki,appendNativePortableHistory:()=>Ot,compareAndSwapNativePortableState:()=>Ht,createNativePortableState:()=>sp,parseNativePortableState:()=>ne,readNativePortableState:()=>te,writeNativePortableState:()=>Yi});import{promises as Tk}from"node:fs";function ce(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function le(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 K(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 sl(e,t){return e===null?null:K(e,t)}function ap(e,t){let r=K(e,t);if(!Hk.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Lr(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function L(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 Bk(e,t){return e===null?null:L(e,t,Number.MIN_SAFE_INTEGER)}function W(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Ke(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function no(e,t){return Ke(e,t,(r,i)=>K(r,`${t}[${i}]`))}function or(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function qr(e,t){let r=K(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function cl(e,t,r=!1){let i=K(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 Ae(e,t){let r=ce(e,t);return le(r,new Set(["text","truncated"]),t),{text:K(r.text,`${t}.text`,{empty:!0}),truncated:Lr(r.truncated,`${t}.truncated`)}}function Lk(e,t){let r=`Native spec_changes[${t}]`,i=ce(e,r);le(i,new Set(["capability","operation","source"]),r);let n=K(i.capability,`${r}.capability`);if(!$k.test(n))throw new Error(`${r}.capability is invalid`);let a=W(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:cl(i.source,`${r}.source`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);return{capability:n,operation:a,source:o}}function qk(e){let t="Native workspace",r=ce(e,t);le(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=W(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=sl(r.change_branch,`${t}.change_branch`),a=sl(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:W(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 Fk(e){let t="Native loop",r=ce(e,t);le(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=no(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);or(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:W(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:W(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:L(r.goal_cycle,`${t}.goal_cycle`,1),iteration:L(r.iteration,`${t}.iteration`),attempt:L(r.attempt,`${t}.attempt`),retry_epoch:L(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:L(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:L(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:L(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:sl(r.next_action,`${t}.next_action`)}}function Vk(e,t){let r=`Native acceptance[${t}]`,i=ce(e,r);le(i,new Set(["id","source","text","result","reason"]),r);let n=K(i.id,`${r}.id`);if(!Ok.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:cl(i.source,`${r}.source`),text:K(i.text,`${r}.text`),result:W(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Ae(i.reason,`${r}.reason`)}}function Mk(e,t){let r=`Native builder_handoff.checks[${t}]`,i=ce(e,r);return le(i,new Set(["name","result","note"]),r),{name:Ae(i.name,`${r}.name`),result:W(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Ae(i.note,`${r}.note`)}}function Wk(e){let t="Native builder_handoff",r=ce(e,t);le(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=no(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);or(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:ce(r.review,`${t}.review`);return n&&le(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:K(r.candidate_id,`${t}.candidate_id`),identity_provider:K(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:K(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:L(r.iteration,`${t}.iteration`,1),summary:Ae(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Ke(r.checks,`${t}.checks`,Mk),checks_truncated:Lr(r.checks_truncated,`${t}.checks_truncated`),known_limits:Ke(r.known_limits,`${t}.known_limits`,(a,o)=>Ae(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Lr(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:W(n.status,["passed"],`${t}.review.status`),summary:Ae(n.summary,`${t}.review.summary`),reviewer_execution_ref:K(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:qr(r.submitted_at,`${t}.submitted_at`)}}function zk(e,t){let r=`Native blockers[${t}]`,i=ce(e,r);le(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=no(i.acceptance_ids,`${r}.acceptance_ids`);return or(n,`${r}.acceptance_ids`),{owner:W(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Ae(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:W(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function Jk(e,t){let r=`Native verification.checks[${t}]`,i=ce(e,r);return le(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:K(i.id,`${r}.id`),name:Ae(i.name,`${r}.name`),argv_display:Ke(i.argv_display,`${r}.argv_display`,(n,a)=>Ae(n,`${r}.argv_display[${a}]`)),argv_truncated:Lr(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:cl(i.cwd_ref,`${r}.cwd_ref`,!0),status:W(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:Bk(i.exit_code,`${r}.exit_code`),duration_ms:L(i.duration_ms,`${r}.duration_ms`)}}function Gk(e){let t="Native verification",r=ce(e,t);le(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Ke(r.checks,`${t}.checks`,Jk);or(i.map(a=>a.id),`${t}.checks IDs`);let n=K(r.identity_provider,`${t}.identity_provider`);return{candidate_id:K(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:K(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:L(r.iteration,`${t}.iteration`,1),attempt:L(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":W(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:W(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:Ae(r.summary,`${t}.summary`),risks:Ke(r.risks,`${t}.risks`,(a,o)=>Ae(a,`${t}.risks[${o}]`)),risks_truncated:Lr(r.risks_truncated,`${t}.risks_truncated`),completed_at:qr(r.completed_at,`${t}.completed_at`)}}function op(e,t){let r=`Native history[${t}]`,i=ce(e,r);le(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=no(i.unresolved_ids,`${r}.unresolved_ids`);return or(n,`${r}.unresolved_ids`),{goal_cycle:L(i.goal_cycle,`${r}.goal_cycle`,1),iteration:L(i.iteration,`${r}.iteration`),attempt:L(i.attempt,`${r}.attempt`),outcome:W(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Ae(i.summary,`${r}.summary`),completed_at:qr(i.completed_at,`${r}.completed_at`)}}function Uk(e){let t="Native history_overflow.outcome_counts",r=ce(e,t),i=["pass","fail","blocked","execution-error","recovery"];return le(r,new Set(i),t),{pass:L(r.pass,`${t}.pass`),fail:L(r.fail,`${t}.fail`),blocked:L(r.blocked,`${t}.blocked`),"execution-error":L(r["execution-error"],`${t}.execution-error`),recovery:L(r.recovery,`${t}.recovery`)}}function Kk(e){let t="Native history_overflow",r=ce(e,t);le(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=L(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:qr(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:qr(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=Uk(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 Yk(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 Xk(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 ne(e){let t=ce(e,"Native portable state");if(le(t,Dk,"Native portable state"),t.schema!==ar)throw new Error(`Native portable state schema must be ${ar}`);let r=K(t.name,"Native state name");if(!jk.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=Ke(t.spec_changes,"Native spec_changes",Lk);or(i.map(s=>s.capability),"Native spec change capabilities");let n=Ke(t.acceptance,"Native acceptance",Vk);or(n.map(s=>s.id),"Native acceptance IDs");let a=Ke(t.history,"Native history",op);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:ar,name:r,language:W(t.language,["en","zh-CN"],"Native state language"),phase:W(t.phase,["shape","build","verify","archive"],"Native state phase"),status:W(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:L(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:ap(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:ap(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:W(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:qk(t.workspace),loop:Fk(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:Wk(t.builder_handoff),blockers:Ke(t.blockers,"Native blockers",zk),verification:t.verification===null?null:Gk(t.verification),history:a,history_overflow:Kk(t.history_overflow),verification_result:W(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:W(t.verification_report,["verification.md"],"Native verification_report"),archived:Lr(t.archived,"Native archived"),created_at:qr(t.created_at,"Native created_at")};return Yk(o),Xk(o),o}function sp(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return ne({schema:ar,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:to(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function Ot(e,t){let r=ne(e),i=op(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 ne({...r,history:n,history_overflow:a})}function Qk(e,t){let r=(0,io.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 te(e){let t=await Tk.readFile(e,"utf8");return ne(Qk(t,"Native portable state"))}async function Yi(e,t,r={}){let i=ne(t);await de(e,(0,io.stringify)(i),r)}async function Zk(e,t){let r=ro.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);ro.set(e,a),await r;try{return await t()}finally{i(),ro.get(e)===a&&ro.delete(e)}}async function Ht(e){return Zk(e.file,async()=>{let t=L(e.expectedStateVersion,"Native expected state version",1),r=ne(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await te(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new Ki(t,i.state_version);return await Yi(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await te(e.file);if(n.state_version!==t)throw new Ki(t,n.state_version)}}),r})}var io,jk,$k,Ok,Hk,Dk,Ki,ro,Ye=E(()=>{"use strict";io=ri(jr(),1);q();Ui();jk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,$k=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ok=/^A[1-9][0-9]*$/u,Hk=/^[a-f0-9]{64}$/u,Dk=new Set(["schema","name","language","phase","status","state_version","brief","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),Ki=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"};ro=new Map});function eS(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function lt(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(eS(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 Xi=E(()=>{"use strict"});var ut,Xe,Qe,ao=E(()=>{"use strict";ut="comet.native.v3",Xe="comet.native.v2",Qe="comet.native.v1"});import tS from"node:path";function sS(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function cS(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 lS(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 uS(e){return e.schema===Qe?Qi(e):e.schema===Xe?Zi(e):en(e)}function dS(e){return tS.posix.normalize(e.replaceAll("\\","/"))}function fS(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:dS(t.source)})}function hS(e){return e==="shape"?"shape":"build"}function pS(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function mS(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 cp(e){let t=uS(e.state);rp(e.acceptance);let r=hS(t.phase),i=r==="shape"?0:1,n=cS(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 ne({schema:ar,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:fS(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:pS(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:lt(mS(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:to(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function ul(e){let t=sS(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!rS.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==oo)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!nS.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!iS.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!oS.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!aS.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:oo,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:lS(t.createdAt,"Native portable migration transaction createdAt")}}function lp(e){switch(ul(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 oo,rS,iS,nS,aS,oS,dl=E(()=>{"use strict";Y();eo();Ye();Xi();Ui();ao();oo="comet.native.portable-migration.v1",rS=new Set(["schema","id","change","fromSchema","status","createdAt"]),iS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,nS=/^[a-z0-9][a-z0-9-]{7,127}$/u,aS=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),oS=new Set([Qe,Xe,ut])});import fl from"node:path";function fp(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function hp(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${r} fields are invalid`)}function SS(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=fp(e,r);if(hp(i,kS,r),typeof i.capability!="string"||!dp.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation;if(n==="remove"){if(i.source!==null||i.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);return{capability:i.capability,operation:n,source:i.source,content:i.content}}function ES(e){let t=fp(e,"Native portable Archive transaction");if(hp(t,bS,"Native portable Archive transaction"),t.schema!==so)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!wS.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!dp.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"||!yS.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"||!NS.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(SS);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:so,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 co(e){let t=vS.exec(e);if(t)return{kind:"archive",change:t[1]};let r=gS.exec(e);return r?{kind:"migration",change:r[1]}:null}function sr(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=co(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return fl.join(e.transactionsDir,r)}async function hl(e,t){let r=co(t);if(!r)return null;let i=await F({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=fl.join(e.transactionsDir,t);if(r.kind==="archive"){let s=ES(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=ul(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 Dt(e,t){let r=sr(e,t);try{return await hl(e,fl.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function pp(e){return e.kind==="archive"||e.journal.status!=="committed"}var so,up,vS,gS,wS,yS,NS,bS,kS,dp,Fr=E(()=>{"use strict";Ee();dl();so="comet.native.archive-transaction.v4",up="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",vS=new RegExp(`^portable-archive-(${up})\\.json$`,"u"),gS=new RegExp(`^portable-migration-(${up})\\.json$`,"u"),wS=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,yS=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,NS=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),bS=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),kS=new Set(["capability","operation","source","content"]),dp=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as PS}from"node:crypto";import{constants as lo,promises as Be}from"node:fs";import Le from"node:path";function fo(e,t){let r=Le.relative(e,t);return r===""||!Le.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Le.sep}`)}function xS(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function CS(e,t){return O({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function RS(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function uo(e,t){return O({...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 pl(e,t){let r=await Be.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Be.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function AS(e,t,r){let i=Le.resolve(e),n=Le.resolve(t);if(!fo(i,n))throw new Error(`${r} is outside its managed root`);let a=[await pl(i,r)],o=i;for(let s of Le.relative(i,n).split(Le.sep).filter(Boolean)){await cr(a,r),o=Le.join(o,s);let c=await pl(o,r);if(!fo(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await cr(a,r),a}async function cr(e,t){for(let r of e){let i=await Be.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!CS(r,i)||await Be.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function _S(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Vr(e){let t=xS(e.maxBytes),r=Le.resolve(e.file),i=await AS(e.root,Le.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(f=>pl(Le.resolve(f),e.label)));await e.hooks?.afterParentChainCaptured?.(),await cr(i,e.label);let a=await Be.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=RS(a),s=await Be.realpath(r);if(!fo(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(f=>fo(f.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?lo.O_RDONLY:lo.O_RDONLY|lo.O_NOFOLLOW|lo.O_NONBLOCK,l=await Be.open(r,c);try{let f=await l.stat();await e.hooks?.afterOpen?.();let[d,u]=await Promise.all([Be.lstat(r),Be.realpath(r)]);if(await cr(i,e.label),await cr(n,e.label),!f.isFile()||!d.isFile()||d.isSymbolicLink()||u!==s||!uo(o,f)||!uo(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await _S(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[g,h,m]=await Promise.all([l.stat(),Be.lstat(r),Be.realpath(r)]);if(await cr(i,e.label),await cr(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!uo(o,g)||!uo(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:PS("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}var Ze=E(()=>{"use strict";q();Me()});import dt from"path";import{TextDecoder as TS}from"util";function po(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function mo(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 wp(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function ml(e,t){if(typeof e!="string"||e.length===0||dt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function ho(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function mp(e,t){if(ml(e,t),e.includes("\\")||e!==dt.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 LS(e,t){let r=po(e,`transaction operations[${t}]`);if(mo(r,$S,`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`);ml(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&ml(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 yp(e){let t=po(e,"Native Archive transaction journal");if(mo(t,OS,"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"||!gp.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(!wp(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(ho(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=po(s,`Archive transaction operations[${c}]`);if(mo(l,HS,`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`);mp(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&mp(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&ho(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(ho(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`);ho(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 qS(e){let t=po(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return yp(t);if(mo(t,jS,"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"||!gp.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!dt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!dt.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(!wp(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(LS),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 FS(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return dt.join(e.transactionsDir,t)}function Np(e,t){let r=FS(e,t);return{directory:r,journal:dt.join(r,"transaction.json"),events:dt.join(r,"events.jsonl"),staged:dt.join(r,"staged"),backups:dt.join(r,"backups")}}async function gl(e,t){let r=Np(e,t);return await Promise.all(Object.values(r).map(i=>V(e.runtimeDir,i))),r}async function wl(e,t,r={}){let i=await gl(e,t),n=await Vr({root:e.runtimeDir,file:i.journal,maxBytes:DS,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(BS.decode(n.bytes)),o=qS(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var jS,$S,OS,HS,gp,DS,Y_,X_,Q_,BS,vo=E(()=>{"use strict";q();B();Ze();jS=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),$S=new Set(["id","type","source","target","staged","backup"]),OS=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),HS=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),gp=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),DS=256*1024,Y_=1024*1024,X_=16*1024,Q_=64*1024*1024,BS=new TS("utf-8",{fatal:!0})});import{promises as VS}from"fs";import MS from"path";async function WS(e,t,r){let i;try{i=await VS.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 wl(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(co(n.name))try{let a=await hl(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(pp(a))return!0}catch{return!0}return!1}async function zS(e,t){let r=Date.now()+5e3,i=MS.join(e.locksDir,"root-move.lock");for(;;)try{return await Ua(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Uh(i);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function re(e,t,r,i){let n=await zS(e,t);try{if(await Wi(e.projectRoot),await WS(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await Ka(n)}}var me=E(()=>{"use strict";Ce();zi();Fr();vo()});var bp=E(()=>{"use strict"});import{createHash as JS}from"crypto";function _e(e){return JS("sha256").update(e).digest("hex")}var et=E(()=>{"use strict"});var yI,NI,bI,kI,SI,EI,PI,tn=E(()=>{"use strict";q();Ce();et();Me();B();Ze();si();yI={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},NI=8*1024*1024,bI=64*1024,kI=64*1024,SI={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},EI={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024},PI=(1n<<256n)-1n});var rn=E(()=>{"use strict"});var go=E(()=>{"use strict"});var kp=E(()=>{"use strict"});var yl=E(()=>{"use strict";go()});var Sp=E(()=>{"use strict";go();yl()});var ZS,Ep=E(()=>{"use strict";ZS=ri(jr(),1);Hr();Tt();ir()});var FI,Pp=E(()=>{"use strict";Hr();ir();FI=4*1024*1024});function tE(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function xp(e,t){return(...r)=>{let i=eE;if(i===null)return t(...r);let n=tE(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}var eE,Cp=E(()=>{"use strict";eE=null});var JI,Rp=E(()=>{"use strict";Cp();Or();JI=xp("hookWritePolicy",async e=>(await Jc(e))?.hook??{allow_paths:[]})});var Ap=E(()=>{"use strict";go();Hr();kp();Sp();Tt();Ep();ir();Or();Yc();Pp();Rp();Gc();yl()});var _p=E(()=>{"use strict";Ap();ai()});var MT,Ip=E(()=>{"use strict";_p();MT=256*1024});var Tp=E(()=>{"use strict";Ip();rn()});var rj,nn=E(()=>{"use strict";rn();Tp();q();Me();rj={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024}});var Nl=E(()=>{"use strict";rn();me();B();nn()});import Mr from"node:path";function nE(e,t){let r=Mr.relative(e,t);return Mr.isAbsolute(r)||r===".."||r.startsWith(`..${Mr.sep}`)?null:r.replaceAll("\\","/")||"."}function Op(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Hp(e,t){if(e.length===0||Op(e)||e.includes("\\")||Mr.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=Mr.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function aE(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 bl(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Op(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function oE(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(bl(e.changeBranch,"Native workspace change branch"),bl(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 sE(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"||!$p.test(t.baseCommit)||typeof t.targetCommit!="string"||!$p.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");bl(t.targetBranch,"Native workspace Git target branch")}function cE(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"||!an.test(String(t.projectRootId))||!an.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");aE(t.capturedAt),Hp(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&&!an.test(String(t.projectRootPathId))||a&&!an.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!an.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&sE(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(oE(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 lE(e,t){return Mr.join(Je(e,t),"workspace.json")}function uE(e,t){let r=lE(e,t),i=Ge(e,r),n=nE(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:Hp(n,"Native workspace file ref")}}async function dE(e,t){try{let r=uE(e,t),i=await F({root:r.root,ref:r.ref,maxBytes:iE});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function on(e,t){let r=await dE(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(cE(r),r)}var an,$p,iE,gj,Wr=E(()=>{"use strict";ke();q();Ee();me();B();an=/^[a-f0-9]{64}$/u,$p=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,iE=16*1024,gj=process.platform});import zr from"path";function ln(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Fp(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 xl(e){if(!qp.test(e))throw new Error(`Invalid Native change name: ${e}`)}function bE(e){if(!qp.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Vp(e,t){if(e.length===0||zr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function kE(e,t){let r=ln(e,`spec_changes[${t}]`);if(Fp(r,vE,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(bE(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&Vp(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!Sl.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!Sl.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function SE(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function Cl(e,t){if(Fp(e,t,lr),typeof e.name!="string")throw new Error("Native change name is required");if(xl(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!gE.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!wE.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(kE),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!yE.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&Vp(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!SE(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function Qi(e){let t=ln(e,lr);if(t.schema!==Qe)throw new Error(`Expected ${Qe}`);return{schema:Qe,...Cl(t,pE)}}function cn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function kl(e,t,r){if(e===null)return null;let i=typeof e=="string"?NE.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function EE(e){if(e==null)return null;if(typeof e!="string"||!Sl.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function PE(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function Zi(e){let t=ln(e,lr);if(t.schema!==Xe)throw new Error(`Expected ${Xe}`);if(cn(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Xe} minimum_runtime_version must be 2`);return{schema:Xe,minimum_runtime_version:2,revision:cn(t.revision,"Native v2 revision"),...Cl(t,Lp)}}function en(e){let t=ln(e,lr);if(t.schema!==ut){if(t.schema===Qe||t.schema===Xe){let o=t.schema===Qe?Qi(t):Zi(t);throw new El(o.name,o.schema)}throw new Lt(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=cn(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Lt(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=cn(t.revision,"Native revision"),n=Cl(t,mE),a=EE(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ut,minimum_runtime_version:3,revision:i,verification_protocol:PE(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:kl(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:kl(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:kl(t.partial_allowance,"Native partial_allowance","allowances")}}function xE(e){let t=ln(e,lr);if(t.schema===Qe){let n=Qi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ut}`}}if(t.schema===Xe){let n=Zi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ut}`}}if(t.schema!==ut){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Lt(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=cn(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Lt(t.schema,r).message};let i=en(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function Ne(e,t){xl(t);let r=zr.join(e.changesDir,t);if(!J(e.changesDir,r))throw new Error("Native change path escaped");return r}async function CE(e,t=zr.dirname(e)){let r=zr.relative(t,e).split(zr.sep).join("/"),i=await F({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Pl.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 No(e,t){let r=zr.join(Ne(e,t),lr);await V(e.nativeRoot,r);let i=xE(await CE(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}var Pl,Bp,pE,Lp,mE,vE,gE,wE,yE,lr,Sl,qp,NE,El,Lt,wo,sn,yo,Vj,Y=E(()=>{"use strict";Pl=ri(jr(),1);ke();Ee();q();Zt();Ce();me();B();Ze();bp();tn();Nl();Wr();ao();Bp=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],pE=new Set(Bp),Lp=new Set([...Bp,"minimum_runtime_version","revision"]),mE=new Set([...Lp,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),vE=new Set(["capability","operation","source","base_hash"]),gE=new Set(["shape","build","verify","archive"]),wE=new Set(["implicit","confirmed"]),yE=new Set(["pending","pass","fail"]),lr="comet-state.yaml",Sl=/^[a-f0-9]{64}$/u,qp=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,NE=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,El=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Lt=class extends Error{constructor(r,i){super(r!==ut||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},wo=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"},sn=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"},yo=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"},Vj=Ta("en")});import{execFileSync as IE}from"node:child_process";function Wp(e,t){try{return IE("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:TE,maxBuffer:jE,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Rl(e,t,i)}}function C(e,t){return Wp(e,t).trim()}function Jr(e){let t=Wp(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let r=t.split("\0").filter(Boolean),i=[];for(let n=0;n<r.length;n+=1){let a=r[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(i.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=r[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");i.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(i)].sort()}function zp(e,t){try{let i=C(e,["config","--get",`branch.${t}.remote`]);if(i&&i!==".")return i}catch{}let r=C(e,["remote"]).split(/\r?\n/u).map(i=>i.trim()).filter(Boolean);if(r.includes("origin"))return"origin";if(r.length===1)return r[0];throw new Error(r.length===0?"Native workspace finish requires a configured Git remote":`Native workspace finish requires an unambiguous Git remote: ${r.join(", ")}`)}var TE,jE,Rl,Gr=E(()=>{"use strict";TE=3e4,jE=8*1024*1024,Rl=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});import{createHash as $E}from"node:crypto";import{lstatSync as OE,readFileSync as Jp,promises as HE}from"node:fs";import Al from"node:path";function Ur(e){try{if(C(e,["ls-files","--",bo]))return!1;let t=Al.join(e,bo),r=OE(t);return!r.isFile()||r.isSymbolicLink()?!1:JSON.parse(Jp(DE(e),"utf8")).hash===BE(Jp(t))}catch{return!1}}function Kr(e,t=[]){return Jr(e).every(r=>t.some(i=>r===i||r.startsWith(`${i}/`))||r===bo&&Ur(e))}async function dn(e){Ur(e)&&await HE.unlink(Al.join(e,bo))}var bo,DE,BE,ko=E(()=>{"use strict";Gr();q();bo=".comet/config.yaml",DE=e=>Al.join(e,".comet","runtime","native","workspace-config.json"),BE=e=>$E("sha256").update(e).digest("hex")});import{existsSync as LE}from"node:fs";import fn from"node:path";function Gp(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function FE(e){let t=(Gp(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function VE(e,t,r){let n=fn.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Gp(t,"PATH")??"").split(fn.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=fn.win32.extname(e)?[e]:FE(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?fn.join(s,c):fn.resolve(r,c)))}function Up(e,t,r){return VE(e,t,r).find(i=>LE(i))??e}function Kp(e){if(e.some(t=>qE.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var qE,l$,So=E(()=>{"use strict";qE=/[&|<>()^%"!\r\n]/u,l$=["$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("; ")});var _l=E(()=>{"use strict"});var ur=E(()=>{"use strict"});var Il=E(()=>{"use strict";So();_l();ur()});var pn,mn=E(()=>{"use strict";pn="skill-coordinated"});var Eo=E(()=>{"use strict";mn()});import Po from"node:path";function Yp(...e){if(e.length===0)return Po.resolve();if(Po.win32.isAbsolute(e[0])){let t=Po.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return Po.resolve(...e)}var Xp=E(()=>{"use strict"});import{execFileSync as JE}from"node:child_process";import Qp from"node:path";function dr(e,t,r={}){let i=r.timeoutMs??GE,n=r.maxBufferBytes??UE;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=Qp.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?Up(e,o,a):e,c=Qp.win32.extname(s).toLowerCase(),l=c===".bat"||c===".cmd";process.platform==="win32"&&l&&Kp(t);try{return JE(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(f){let d=typeof f.stderr=="string"?f.stderr.trim():Buffer.isBuffer(f.stderr)?f.stderr.toString("utf8").trim():"";throw new Tl(e,t,d,{cause:f})}}var GE,UE,Tl,xo=E(()=>{"use strict";So();GE=6e4,UE=8*1024*1024,Tl=class extends Error{constructor(r,i,n,a){super(`${r} ${i.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=r;this.args=i;this.stderr=n;this.name="ExternalCommandError"}command;args;stderr}});var Zp=E(()=>{"use strict";xo()});var Co,jl=E(()=>{"use strict";Gr();ke();Ce();ko();zi();B();Co=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation}});import D from"node:path";import{promises as Ro}from"node:fs";function QE(e,t){let r=D.relative(D.resolve(e),D.resolve(t));return r===""||!D.isAbsolute(r)&&!r.startsWith(`..${D.sep}`)}function ZE(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function eP(e,t,r){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(r))throw new Error("Native Supervisor parent and child names are invalid");return Yp(e,".worktrees",`${t}-${r}`)}function im(e,t){return D.join(xe(e,t),"supervisor")}function Ao(e,t){return D.join(im(e,t),"state.json")}function nm(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!==Ol)throw new Error(`Native Supervisor state schema must be ${Ol}`);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(qt(t.integration.targetCommit,"Native Supervisor target commit"),qt(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");qt(n.candidateCommit,"Native Supervisor integration candidate commit"),qt(n.integrationCommit,"Native Supervisor integration check commit")}if(!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&qt(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(qt(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function qe(e,t,r={}){try{let i=await Ro.readFile(Ao(e,t),"utf8"),n=JSON.parse(i);if(nm(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativeChildrenContract:s,nativeChildrenAcceptanceValidation:c}=await Promise.resolve().then(()=>(Io(),um)),{readNativePortableState:l}=await Promise.resolve().then(()=>(Ye(),ll)),f=await l(D.join(o.changesDir,t,"comet-state.yaml")),d=await s({changeDir:D.join(o.changesDir,t),acceptanceIds:f.acceptance.map(({id:u})=>u),validation:c(f)});if(!d)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let u of n.children)d.contract.children.some(({name:p})=>p===u.name)&&(u.acceptanceScope=om(d.contract,u.name),u.contractHash=H("comet.native.supervisor-contract.v1",d.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(()=>(Ye(),ll)),s=await o(D.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 fr(e,t){nm(t),await Ro.mkdir(e.changesRuntimeDir,{recursive:!0}),await U(Ao(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function qt(e,t){if(!XE.test(e))throw new Error(`${t} must be a Git commit`)}function vn(e){return structuredClone(e)}function Hl(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function am(e){qt(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:om(e.contract,i.name),contractHash:H("comet.native.supervisor-contract.v1",e.contract)}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:Ol,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 om(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}async function Dl(e){let t=ZE(e.parent),r=Jt(e.paths.projectRoot,t);if(!r)return null;let i=Jt(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=ge(e.paths.projectRoot).map(o=>D.resolve(o)).find(o=>$(o).currentBranch===t);if(!n)return null;let a=am({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 Hl(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function _o(e){if(!Kr(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=C(e.integration.worktree,["rev-parse","--show-toplevel"]);if(D.resolve(t)!==D.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=C(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 C(e.integration.worktree,["rev-parse","HEAD"])}async function tP(e){let t=Jt(e.paths.projectRoot,e.state.integration.targetBranch);if(!t||t===e.state.integration.targetCommit)return null;let r=e.state;if(_o(r)!==r.integration.headCommit)throw new Error("Native Supervisor integration head changed before target refresh");try{C(r.integration.worktree,["merge","--no-edit",r.integration.targetBranch])}catch(o){throw new Error(`Native Supervisor target drift requires conflict resolution in ${r.integration.worktree}`,{cause:o})}let n=C(r.integration.worktree,["rev-parse","HEAD"]),a=vn(r);return a.integration.headCommit=n,a.finalVerification={status:"pending",summary:null},Hl(a,{kind:"target-refreshed",child:null,runId:null,summary:`Target ${r.integration.targetBranch} was refreshed before delivery`}),a.stateVersion+=1,await fr(e.paths,a),a}function rP(e,t){if(qt(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=vn(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 sm(e){let t=_o(e);if(t===e.integration.headCommit)return e;try{C(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=vn(e);return r.integration.headCommit=t,Hl(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function cm(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=_o(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 rP(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}async function gn(e){let r=await qe(e.paths,e.state.parent)??e.state;if(r.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before delivery; reload status first");if(r.finalVerification.status!=="passed")throw new Error("Native Supervisor delivery requires a passed final verification");if(!r.children.every(({status:h})=>h==="integrated"||h==="archived"))throw new Error("Native Supervisor delivery requires every child to be integrated");let n=ge(e.paths.projectRoot).map(h=>D.resolve(h)).find(h=>$(h).currentBranch===r.integration.targetBranch);if(!n)throw new Error(`Native Supervisor target branch worktree is unavailable: ${r.integration.targetBranch}`);let a=D.resolve(n)===D.resolve(e.paths.projectRoot)?[D.relative(n,D.join(e.paths.changesDir,r.parent)).replaceAll("\\","/"),".comet/current-change.json",...e.archiveOwnedPaths??[]]:[];if(!Kr(n,a))throw new Error(`Native Supervisor target worktree is not clean: ${n}`);let o=C(n,["rev-parse","HEAD"]);if((()=>{try{return C(n,["merge-base","--is-ancestor",r.integration.headCommit,o]),!0}catch{return!1}})()){let h=await tm({paths:e.paths,state:r,targetCommit:o});if(await rm({paths:e.paths,plan:h,targetRoot:n}),r.children.every(({status:v})=>v==="archived"))return await $l(e.paths,r.parent),{state:r,targetRoot:n,targetCommit:o};let m=vn(r);for(let v of m.children)v.status="archived";return m.stateVersion+=1,await fr(e.paths,m),await $l(e.paths,r.parent),{state:m,targetRoot:n,targetCommit:o}}let l=_o(r);if(l!==r.integration.headCommit)throw new Error("Native Supervisor integration head changed after final verification");let f=Jt(e.paths.projectRoot,r.integration.targetBranch),d=(()=>{if(!f)return!1;try{return C(r.integration.worktree,["merge-base","--is-ancestor",f,l]),!0}catch{return!1}})();if(f!==l&&!d&&f!==r.integration.targetCommit&&await tP({paths:e.paths,state:r}))throw new Error("Native Supervisor target changed; parent integration checks must be rerun before delivery");let u=await tm({paths:e.paths,state:r,targetCommit:l});f!==l&&C(n,["merge","--ff-only",r.integration.branch]);let p=C(n,["rev-parse","HEAD"]);if(p!==l)throw new Error("Native Supervisor target did not receive the verified integration head");let g=vn(r);for(let h of g.children)h.status="archived";return await rm({paths:e.paths,plan:u,targetRoot:n}),g.stateVersion+=1,await fr(e.paths,g),await $l(e.paths,r.parent),{state:g,targetRoot:n,targetCommit:p}}function lm(e,t){return D.join(im(e,t),"cleanup.json")}function em(e){let t=ge(e.paths.projectRoot).map(s=>D.resolve(s)),r=D.resolve(process.cwd()),i=[{root:e.state.integration.worktree,branch:e.state.integration.branch},...e.state.children.map(({name:s,projectRoot:c,task:l})=>({root:c??l?.projectRoot??eP($(e.paths.projectRoot).primaryWorktreeRoot??e.paths.projectRoot,e.state.parent,s),branch:`comet/supervisor/${e.state.parent}/${s}`}))].map(s=>({...s,root:D.resolve(s.root)})),n=e.targetCommit,a=[e.state.integration.branch,...e.state.children.map(({name:s})=>`comet/supervisor/${e.state.parent}/${s}`)],o=i.flatMap(s=>{let c=t.find(l=>l===s.root);return c?[{...s,root:c}]:[]});for(let s of o){if(QE(s.root,r))throw new Error(`Native Supervisor cannot clean the current worktree: ${s.root}`);if(!Kr(s.root))throw new Error(`Native Supervisor cleanup requires a clean worktree: ${s.root}`);let c=$(s.root).currentBranch;if(!c)throw new Error(`Native Supervisor worktree is detached: ${s.root}`);if(c!==s.branch)throw new Error(`Native Supervisor cleanup found unexpected branch ${c} for ${s.root}; expected ${s.branch}`);try{C(e.paths.projectRoot,["merge-base","--is-ancestor",c,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${c}`)}}for(let s of a)if(ni(e.paths.projectRoot,s))try{C(e.paths.projectRoot,["merge-base","--is-ancestor",s,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${s}`)}return{parent:e.state.parent,targetCommit:e.targetCommit,worktrees:o.map(({root:s})=>s),expectedBranches:Object.fromEntries(o.map(({root:s,branch:c})=>[s,c])),branches:a}}async function tm(e){let t=lm(e.paths,e.state.parent);try{let i=JSON.parse(await Ro.readFile(t,"utf8"));if(i.parent===e.state.parent&&i.targetCommit===e.targetCommit&&Array.isArray(i.worktrees)&&i.expectedBranches&&typeof i.expectedBranches=="object"&&Array.isArray(i.branches)){let n=em(e);return{parent:i.parent,targetCommit:i.targetCommit,worktrees:[...new Set([...i.worktrees,...n.worktrees])],expectedBranches:{...i.expectedBranches,...n.expectedBranches},branches:[...new Set([...i.branches,...n.branches])]}}}catch(i){if(i.code!=="ENOENT")throw i}let r=em(e);return await U(t,r,{containedRoot:e.paths.changesRuntimeDir}),r}async function rm(e){for(let t of e.plan.worktrees){if(!ge(e.paths.projectRoot).map(a=>D.resolve(a)).includes(D.resolve(t)))continue;let i=e.plan.expectedBranches[t];if(!i)throw new Error(`Native Supervisor cleanup has no expected branch for ${t}`);let n=$(t).currentBranch;if(n!==i)throw new Error(`Native Supervisor cleanup found unexpected branch ${n??"(detached)"} for ${t}; expected ${i}`);await dn(t),C(e.paths.projectRoot,["worktree","remove",t])}for(let t of e.plan.branches)ni(e.paths.projectRoot,t)&&C(e.targetRoot,["branch","-d",t])}async function $l(e,t){await Ro.rm(lm(e,t),{force:!0})}function Bl(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:i.status==="ready"&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing"}));return{contractHash:null,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var Ol,XE,wn=E(()=>{"use strict";ko();q();se();Il();Eo();me();B();Ce();ke();Xp();Gr();Zp();jl();Ol="comet.native.supervisor.v2",XE=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u});var um={};Pu(um,{NATIVE_CHILDREN_FILE:()=>Ll,NATIVE_CHILDREN_SCHEMA:()=>hr,NATIVE_CHILDREN_SCHEMA_V2:()=>Ml,NATIVE_CHILDREN_V2_SCHEMA:()=>pr,findNativeV1SupervisorParents:()=>zl,hasNativeSupervisorShapeIntent:()=>ym,hashNativeParentContract:()=>Oo,inspectNativeChildren:()=>Ho,nativeChildrenAcceptanceValidation:()=>$o,nativeChildrenIndexDrift:()=>gm,parseNativeChildrenContract:()=>wm,readNativeChildrenContract:()=>mr,readNativeSupervisorShapeIntent:()=>Wl});import{promises as Fl}from"node:fs";import ve from"node:path";function jo(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function To(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 fm(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 ql(e,t){let r=ve.normalize(ve.resolve(e)),i=ve.normalize(ve.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function cP(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 hm(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 gm(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===Ml&&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 f=s.get(l),d=e.acceptance_index[l];f&&d&&(d.source!==f.source||d.text!==f.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(f=>!c.has(f)));return i.uncovered=o.filter(l=>!pm(e.children,l)),mm(i)?i:null}if(e.schema===hr&&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=>!pm(e.children,a)),mm(i)?i:null}return null}function pm(e,t){return e.some(r=>r.covers.includes(t))}function mm(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function $o(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 lP(e){let t=jo(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=jo(n,`Native children acceptance_index.${i}`);if(To(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 uP(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 f=c.get(l);if(!f)continue;let d=e[l];if(d.source!==f.source||d.text!==f.text){let u=["source","text"].filter(p=>d[p]!==f[p]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${u.join(", ")} exactly from the current acceptance catalog`)}}}function wm(e,t,r={}){let i=(0,Vl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=jo(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==hr&&a!==pr)throw To(n,dm,"Native children contract"),new Error(`Native children schema must be ${hr} or ${pr}`);let o=a===hr?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(To(n,o==="indexed-v2"?nP:dm,"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((u,p)=>{let g=jo(u,`Native child ${p}`);if(To(g,o==="indexed-v2"?sP:o==="summary-v2"?oP:aP,`Native ${s} child fields (child ${p})`),typeof g.name!="string"||!iP.test(g.name))throw new Error(`Native child ${p} name is invalid`);let h=o==="summary-v2";if(h){if(typeof g.summary!="string"||g.summary.trim().length===0)throw new Error(`Native child ${g.name} summary must be a non-empty string`);if(g.summary.length>2e3)throw new Error(`Native child ${g.name} summary exceeds 2000 characters`)}return{name:g.name,summary:h?g.summary:null,depends_on:fm(g.depends_on,`Native child ${g.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?fm(g.covers,`Native child ${g.name} covers`):[]}}),l=c.map(({name:u})=>u);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let f=new Set(l);for(let u of c){let p=u.depends_on.filter(g=>!f.has(g));if(p.length>0)throw new Error(`Native child ${u.name} depends on unknown child: ${p.join(", ")}`)}cP(c);let d=r.policy==="advisory";if(a===Ml){if(o==="indexed-v2"){let u=lP(n.acceptance_index);d||uP(u,t,r);let p=Object.keys(u);return d||hm(c,p,p),{schema:pr,acceptance_index:u,children:c}}return{schema:pr,children:c}}return t&&!d&&hm(c,t),{schema:hr,children:c}}async function mr(e){let t=ve.join(e.changeDir,Ll);try{await Fl.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await F({root:e.changeDir,ref:Ll}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=wm(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?gm(a,e.acceptanceIds,e.validation??{}):null}}function dP(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 ym(e){let t=dP(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 Wl(e){try{let t=await F({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return ym(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Oo(e){return H("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 Nm(e){let t=ge(e.projectRoot);t.some(i=>ql(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>ve.resolve(n)))]){let n=await ye(i);n&&r.push({projectRoot:i,paths:await ct(i,n.native.artifact_root),parent:ql(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function zl(e){let t=await Nm(e.paths),r=[],i=[],n=new Map;for(let a of t){let o;try{o=await Fl.readdir(a.paths.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o){if(!s.isDirectory()||s.isSymbolicLink()||s.name===e.childName)continue;let c=ve.join(a.paths.changesDir,s.name),l;try{l=await te(ve.join(c,"comet-state.yaml"))}catch{continue}if(l.phase!=="build"||l.status!=="active")continue;let f=await mr({changeDir:c,...l.acceptance.length>0?{acceptanceIds:l.acceptance.map(({id:d})=>d)}:{}});!f||f.contract.schema!==hr||f.contract.children.some(({name:d})=>d===e.childName)&&n.set(l.name,[...n.get(l.name)??[],{source:a,state:l}])}}for(let[a,o]of n){let s=e.targetBranch===null?[]:o.filter(({state:p})=>p.workspace.target_branch===e.targetBranch);if(e.targetBranch===null){i.push(`Native Supervisor Child ${e.childName} has no target branch to match parent ${a}`);continue}let c=s.find(({source:p,state:g})=>$(p.projectRoot).currentBranch===g.workspace.change_branch);if(!c){let p=o.find(({state:g})=>g.workspace.target_branch!==e.targetBranch);if(p)i.push(`Native Supervisor parent ${a} targets ${p.state.workspace.target_branch??"(missing)"}, not ${e.targetBranch}`);else{let g=s[0]?.state??o[0].state;i.push(`Native Supervisor parent ${a} is not bound to branch ${g.workspace.change_branch}`)}continue}let{source:l,state:f}=c,d=l.paths,u=await Ho({paths:d,state:f});if(!u)i.push(`Native Supervisor parent ${a} has no readable Child inspection`);else if(!u.confirmed)i.push(`Native Supervisor parent ${a} requires Shape confirmation`);else if(u.allDone)r.push({paths:d,state:f,inspection:u});else{let p=u.children.filter(({status:g})=>g!=="done").map(({name:g,status:h,message:m})=>`${g}=${h}${m?` (${m})`:""}`).join(", ");i.push(`Native Supervisor parent ${a} is not ready to advance: ${p||"Child facts are incomplete"}`)}}return n.size===0&&i.push(`Native Supervisor Child ${e.childName} has no active v1 parent declaring it`),n.size>1&&i.push(`Native Supervisor Child ${e.childName} has multiple active parents: ${[...n.keys()].join(", ")}`),r.length===1&&i.length===0?{candidate:r[0],blockers:i}:(r.length>1&&i.push(`Native Supervisor Child ${e.childName} has multiple eligible parents: ${r.map(({state:a})=>a.name).join(", ")}`),{candidate:null,blockers:i})}async function fP(e,t){let r=ve.join(e.paths.changesDir,t,"comet-state.yaml");try{return await te(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function hP(e,t){let r;try{r=await Fl.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=ve.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await te(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function pP(e,t,r){let i=ve.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${ve.sep}`))return null;let n=i.split(ve.sep).join("/");try{let a=(0,Vl.parseDocument)(C(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:ne(a.toJS({mapAsMap:!1}))}catch{return null}}function mP(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 vm(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Ho(e){let t=ve.join(e.paths.changesDir,e.state.name),r=await Wl(t),i=null,n;try{n=await mr({changeDir:t,validation:$o(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 qe(e.paths,e.state.name,{diagnostics:!0});if(v){let y=Bl(v);return{...y,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(b=>({...b,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=Oo({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===pr){let v=await qe(e.paths,e.state.name,{diagnostics:!0});if(!v){let w=e.state.workspace.change_branch??e.state.workspace.target_branch;if(w){let N=await Dl({paths:e.paths,parent:e.state.name,targetBranch:w,contract:n.contract});N&&(v=N,await fr(e.paths,N))}}if(v){let w=Bl(v);return e.state.children_contract_hash!==a||n.drift?{...w,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(N=>({...N,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...w,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&w.confirmed}}let y=new Map(n.contract.children.map(w=>[w.name,w])),b=n.contract.children.map(w=>({name:w.name,summary:w.summary,dependsOn:[...w.depends_on],covers:[],status:s&&w.depends_on.every(N=>n.contract.children.filter(({name:P})=>P!==w.name).every(({name:P})=>P!==N))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let w of b){if(w.status!=="ready")continue;y.get(w.name).depends_on.length>0&&(w.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:b,readyChildren:b.filter(({status:w})=>w==="ready").map(({name:w})=>w),allDone:!1}}let c=await Nm(e.paths),l=new Set(n.contract.children.map(({name:v})=>v)),f=new Map,d=new Map;for(let v of c){let y=v.parent&&o?`refs/heads/${o}`:"HEAD";for(let b of await hP(v,l)){let w={...b,source:v,committedState:pP(v,b.file,y)};f.set(b.state.name,[...f.get(b.state.name)??[],w])}for(let b of l){let w=await fP(v,b);w&&d.set(b,[...d.get(b)??[],{source:v,state:w}])}}let u=new Map;for(let v of n.contract.children){let y=(f.get(v.name)??[]).find(({source:N,committedState:P})=>N.parent&&P?.name===v.name&&vm(P,o));if(y){u.set(v.name,{kind:"done",phase:y.state.phase,projectRoot:y.source.projectRoot,message:null});continue}let b=f.get(v.name)?.[0];if(b){u.set(v.name,{kind:"blocked",phase:b.state.phase,projectRoot:b.source.projectRoot,message:`Native child ${v.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let w=d.get(v.name)??[];w.length>1?u.set(v.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${v.name} has multiple active workspace owners`}):w[0]&&u.set(v.name,mP(w[0].state,w[0].source,o))}let p=new Map(n.contract.children.map(v=>[v.name,v])),g=new Map,h=v=>{let y=g.get(v);if(y)return y;let b=p.get(v),N=b.depends_on.map(h).every(({status:ae})=>ae==="done"),P=u.get(v),x=P?.kind==="active"&&N?b.depends_on.filter(ae=>!(f.get(ae)??[]).some(({source:j,committedState:nt})=>ql(j.projectRoot,P.projectRoot)&&nt?.name===ae&&vm(nt,o))):[],k,_=P?.message??null;P?.kind==="done"?(k=N?"done":"blocked",N||(_=`Native child ${v} was merged before its dependencies`)):P?.kind==="active"?(k=N&&x.length===0?"active":"blocked",N?x.length>0&&(_=`Native child ${v} does not include merged dependencies: ${x.join(", ")}`):_=`Native child ${v} started before its dependencies merged`):P?.kind==="blocked"?k="blocked":(k=s&&N?"ready":"pending",s||(_="Parent Shape confirmation is required"));let ue={name:v,summary:b.summary,dependsOn:[...b.depends_on],covers:[...b.covers],status:k,phase:P?.phase??null,projectRoot:P?.projectRoot??null,message:_};return g.set(v,ue),ue},m=n.contract.children.map(({name:v})=>h(v));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:m,readyChildren:m.filter(({status:v})=>v==="ready").map(({name:v})=>v),allDone:m.every(({status:v})=>v==="done")}}var Vl,Ll,hr,pr,Ml,iP,dm,nP,aP,oP,sP,Io=E(()=>{"use strict";Vl=ri(jr(),1);ke();Gr();Ee();se();Ce();B();Ye();wn();Ll="children.yaml",hr="comet.native.children.v1",pr="comet.native.children.v2",Ml=pr,iP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dm=new Set(["schema","children"]),nP=new Set(["schema","acceptance_index","children"]),aP=new Set(["name","depends_on","covers"]),oP=new Set(["name","summary","depends_on"]),sP=new Set(["name","depends_on","covers"])});var Sm,Yr=E(()=>{"use strict";se();tn();Sm=1024*1024});var Fo=E(()=>{"use strict";se();ur();si();Yr()});var Pm,RP,AP,_P,VO,IP,MO,Xl=E(()=>{"use strict";se();Pm="scoped-text-safety",RP=1,AP=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),_P="comet.native.checker-policy.v1",VO=H(_P,{policy:Pm,version:RP,limits:AP,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),IP=["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"],MO=new Set(IP)});var Vo=E(()=>{"use strict";se();Xl();ur()});var $P,o0,Xr=E(()=>{"use strict";q();B();Me();Yr();Fo();Vo();$P=Sm,o0=3*$P});import jv from"node:path";ke();q();Ee();Y();Ce();me();import{randomUUID as UP}from"node:crypto";import{promises as ie}from"node:fs";import X from"node:path";ke();q();import{promises as vr}from"node:fs";import pt from"node:path";Zt();Y();Ee();et();B();import AE from"path";var _E=["outcome","scope","nonGoals","acceptanceExamples"],Xj=[..._E,"constraints","decisions","openQuestions","verificationExpectations"];function Mp(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}function un(e,t){return AE.join(e.specsDir,t,"spec.md")}Ee();se();Io();wn();Y();Il();Ye();Xi();mn();Eo();function vP(e){return e.state_version+1}function gP(e){return e.map(t=>({...t,result:"pending",reason:null}))}function wP(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:lt(e.summary),completed_at:e.completedAt}}function Jl(e){let t=ne(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=(e.now??new Date).toISOString(),i=Ot(t,wP({state:t,outcome:"recovery",summary:e.reason,completedAt:r})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?gP(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return ne({...i,phase:"build",status:"active",state_version:vP(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:a,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,stop_reason:void 0,next_action:"submit-builder-candidate"}})}q();Ui();import{promises as km}from"node:fs";import yn from"node:path";function Do(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Bo(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 tt(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 bm(e,t){return e===null?null:tt(e,t)}function qo(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 yP(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 NP(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Lo(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Gl(e,t){if(e===null)return null;let r=tt(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Ul(e,t){let r=tt(e,t);if(!yn.isAbsolute(r))throw new Error(`${t} must be absolute`);return yn.resolve(r)}function bP(e,t){let r=`Native local checks[${t}]`,i=Do(e,r);if(Bo(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((l,f)=>tt(l,`${r}.argv[${f}]`,!0)),a=Lo(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Gl(i.startedAt,`${r}.startedAt`),s=Gl(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=qo(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:tt(i.id,`${r}.id`),name:tt(i.name,`${r}.name`),operationId:tt(i.operationId,`${r}.operationId`),status:a,repeatable:NP(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:qo(i.executionCount,`${r}.executionCount`),argv:n,cwd:Ul(i.cwd,`${r}.cwd`),exitCode:yP(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:tt(i.log,`${r}.log`)}}function Kl(e){let t="Native local execution state",r=Do(e,t);if(Bo(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==Gi)throw new Error(`Native local execution schema must be ${Gi}`);let i=Do(r.workspace,"Native local workspace");Bo(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Do(r.execution,"Native local execution");Bo(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Gl(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:tt(o.operationId,"Native local execution.operationId"),stage:Lo(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Lo(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:bm(o.executionId,"Native local execution.executionId"),status:Lo(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:qo(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(bP);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:Gi,change:tt(r.change,"Native local change"),basedOnStateVersion:qo(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Ul(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Ul(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:bm(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function ft(e){return Kl({schema:Gi,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:yn.resolve(e.projectRoot),worktreeRoot:yn.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Yl(e){let t;try{t=await km.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 Kl(r)}async function rt(e,t,r={}){let i=Kl(t);await km.mkdir(yn.dirname(e),{recursive:!0}),await U(e,i,r)}me();eo();Ye();Fr();Xi();mn();Eo();q();Zt();mn();import{promises as kP}from"node:fs";function Ft(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
152
|
-
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function
|
|
153
|
-
`),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(d=>{let u=d.argv_display.map(Ft).join(" ");return`| ${
|
|
151
|
+
`),o.context,i)),o=null}};for(let{line:c,body:l}of Ya(e)){let f=l?Xh(c):null,d=f?/^Scenario\s*:\s*(.*)$/iu.exec(f.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=f.level;)a.pop();let u=Ji(d[1]);if(u.length===0)throw new Error("Scenario title must not be empty");o={level:f.level,title:u,body:[],context:a.map(p=>p.text)}}else if(f){for(o!==null&&f.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f)}else o!==null&&l&&o.body.push(c)}return s(),Zh(n,"Specification",i)}var Rk,h_,Xa,Qa=E(()=>{"use strict";Zt();se();Rk="comet.native.acceptance.v1",h_=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Xa=Object.freeze({maxCriteria:1024})});import ep from"node:path";function tp(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||ep.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||ep.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function Ik(e,t){return e.localeCompare(t,"en")}function Za(e){let t=tp(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>Ik(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=nl(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=tp(a.source,`Native spec source for ${a.capability}`);i.push(...al(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=Ji(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function rp(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(!_k.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function ip(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var _k,eo=E(()=>{"use strict";Qa();_k=/^A[1-9]\d*$/u});function to(){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 ar,Gi,np,Ui=E(()=>{"use strict";ar="comet.native.v4",Gi="comet.native.local-execution.v4",np=["multi-session","single-session"]});var ll={};Pu(ll,{NativePortableStateVersionConflictError:()=>Ki,appendNativePortableHistory:()=>Ot,compareAndSwapNativePortableState:()=>Ht,createNativePortableState:()=>sp,parseNativePortableState:()=>ne,readNativePortableState:()=>te,writeNativePortableState:()=>Yi});import{promises as Tk}from"node:fs";function ce(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function le(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 K(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 sl(e,t){return e===null?null:K(e,t)}function ap(e,t){let r=K(e,t);if(!Hk.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Lr(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function L(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 Bk(e,t){return e===null?null:L(e,t,Number.MIN_SAFE_INTEGER)}function W(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Ye(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function no(e,t){return Ye(e,t,(r,i)=>K(r,`${t}[${i}]`))}function or(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function qr(e,t){let r=K(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function cl(e,t,r=!1){let i=K(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 Ae(e,t){let r=ce(e,t);return le(r,new Set(["text","truncated"]),t),{text:K(r.text,`${t}.text`,{empty:!0}),truncated:Lr(r.truncated,`${t}.truncated`)}}function Lk(e,t){let r=`Native spec_changes[${t}]`,i=ce(e,r);le(i,new Set(["capability","operation","source"]),r);let n=K(i.capability,`${r}.capability`);if(!$k.test(n))throw new Error(`${r}.capability is invalid`);let a=W(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:cl(i.source,`${r}.source`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);return{capability:n,operation:a,source:o}}function qk(e){let t="Native workspace",r=ce(e,t);le(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=W(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=sl(r.change_branch,`${t}.change_branch`),a=sl(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:W(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 Fk(e){let t="Native loop",r=ce(e,t);le(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=no(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);or(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:W(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:W(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:L(r.goal_cycle,`${t}.goal_cycle`,1),iteration:L(r.iteration,`${t}.iteration`),attempt:L(r.attempt,`${t}.attempt`),retry_epoch:L(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:L(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:L(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:L(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:sl(r.next_action,`${t}.next_action`)}}function Vk(e,t){let r=`Native acceptance[${t}]`,i=ce(e,r);le(i,new Set(["id","source","text","result","reason"]),r);let n=K(i.id,`${r}.id`);if(!Ok.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:cl(i.source,`${r}.source`),text:K(i.text,`${r}.text`),result:W(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Ae(i.reason,`${r}.reason`)}}function Mk(e,t){let r=`Native builder_handoff.checks[${t}]`,i=ce(e,r);return le(i,new Set(["name","result","note"]),r),{name:Ae(i.name,`${r}.name`),result:W(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Ae(i.note,`${r}.note`)}}function Wk(e){let t="Native builder_handoff",r=ce(e,t);le(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=no(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);or(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:ce(r.review,`${t}.review`);return n&&le(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:K(r.candidate_id,`${t}.candidate_id`),identity_provider:K(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:K(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:L(r.iteration,`${t}.iteration`,1),summary:Ae(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Ye(r.checks,`${t}.checks`,Mk),checks_truncated:Lr(r.checks_truncated,`${t}.checks_truncated`),known_limits:Ye(r.known_limits,`${t}.known_limits`,(a,o)=>Ae(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Lr(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:W(n.status,["passed"],`${t}.review.status`),summary:Ae(n.summary,`${t}.review.summary`),reviewer_execution_ref:K(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:qr(r.submitted_at,`${t}.submitted_at`)}}function zk(e,t){let r=`Native blockers[${t}]`,i=ce(e,r);le(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=no(i.acceptance_ids,`${r}.acceptance_ids`);return or(n,`${r}.acceptance_ids`),{owner:W(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Ae(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:W(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function Jk(e,t){let r=`Native verification.checks[${t}]`,i=ce(e,r);return le(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:K(i.id,`${r}.id`),name:Ae(i.name,`${r}.name`),argv_display:Ye(i.argv_display,`${r}.argv_display`,(n,a)=>Ae(n,`${r}.argv_display[${a}]`)),argv_truncated:Lr(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:cl(i.cwd_ref,`${r}.cwd_ref`,!0),status:W(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:Bk(i.exit_code,`${r}.exit_code`),duration_ms:L(i.duration_ms,`${r}.duration_ms`)}}function Gk(e){let t="Native verification",r=ce(e,t);le(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Ye(r.checks,`${t}.checks`,Jk);or(i.map(a=>a.id),`${t}.checks IDs`);let n=K(r.identity_provider,`${t}.identity_provider`);return{candidate_id:K(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:K(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:L(r.iteration,`${t}.iteration`,1),attempt:L(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":W(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:W(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:Ae(r.summary,`${t}.summary`),risks:Ye(r.risks,`${t}.risks`,(a,o)=>Ae(a,`${t}.risks[${o}]`)),risks_truncated:Lr(r.risks_truncated,`${t}.risks_truncated`),completed_at:qr(r.completed_at,`${t}.completed_at`)}}function op(e,t){let r=`Native history[${t}]`,i=ce(e,r);le(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=no(i.unresolved_ids,`${r}.unresolved_ids`);return or(n,`${r}.unresolved_ids`),{goal_cycle:L(i.goal_cycle,`${r}.goal_cycle`,1),iteration:L(i.iteration,`${r}.iteration`),attempt:L(i.attempt,`${r}.attempt`),outcome:W(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Ae(i.summary,`${r}.summary`),completed_at:qr(i.completed_at,`${r}.completed_at`)}}function Uk(e){let t="Native history_overflow.outcome_counts",r=ce(e,t),i=["pass","fail","blocked","execution-error","recovery"];return le(r,new Set(i),t),{pass:L(r.pass,`${t}.pass`),fail:L(r.fail,`${t}.fail`),blocked:L(r.blocked,`${t}.blocked`),"execution-error":L(r["execution-error"],`${t}.execution-error`),recovery:L(r.recovery,`${t}.recovery`)}}function Kk(e){let t="Native history_overflow",r=ce(e,t);le(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=L(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:qr(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:qr(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=Uk(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 Yk(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 Xk(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 ne(e){let t=ce(e,"Native portable state");if(le(t,Dk,"Native portable state"),t.schema!==ar)throw new Error(`Native portable state schema must be ${ar}`);let r=K(t.name,"Native state name");if(!jk.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=Ye(t.spec_changes,"Native spec_changes",Lk);or(i.map(s=>s.capability),"Native spec change capabilities");let n=Ye(t.acceptance,"Native acceptance",Vk);or(n.map(s=>s.id),"Native acceptance IDs");let a=Ye(t.history,"Native history",op);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:ar,name:r,language:W(t.language,["en","zh-CN"],"Native state language"),phase:W(t.phase,["shape","build","verify","archive"],"Native state phase"),status:W(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:L(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:ap(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:ap(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:W(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:qk(t.workspace),loop:Fk(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:Wk(t.builder_handoff),blockers:Ye(t.blockers,"Native blockers",zk),verification:t.verification===null?null:Gk(t.verification),history:a,history_overflow:Kk(t.history_overflow),verification_result:W(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:W(t.verification_report,["verification.md"],"Native verification_report"),archived:Lr(t.archived,"Native archived"),created_at:qr(t.created_at,"Native created_at")};return Yk(o),Xk(o),o}function sp(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return ne({schema:ar,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:to(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function Ot(e,t){let r=ne(e),i=op(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 ne({...r,history:n,history_overflow:a})}function Qk(e,t){let r=(0,io.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 te(e){let t=await Tk.readFile(e,"utf8");return ne(Qk(t,"Native portable state"))}async function Yi(e,t,r={}){let i=ne(t);await de(e,(0,io.stringify)(i),r)}async function Zk(e,t){let r=ro.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);ro.set(e,a),await r;try{return await t()}finally{i(),ro.get(e)===a&&ro.delete(e)}}async function Ht(e){return Zk(e.file,async()=>{let t=L(e.expectedStateVersion,"Native expected state version",1),r=ne(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await te(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new Ki(t,i.state_version);return await Yi(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await te(e.file);if(n.state_version!==t)throw new Ki(t,n.state_version)}}),r})}var io,jk,$k,Ok,Hk,Dk,Ki,ro,Xe=E(()=>{"use strict";io=ri(jr(),1);q();Ui();jk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,$k=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ok=/^A[1-9][0-9]*$/u,Hk=/^[a-f0-9]{64}$/u,Dk=new Set(["schema","name","language","phase","status","state_version","brief","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),Ki=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"};ro=new Map});function eS(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function ut(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(eS(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 Xi=E(()=>{"use strict"});var dt,Qe,Ze,ao=E(()=>{"use strict";dt="comet.native.v3",Qe="comet.native.v2",Ze="comet.native.v1"});import tS from"node:path";function sS(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function cS(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 lS(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 uS(e){return e.schema===Ze?Qi(e):e.schema===Qe?Zi(e):en(e)}function dS(e){return tS.posix.normalize(e.replaceAll("\\","/"))}function fS(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:dS(t.source)})}function hS(e){return e==="shape"?"shape":"build"}function pS(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function mS(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 cp(e){let t=uS(e.state);rp(e.acceptance);let r=hS(t.phase),i=r==="shape"?0:1,n=cS(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 ne({schema:ar,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:fS(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:pS(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:ut(mS(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:to(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function ul(e){let t=sS(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!rS.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==oo)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!nS.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!iS.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!oS.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!aS.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:oo,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:lS(t.createdAt,"Native portable migration transaction createdAt")}}function lp(e){switch(ul(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 oo,rS,iS,nS,aS,oS,dl=E(()=>{"use strict";Y();eo();Xe();Xi();Ui();ao();oo="comet.native.portable-migration.v1",rS=new Set(["schema","id","change","fromSchema","status","createdAt"]),iS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,nS=/^[a-z0-9][a-z0-9-]{7,127}$/u,aS=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),oS=new Set([Ze,Qe,dt])});import fl from"node:path";function fp(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function hp(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${r} fields are invalid`)}function SS(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=fp(e,r);if(hp(i,kS,r),typeof i.capability!="string"||!dp.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation;if(n==="remove"){if(i.source!==null||i.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);return{capability:i.capability,operation:n,source:i.source,content:i.content}}function ES(e){let t=fp(e,"Native portable Archive transaction");if(hp(t,bS,"Native portable Archive transaction"),t.schema!==so)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!wS.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!dp.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"||!yS.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"||!NS.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(SS);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:so,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 co(e){let t=vS.exec(e);if(t)return{kind:"archive",change:t[1]};let r=gS.exec(e);return r?{kind:"migration",change:r[1]}:null}function sr(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=co(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return fl.join(e.transactionsDir,r)}async function hl(e,t){let r=co(t);if(!r)return null;let i=await F({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=fl.join(e.transactionsDir,t);if(r.kind==="archive"){let s=ES(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=ul(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 Dt(e,t){let r=sr(e,t);try{return await hl(e,fl.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function pp(e){return e.kind==="archive"||e.journal.status!=="committed"}var so,up,vS,gS,wS,yS,NS,bS,kS,dp,Fr=E(()=>{"use strict";Ee();dl();so="comet.native.archive-transaction.v4",up="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",vS=new RegExp(`^portable-archive-(${up})\\.json$`,"u"),gS=new RegExp(`^portable-migration-(${up})\\.json$`,"u"),wS=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,yS=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,NS=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),bS=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),kS=new Set(["capability","operation","source","content"]),dp=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as PS}from"node:crypto";import{constants as lo,promises as Le}from"node:fs";import qe from"node:path";function fo(e,t){let r=qe.relative(e,t);return r===""||!qe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${qe.sep}`)}function xS(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function CS(e,t){return O({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function RS(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function uo(e,t){return O({...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 pl(e,t){let r=await Le.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Le.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function AS(e,t,r){let i=qe.resolve(e),n=qe.resolve(t);if(!fo(i,n))throw new Error(`${r} is outside its managed root`);let a=[await pl(i,r)],o=i;for(let s of qe.relative(i,n).split(qe.sep).filter(Boolean)){await cr(a,r),o=qe.join(o,s);let c=await pl(o,r);if(!fo(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await cr(a,r),a}async function cr(e,t){for(let r of e){let i=await Le.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!CS(r,i)||await Le.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function _S(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Vr(e){let t=xS(e.maxBytes),r=qe.resolve(e.file),i=await AS(e.root,qe.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(f=>pl(qe.resolve(f),e.label)));await e.hooks?.afterParentChainCaptured?.(),await cr(i,e.label);let a=await Le.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=RS(a),s=await Le.realpath(r);if(!fo(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(f=>fo(f.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?lo.O_RDONLY:lo.O_RDONLY|lo.O_NOFOLLOW|lo.O_NONBLOCK,l=await Le.open(r,c);try{let f=await l.stat();await e.hooks?.afterOpen?.();let[d,u]=await Promise.all([Le.lstat(r),Le.realpath(r)]);if(await cr(i,e.label),await cr(n,e.label),!f.isFile()||!d.isFile()||d.isSymbolicLink()||u!==s||!uo(o,f)||!uo(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await _S(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[g,h,m]=await Promise.all([l.stat(),Le.lstat(r),Le.realpath(r)]);if(await cr(i,e.label),await cr(n,e.label),!h.isFile()||h.isSymbolicLink()||m!==s||!uo(o,g)||!uo(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:PS("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}var et=E(()=>{"use strict";q();We()});import ft from"path";import{TextDecoder as TS}from"util";function po(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function mo(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 wp(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function ml(e,t){if(typeof e!="string"||e.length===0||ft.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function ho(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function mp(e,t){if(ml(e,t),e.includes("\\")||e!==ft.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 LS(e,t){let r=po(e,`transaction operations[${t}]`);if(mo(r,$S,`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`);ml(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&ml(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 yp(e){let t=po(e,"Native Archive transaction journal");if(mo(t,OS,"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"||!gp.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(!wp(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(ho(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=po(s,`Archive transaction operations[${c}]`);if(mo(l,HS,`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`);mp(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&mp(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&ho(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(ho(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`);ho(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 qS(e){let t=po(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return yp(t);if(mo(t,jS,"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"||!gp.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!ft.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!ft.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(!wp(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(LS),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 FS(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return ft.join(e.transactionsDir,t)}function Np(e,t){let r=FS(e,t);return{directory:r,journal:ft.join(r,"transaction.json"),events:ft.join(r,"events.jsonl"),staged:ft.join(r,"staged"),backups:ft.join(r,"backups")}}async function gl(e,t){let r=Np(e,t);return await Promise.all(Object.values(r).map(i=>V(e.runtimeDir,i))),r}async function wl(e,t,r={}){let i=await gl(e,t),n=await Vr({root:e.runtimeDir,file:i.journal,maxBytes:DS,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(BS.decode(n.bytes)),o=qS(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var jS,$S,OS,HS,gp,DS,Y_,X_,Q_,BS,vo=E(()=>{"use strict";q();B();et();jS=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),$S=new Set(["id","type","source","target","staged","backup"]),OS=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),HS=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),gp=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),DS=256*1024,Y_=1024*1024,X_=16*1024,Q_=64*1024*1024,BS=new TS("utf-8",{fatal:!0})});import{promises as VS}from"fs";import MS from"path";async function WS(e,t,r){let i;try{i=await VS.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 wl(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(co(n.name))try{let a=await hl(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(pp(a))return!0}catch{return!0}return!1}async function zS(e,t){let r=Date.now()+5e3,i=MS.join(e.locksDir,"root-move.lock");for(;;)try{return await Ua(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Uh(i);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function re(e,t,r,i){let n=await zS(e,t);try{if(await Wi(e.projectRoot),await WS(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await Ka(n)}}var me=E(()=>{"use strict";Ce();zi();Fr();vo()});var bp=E(()=>{"use strict"});import{createHash as JS}from"crypto";function _e(e){return JS("sha256").update(e).digest("hex")}var tt=E(()=>{"use strict"});var yI,NI,bI,kI,SI,EI,PI,tn=E(()=>{"use strict";q();Ce();tt();We();B();et();si();yI={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},NI=8*1024*1024,bI=64*1024,kI=64*1024,SI={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},EI={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024},PI=(1n<<256n)-1n});var rn=E(()=>{"use strict"});var go=E(()=>{"use strict"});var kp=E(()=>{"use strict"});var yl=E(()=>{"use strict";go()});var Sp=E(()=>{"use strict";go();yl()});var ZS,Ep=E(()=>{"use strict";ZS=ri(jr(),1);Hr();Tt();ir()});var FI,Pp=E(()=>{"use strict";Hr();ir();FI=4*1024*1024});function tE(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function xp(e,t){return(...r)=>{let i=eE;if(i===null)return t(...r);let n=tE(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}var eE,Cp=E(()=>{"use strict";eE=null});var JI,Rp=E(()=>{"use strict";Cp();Or();JI=xp("hookWritePolicy",async e=>(await Jc(e))?.hook??{allow_paths:[]})});var Ap=E(()=>{"use strict";go();Hr();kp();Sp();Tt();Ep();ir();Or();Yc();Pp();Rp();Gc();yl()});var _p=E(()=>{"use strict";Ap();ai()});var MT,Ip=E(()=>{"use strict";_p();MT=256*1024});var Tp=E(()=>{"use strict";Ip();rn()});var rj,nn=E(()=>{"use strict";rn();Tp();q();We();rj={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024}});var Nl=E(()=>{"use strict";rn();me();B();nn()});import Mr from"node:path";function nE(e,t){let r=Mr.relative(e,t);return Mr.isAbsolute(r)||r===".."||r.startsWith(`..${Mr.sep}`)?null:r.replaceAll("\\","/")||"."}function Op(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Hp(e,t){if(e.length===0||Op(e)||e.includes("\\")||Mr.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=Mr.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function aE(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 bl(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Op(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function oE(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(bl(e.changeBranch,"Native workspace change branch"),bl(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 sE(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"||!$p.test(t.baseCommit)||typeof t.targetCommit!="string"||!$p.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");bl(t.targetBranch,"Native workspace Git target branch")}function cE(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"||!an.test(String(t.projectRootId))||!an.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");aE(t.capturedAt),Hp(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&&!an.test(String(t.projectRootPathId))||a&&!an.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!an.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&sE(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(oE(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 lE(e,t){return Mr.join(Ge(e,t),"workspace.json")}function uE(e,t){let r=lE(e,t),i=Ue(e,r),n=nE(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:Hp(n,"Native workspace file ref")}}async function dE(e,t){try{let r=uE(e,t),i=await F({root:r.root,ref:r.ref,maxBytes:iE});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function on(e,t){let r=await dE(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(cE(r),r)}var an,$p,iE,gj,Wr=E(()=>{"use strict";ke();q();Ee();me();B();an=/^[a-f0-9]{64}$/u,$p=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,iE=16*1024,gj=process.platform});import zr from"path";function ln(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Fp(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 xl(e){if(!qp.test(e))throw new Error(`Invalid Native change name: ${e}`)}function bE(e){if(!qp.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Vp(e,t){if(e.length===0||zr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function kE(e,t){let r=ln(e,`spec_changes[${t}]`);if(Fp(r,vE,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(bE(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&Vp(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!Sl.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!Sl.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function SE(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function Cl(e,t){if(Fp(e,t,lr),typeof e.name!="string")throw new Error("Native change name is required");if(xl(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!gE.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!wE.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(kE),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!yE.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&Vp(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!SE(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function Qi(e){let t=ln(e,lr);if(t.schema!==Ze)throw new Error(`Expected ${Ze}`);return{schema:Ze,...Cl(t,pE)}}function cn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function kl(e,t,r){if(e===null)return null;let i=typeof e=="string"?NE.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function EE(e){if(e==null)return null;if(typeof e!="string"||!Sl.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function PE(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function Zi(e){let t=ln(e,lr);if(t.schema!==Qe)throw new Error(`Expected ${Qe}`);if(cn(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Qe} minimum_runtime_version must be 2`);return{schema:Qe,minimum_runtime_version:2,revision:cn(t.revision,"Native v2 revision"),...Cl(t,Lp)}}function en(e){let t=ln(e,lr);if(t.schema!==dt){if(t.schema===Ze||t.schema===Qe){let o=t.schema===Ze?Qi(t):Zi(t);throw new El(o.name,o.schema)}throw new Lt(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=cn(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Lt(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=cn(t.revision,"Native revision"),n=Cl(t,mE),a=EE(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:dt,minimum_runtime_version:3,revision:i,verification_protocol:PE(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:kl(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:kl(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:kl(t.partial_allowance,"Native partial_allowance","allowances")}}function xE(e){let t=ln(e,lr);if(t.schema===Ze){let n=Qi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${dt}`}}if(t.schema===Qe){let n=Zi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${dt}`}}if(t.schema!==dt){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Lt(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=cn(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Lt(t.schema,r).message};let i=en(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function Ne(e,t){xl(t);let r=zr.join(e.changesDir,t);if(!J(e.changesDir,r))throw new Error("Native change path escaped");return r}async function CE(e,t=zr.dirname(e)){let r=zr.relative(t,e).split(zr.sep).join("/"),i=await F({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Pl.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 No(e,t){let r=zr.join(Ne(e,t),lr);await V(e.nativeRoot,r);let i=xE(await CE(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}var Pl,Bp,pE,Lp,mE,vE,gE,wE,yE,lr,Sl,qp,NE,El,Lt,wo,sn,yo,Vj,Y=E(()=>{"use strict";Pl=ri(jr(),1);ke();Ee();q();Zt();Ce();me();B();et();bp();tn();Nl();Wr();ao();Bp=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],pE=new Set(Bp),Lp=new Set([...Bp,"minimum_runtime_version","revision"]),mE=new Set([...Lp,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),vE=new Set(["capability","operation","source","base_hash"]),gE=new Set(["shape","build","verify","archive"]),wE=new Set(["implicit","confirmed"]),yE=new Set(["pending","pass","fail"]),lr="comet-state.yaml",Sl=/^[a-f0-9]{64}$/u,qp=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,NE=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,El=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Lt=class extends Error{constructor(r,i){super(r!==dt||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},wo=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"},sn=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"},yo=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"},Vj=Ta("en")});import{execFileSync as IE}from"node:child_process";function Wp(e,t){try{return IE("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:TE,maxBuffer:jE,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Rl(e,t,i)}}function C(e,t){return Wp(e,t).trim()}function Jr(e){let t=Wp(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let r=t.split("\0").filter(Boolean),i=[];for(let n=0;n<r.length;n+=1){let a=r[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(i.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=r[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");i.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(i)].sort()}function zp(e,t){try{let i=C(e,["config","--get",`branch.${t}.remote`]);if(i&&i!==".")return i}catch{}let r=C(e,["remote"]).split(/\r?\n/u).map(i=>i.trim()).filter(Boolean);if(r.includes("origin"))return"origin";if(r.length===1)return r[0];throw new Error(r.length===0?"Native workspace finish requires a configured Git remote":`Native workspace finish requires an unambiguous Git remote: ${r.join(", ")}`)}var TE,jE,Rl,Gr=E(()=>{"use strict";TE=3e4,jE=8*1024*1024,Rl=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});import{createHash as $E}from"node:crypto";import{lstatSync as OE,readFileSync as Jp,promises as HE}from"node:fs";import Al from"node:path";function Ur(e){try{if(C(e,["ls-files","--",bo]))return!1;let t=Al.join(e,bo),r=OE(t);return!r.isFile()||r.isSymbolicLink()?!1:JSON.parse(Jp(DE(e),"utf8")).hash===BE(Jp(t))}catch{return!1}}function Kr(e,t=[]){return Jr(e).every(r=>t.some(i=>r===i||r.startsWith(`${i}/`))||r===bo&&Ur(e))}async function dn(e){Ur(e)&&await HE.unlink(Al.join(e,bo))}var bo,DE,BE,ko=E(()=>{"use strict";Gr();q();bo=".comet/config.yaml",DE=e=>Al.join(e,".comet","runtime","native","workspace-config.json"),BE=e=>$E("sha256").update(e).digest("hex")});import{existsSync as LE}from"node:fs";import fn from"node:path";function Gp(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function FE(e){let t=(Gp(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function VE(e,t,r){let n=fn.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Gp(t,"PATH")??"").split(fn.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=fn.win32.extname(e)?[e]:FE(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?fn.join(s,c):fn.resolve(r,c)))}function Up(e,t,r){return VE(e,t,r).find(i=>LE(i))??e}function Kp(e){if(e.some(t=>qE.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var qE,l$,So=E(()=>{"use strict";qE=/[&|<>()^%"!\r\n]/u,l$=["$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("; ")});var _l=E(()=>{"use strict"});var ur=E(()=>{"use strict"});var Il=E(()=>{"use strict";So();_l();ur()});var pn,mn=E(()=>{"use strict";pn="skill-coordinated"});var Eo=E(()=>{"use strict";mn()});import Po from"node:path";function Yp(...e){if(e.length===0)return Po.resolve();if(Po.win32.isAbsolute(e[0])){let t=Po.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return Po.resolve(...e)}var Xp=E(()=>{"use strict"});import{execFileSync as JE}from"node:child_process";import Qp from"node:path";function dr(e,t,r={}){let i=r.timeoutMs??GE,n=r.maxBufferBytes??UE;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=Qp.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?Up(e,o,a):e,c=Qp.win32.extname(s).toLowerCase(),l=c===".bat"||c===".cmd";process.platform==="win32"&&l&&Kp(t);try{return JE(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(f){let d=typeof f.stderr=="string"?f.stderr.trim():Buffer.isBuffer(f.stderr)?f.stderr.toString("utf8").trim():"";throw new Tl(e,t,d,{cause:f})}}var GE,UE,Tl,xo=E(()=>{"use strict";So();GE=6e4,UE=8*1024*1024,Tl=class extends Error{constructor(r,i,n,a){super(`${r} ${i.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=r;this.args=i;this.stderr=n;this.name="ExternalCommandError"}command;args;stderr}});var Zp=E(()=>{"use strict";xo()});var Co,jl=E(()=>{"use strict";Gr();ke();Ce();ko();zi();B();Co=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation}});import D from"node:path";import{promises as Ro}from"node:fs";function QE(e,t){let r=D.relative(D.resolve(e),D.resolve(t));return r===""||!D.isAbsolute(r)&&!r.startsWith(`..${D.sep}`)}function ZE(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function eP(e,t,r){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(r))throw new Error("Native Supervisor parent and child names are invalid");return Yp(e,".worktrees",`${t}-${r}`)}function im(e,t){return D.join(xe(e,t),"supervisor")}function Ao(e,t){return D.join(im(e,t),"state.json")}function nm(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!==Ol)throw new Error(`Native Supervisor state schema must be ${Ol}`);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(qt(t.integration.targetCommit,"Native Supervisor target commit"),qt(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");qt(n.candidateCommit,"Native Supervisor integration candidate commit"),qt(n.integrationCommit,"Native Supervisor integration check commit")}if(!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&qt(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(qt(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function Fe(e,t,r={}){try{let i=await Ro.readFile(Ao(e,t),"utf8"),n=JSON.parse(i);if(nm(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativeChildrenContract:s,nativeChildrenAcceptanceValidation:c}=await Promise.resolve().then(()=>(Io(),um)),{readNativePortableState:l}=await Promise.resolve().then(()=>(Xe(),ll)),f=await l(D.join(o.changesDir,t,"comet-state.yaml")),d=await s({changeDir:D.join(o.changesDir,t),acceptanceIds:f.acceptance.map(({id:u})=>u),validation:c(f)});if(!d)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let u of n.children)d.contract.children.some(({name:p})=>p===u.name)&&(u.acceptanceScope=om(d.contract,u.name),u.contractHash=H("comet.native.supervisor-contract.v1",d.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(()=>(Xe(),ll)),s=await o(D.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 fr(e,t){nm(t),await Ro.mkdir(e.changesRuntimeDir,{recursive:!0}),await U(Ao(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function qt(e,t){if(!XE.test(e))throw new Error(`${t} must be a Git commit`)}function vn(e){return structuredClone(e)}function Hl(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function am(e){qt(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:om(e.contract,i.name),contractHash:H("comet.native.supervisor-contract.v1",e.contract)}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:Ol,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 om(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}async function Dl(e){let t=ZE(e.parent),r=Jt(e.paths.projectRoot,t);if(!r)return null;let i=Jt(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=ge(e.paths.projectRoot).map(o=>D.resolve(o)).find(o=>$(o).currentBranch===t);if(!n)return null;let a=am({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 Hl(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function _o(e){if(!Kr(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=C(e.integration.worktree,["rev-parse","--show-toplevel"]);if(D.resolve(t)!==D.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=C(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 C(e.integration.worktree,["rev-parse","HEAD"])}async function tP(e){let t=Jt(e.paths.projectRoot,e.state.integration.targetBranch);if(!t||t===e.state.integration.targetCommit)return null;let r=e.state;if(_o(r)!==r.integration.headCommit)throw new Error("Native Supervisor integration head changed before target refresh");try{C(r.integration.worktree,["merge","--no-edit",r.integration.targetBranch])}catch(o){throw new Error(`Native Supervisor target drift requires conflict resolution in ${r.integration.worktree}`,{cause:o})}let n=C(r.integration.worktree,["rev-parse","HEAD"]),a=vn(r);return a.integration.headCommit=n,a.finalVerification={status:"pending",summary:null},Hl(a,{kind:"target-refreshed",child:null,runId:null,summary:`Target ${r.integration.targetBranch} was refreshed before delivery`}),a.stateVersion+=1,await fr(e.paths,a),a}function rP(e,t){if(qt(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=vn(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 sm(e){let t=_o(e);if(t===e.integration.headCommit)return e;try{C(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=vn(e);return r.integration.headCommit=t,Hl(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function cm(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=_o(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 rP(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}async function gn(e){let r=await Fe(e.paths,e.state.parent)??e.state;if(r.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before delivery; reload status first");if(r.finalVerification.status!=="passed")throw new Error("Native Supervisor delivery requires a passed final verification");if(!r.children.every(({status:h})=>h==="integrated"||h==="archived"))throw new Error("Native Supervisor delivery requires every child to be integrated");let n=ge(e.paths.projectRoot).map(h=>D.resolve(h)).find(h=>$(h).currentBranch===r.integration.targetBranch);if(!n)throw new Error(`Native Supervisor target branch worktree is unavailable: ${r.integration.targetBranch}`);let a=D.resolve(n)===D.resolve(e.paths.projectRoot)?[D.relative(n,D.join(e.paths.changesDir,r.parent)).replaceAll("\\","/"),".comet/current-change.json",...e.archiveOwnedPaths??[]]:[];if(!Kr(n,a))throw new Error(`Native Supervisor target worktree is not clean: ${n}`);let o=C(n,["rev-parse","HEAD"]);if((()=>{try{return C(n,["merge-base","--is-ancestor",r.integration.headCommit,o]),!0}catch{return!1}})()){let h=await tm({paths:e.paths,state:r,targetCommit:o});if(await rm({paths:e.paths,plan:h,targetRoot:n}),r.children.every(({status:v})=>v==="archived"))return await $l(e.paths,r.parent),{state:r,targetRoot:n,targetCommit:o};let m=vn(r);for(let v of m.children)v.status="archived";return m.stateVersion+=1,await fr(e.paths,m),await $l(e.paths,r.parent),{state:m,targetRoot:n,targetCommit:o}}let l=_o(r);if(l!==r.integration.headCommit)throw new Error("Native Supervisor integration head changed after final verification");let f=Jt(e.paths.projectRoot,r.integration.targetBranch),d=(()=>{if(!f)return!1;try{return C(r.integration.worktree,["merge-base","--is-ancestor",f,l]),!0}catch{return!1}})();if(f!==l&&!d&&f!==r.integration.targetCommit&&await tP({paths:e.paths,state:r}))throw new Error("Native Supervisor target changed; parent integration checks must be rerun before delivery");let u=await tm({paths:e.paths,state:r,targetCommit:l});f!==l&&C(n,["merge","--ff-only",r.integration.branch]);let p=C(n,["rev-parse","HEAD"]);if(p!==l)throw new Error("Native Supervisor target did not receive the verified integration head");let g=vn(r);for(let h of g.children)h.status="archived";return await rm({paths:e.paths,plan:u,targetRoot:n}),g.stateVersion+=1,await fr(e.paths,g),await $l(e.paths,r.parent),{state:g,targetRoot:n,targetCommit:p}}function lm(e,t){return D.join(im(e,t),"cleanup.json")}function em(e){let t=ge(e.paths.projectRoot).map(s=>D.resolve(s)),r=D.resolve(process.cwd()),i=[{root:e.state.integration.worktree,branch:e.state.integration.branch},...e.state.children.map(({name:s,projectRoot:c,task:l})=>({root:c??l?.projectRoot??eP($(e.paths.projectRoot).primaryWorktreeRoot??e.paths.projectRoot,e.state.parent,s),branch:`comet/supervisor/${e.state.parent}/${s}`}))].map(s=>({...s,root:D.resolve(s.root)})),n=e.targetCommit,a=[e.state.integration.branch,...e.state.children.map(({name:s})=>`comet/supervisor/${e.state.parent}/${s}`)],o=i.flatMap(s=>{let c=t.find(l=>l===s.root);return c?[{...s,root:c}]:[]});for(let s of o){if(QE(s.root,r))throw new Error(`Native Supervisor cannot clean the current worktree: ${s.root}`);if(!Kr(s.root))throw new Error(`Native Supervisor cleanup requires a clean worktree: ${s.root}`);let c=$(s.root).currentBranch;if(!c)throw new Error(`Native Supervisor worktree is detached: ${s.root}`);if(c!==s.branch)throw new Error(`Native Supervisor cleanup found unexpected branch ${c} for ${s.root}; expected ${s.branch}`);try{C(e.paths.projectRoot,["merge-base","--is-ancestor",c,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${c}`)}}for(let s of a)if(ni(e.paths.projectRoot,s))try{C(e.paths.projectRoot,["merge-base","--is-ancestor",s,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${s}`)}return{parent:e.state.parent,targetCommit:e.targetCommit,worktrees:o.map(({root:s})=>s),expectedBranches:Object.fromEntries(o.map(({root:s,branch:c})=>[s,c])),branches:a}}async function tm(e){let t=lm(e.paths,e.state.parent);try{let i=JSON.parse(await Ro.readFile(t,"utf8"));if(i.parent===e.state.parent&&i.targetCommit===e.targetCommit&&Array.isArray(i.worktrees)&&i.expectedBranches&&typeof i.expectedBranches=="object"&&Array.isArray(i.branches)){let n=em(e);return{parent:i.parent,targetCommit:i.targetCommit,worktrees:[...new Set([...i.worktrees,...n.worktrees])],expectedBranches:{...i.expectedBranches,...n.expectedBranches},branches:[...new Set([...i.branches,...n.branches])]}}}catch(i){if(i.code!=="ENOENT")throw i}let r=em(e);return await U(t,r,{containedRoot:e.paths.changesRuntimeDir}),r}async function rm(e){for(let t of e.plan.worktrees){if(!ge(e.paths.projectRoot).map(a=>D.resolve(a)).includes(D.resolve(t)))continue;let i=e.plan.expectedBranches[t];if(!i)throw new Error(`Native Supervisor cleanup has no expected branch for ${t}`);let n=$(t).currentBranch;if(n!==i)throw new Error(`Native Supervisor cleanup found unexpected branch ${n??"(detached)"} for ${t}; expected ${i}`);await dn(t),C(e.paths.projectRoot,["worktree","remove",t])}for(let t of e.plan.branches)ni(e.paths.projectRoot,t)&&C(e.targetRoot,["branch","-d",t])}async function $l(e,t){await Ro.rm(lm(e,t),{force:!0})}function Bl(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:i.status==="ready"&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing"}));return{contractHash:null,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var Ol,XE,wn=E(()=>{"use strict";ko();q();se();Il();Eo();me();B();Ce();ke();Xp();Gr();Zp();jl();Ol="comet.native.supervisor.v2",XE=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u});var um={};Pu(um,{NATIVE_CHILDREN_FILE:()=>Ll,NATIVE_CHILDREN_SCHEMA:()=>hr,NATIVE_CHILDREN_SCHEMA_V2:()=>Ml,NATIVE_CHILDREN_V2_SCHEMA:()=>pr,findNativeV1SupervisorParents:()=>zl,hasNativeSupervisorShapeIntent:()=>ym,hashNativeParentContract:()=>Oo,inspectNativeChildren:()=>Ho,nativeChildrenAcceptanceValidation:()=>$o,nativeChildrenIndexDrift:()=>gm,parseNativeChildrenContract:()=>wm,readNativeChildrenContract:()=>mr,readNativeSupervisorShapeIntent:()=>Wl});import{promises as Fl}from"node:fs";import ve from"node:path";function jo(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function To(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 fm(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 ql(e,t){let r=ve.normalize(ve.resolve(e)),i=ve.normalize(ve.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function cP(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 hm(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 gm(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===Ml&&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 f=s.get(l),d=e.acceptance_index[l];f&&d&&(d.source!==f.source||d.text!==f.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(f=>!c.has(f)));return i.uncovered=o.filter(l=>!pm(e.children,l)),mm(i)?i:null}if(e.schema===hr&&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=>!pm(e.children,a)),mm(i)?i:null}return null}function pm(e,t){return e.some(r=>r.covers.includes(t))}function mm(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function $o(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 lP(e){let t=jo(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=jo(n,`Native children acceptance_index.${i}`);if(To(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 uP(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 f=c.get(l);if(!f)continue;let d=e[l];if(d.source!==f.source||d.text!==f.text){let u=["source","text"].filter(p=>d[p]!==f[p]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${u.join(", ")} exactly from the current acceptance catalog`)}}}function wm(e,t,r={}){let i=(0,Vl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=jo(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==hr&&a!==pr)throw To(n,dm,"Native children contract"),new Error(`Native children schema must be ${hr} or ${pr}`);let o=a===hr?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(To(n,o==="indexed-v2"?nP:dm,"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((u,p)=>{let g=jo(u,`Native child ${p}`);if(To(g,o==="indexed-v2"?sP:o==="summary-v2"?oP:aP,`Native ${s} child fields (child ${p})`),typeof g.name!="string"||!iP.test(g.name))throw new Error(`Native child ${p} name is invalid`);let h=o==="summary-v2";if(h){if(typeof g.summary!="string"||g.summary.trim().length===0)throw new Error(`Native child ${g.name} summary must be a non-empty string`);if(g.summary.length>2e3)throw new Error(`Native child ${g.name} summary exceeds 2000 characters`)}return{name:g.name,summary:h?g.summary:null,depends_on:fm(g.depends_on,`Native child ${g.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?fm(g.covers,`Native child ${g.name} covers`):[]}}),l=c.map(({name:u})=>u);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let f=new Set(l);for(let u of c){let p=u.depends_on.filter(g=>!f.has(g));if(p.length>0)throw new Error(`Native child ${u.name} depends on unknown child: ${p.join(", ")}`)}cP(c);let d=r.policy==="advisory";if(a===Ml){if(o==="indexed-v2"){let u=lP(n.acceptance_index);d||uP(u,t,r);let p=Object.keys(u);return d||hm(c,p,p),{schema:pr,acceptance_index:u,children:c}}return{schema:pr,children:c}}return t&&!d&&hm(c,t),{schema:hr,children:c}}async function mr(e){let t=ve.join(e.changeDir,Ll);try{await Fl.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await F({root:e.changeDir,ref:Ll}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=wm(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?gm(a,e.acceptanceIds,e.validation??{}):null}}function dP(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 ym(e){let t=dP(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 Wl(e){try{let t=await F({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return ym(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Oo(e){return H("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 Nm(e){let t=ge(e.projectRoot);t.some(i=>ql(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>ve.resolve(n)))]){let n=await ye(i);n&&r.push({projectRoot:i,paths:await lt(i,n.native.artifact_root),parent:ql(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function zl(e){let t=await Nm(e.paths),r=[],i=[],n=new Map;for(let a of t){let o;try{o=await Fl.readdir(a.paths.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o){if(!s.isDirectory()||s.isSymbolicLink()||s.name===e.childName)continue;let c=ve.join(a.paths.changesDir,s.name),l;try{l=await te(ve.join(c,"comet-state.yaml"))}catch{continue}if(l.phase!=="build"||l.status!=="active")continue;let f=await mr({changeDir:c,...l.acceptance.length>0?{acceptanceIds:l.acceptance.map(({id:d})=>d)}:{}});!f||f.contract.schema!==hr||f.contract.children.some(({name:d})=>d===e.childName)&&n.set(l.name,[...n.get(l.name)??[],{source:a,state:l}])}}for(let[a,o]of n){let s=e.targetBranch===null?[]:o.filter(({state:p})=>p.workspace.target_branch===e.targetBranch);if(e.targetBranch===null){i.push(`Native Supervisor Child ${e.childName} has no target branch to match parent ${a}`);continue}let c=s.find(({source:p,state:g})=>$(p.projectRoot).currentBranch===g.workspace.change_branch);if(!c){let p=o.find(({state:g})=>g.workspace.target_branch!==e.targetBranch);if(p)i.push(`Native Supervisor parent ${a} targets ${p.state.workspace.target_branch??"(missing)"}, not ${e.targetBranch}`);else{let g=s[0]?.state??o[0].state;i.push(`Native Supervisor parent ${a} is not bound to branch ${g.workspace.change_branch}`)}continue}let{source:l,state:f}=c,d=l.paths,u=await Ho({paths:d,state:f});if(!u)i.push(`Native Supervisor parent ${a} has no readable Child inspection`);else if(!u.confirmed)i.push(`Native Supervisor parent ${a} requires Shape confirmation`);else if(u.allDone)r.push({paths:d,state:f,inspection:u});else{let p=u.children.filter(({status:g})=>g!=="done").map(({name:g,status:h,message:m})=>`${g}=${h}${m?` (${m})`:""}`).join(", ");i.push(`Native Supervisor parent ${a} is not ready to advance: ${p||"Child facts are incomplete"}`)}}return n.size===0&&i.push(`Native Supervisor Child ${e.childName} has no active v1 parent declaring it`),n.size>1&&i.push(`Native Supervisor Child ${e.childName} has multiple active parents: ${[...n.keys()].join(", ")}`),r.length===1&&i.length===0?{candidate:r[0],blockers:i}:(r.length>1&&i.push(`Native Supervisor Child ${e.childName} has multiple eligible parents: ${r.map(({state:a})=>a.name).join(", ")}`),{candidate:null,blockers:i})}async function fP(e,t){let r=ve.join(e.paths.changesDir,t,"comet-state.yaml");try{return await te(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function hP(e,t){let r;try{r=await Fl.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=ve.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await te(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function pP(e,t,r){let i=ve.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${ve.sep}`))return null;let n=i.split(ve.sep).join("/");try{let a=(0,Vl.parseDocument)(C(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:ne(a.toJS({mapAsMap:!1}))}catch{return null}}function mP(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 vm(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Ho(e){let t=ve.join(e.paths.changesDir,e.state.name),r=await Wl(t),i=null,n;try{n=await mr({changeDir:t,validation:$o(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 Fe(e.paths,e.state.name,{diagnostics:!0});if(v){let y=Bl(v);return{...y,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(b=>({...b,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=Oo({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===pr){let v=await Fe(e.paths,e.state.name,{diagnostics:!0});if(!v){let w=e.state.workspace.change_branch??e.state.workspace.target_branch;if(w){let N=await Dl({paths:e.paths,parent:e.state.name,targetBranch:w,contract:n.contract});N&&(v=N,await fr(e.paths,N))}}if(v){let w=Bl(v);return e.state.children_contract_hash!==a||n.drift?{...w,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(N=>({...N,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...w,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&w.confirmed}}let y=new Map(n.contract.children.map(w=>[w.name,w])),b=n.contract.children.map(w=>({name:w.name,summary:w.summary,dependsOn:[...w.depends_on],covers:[],status:s&&w.depends_on.every(N=>n.contract.children.filter(({name:P})=>P!==w.name).every(({name:P})=>P!==N))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let w of b){if(w.status!=="ready")continue;y.get(w.name).depends_on.length>0&&(w.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:b,readyChildren:b.filter(({status:w})=>w==="ready").map(({name:w})=>w),allDone:!1}}let c=await Nm(e.paths),l=new Set(n.contract.children.map(({name:v})=>v)),f=new Map,d=new Map;for(let v of c){let y=v.parent&&o?`refs/heads/${o}`:"HEAD";for(let b of await hP(v,l)){let w={...b,source:v,committedState:pP(v,b.file,y)};f.set(b.state.name,[...f.get(b.state.name)??[],w])}for(let b of l){let w=await fP(v,b);w&&d.set(b,[...d.get(b)??[],{source:v,state:w}])}}let u=new Map;for(let v of n.contract.children){let y=(f.get(v.name)??[]).find(({source:N,committedState:P})=>N.parent&&P?.name===v.name&&vm(P,o));if(y){u.set(v.name,{kind:"done",phase:y.state.phase,projectRoot:y.source.projectRoot,message:null});continue}let b=f.get(v.name)?.[0];if(b){u.set(v.name,{kind:"blocked",phase:b.state.phase,projectRoot:b.source.projectRoot,message:`Native child ${v.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let w=d.get(v.name)??[];w.length>1?u.set(v.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${v.name} has multiple active workspace owners`}):w[0]&&u.set(v.name,mP(w[0].state,w[0].source,o))}let p=new Map(n.contract.children.map(v=>[v.name,v])),g=new Map,h=v=>{let y=g.get(v);if(y)return y;let b=p.get(v),N=b.depends_on.map(h).every(({status:ae})=>ae==="done"),P=u.get(v),x=P?.kind==="active"&&N?b.depends_on.filter(ae=>!(f.get(ae)??[]).some(({source:j,committedState:at})=>ql(j.projectRoot,P.projectRoot)&&at?.name===ae&&vm(at,o))):[],k,_=P?.message??null;P?.kind==="done"?(k=N?"done":"blocked",N||(_=`Native child ${v} was merged before its dependencies`)):P?.kind==="active"?(k=N&&x.length===0?"active":"blocked",N?x.length>0&&(_=`Native child ${v} does not include merged dependencies: ${x.join(", ")}`):_=`Native child ${v} started before its dependencies merged`):P?.kind==="blocked"?k="blocked":(k=s&&N?"ready":"pending",s||(_="Parent Shape confirmation is required"));let ue={name:v,summary:b.summary,dependsOn:[...b.depends_on],covers:[...b.covers],status:k,phase:P?.phase??null,projectRoot:P?.projectRoot??null,message:_};return g.set(v,ue),ue},m=n.contract.children.map(({name:v})=>h(v));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:m,readyChildren:m.filter(({status:v})=>v==="ready").map(({name:v})=>v),allDone:m.every(({status:v})=>v==="done")}}var Vl,Ll,hr,pr,Ml,iP,dm,nP,aP,oP,sP,Io=E(()=>{"use strict";Vl=ri(jr(),1);ke();Gr();Ee();se();Ce();B();Xe();wn();Ll="children.yaml",hr="comet.native.children.v1",pr="comet.native.children.v2",Ml=pr,iP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dm=new Set(["schema","children"]),nP=new Set(["schema","acceptance_index","children"]),aP=new Set(["name","depends_on","covers"]),oP=new Set(["name","summary","depends_on"]),sP=new Set(["name","depends_on","covers"])});var Sm,Yr=E(()=>{"use strict";se();tn();Sm=1024*1024});var Fo=E(()=>{"use strict";se();ur();si();Yr()});var Pm,RP,AP,_P,VO,IP,MO,Xl=E(()=>{"use strict";se();Pm="scoped-text-safety",RP=1,AP=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),_P="comet.native.checker-policy.v1",VO=H(_P,{policy:Pm,version:RP,limits:AP,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),IP=["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"],MO=new Set(IP)});var Vo=E(()=>{"use strict";se();Xl();ur()});var $P,o0,Xr=E(()=>{"use strict";q();B();We();Yr();Fo();Vo();$P=Sm,o0=3*$P});import jv from"node:path";ke();q();Ee();Y();Ce();me();import{randomUUID as UP}from"node:crypto";import{promises as ie}from"node:fs";import X from"node:path";ke();q();import{promises as vr}from"node:fs";import mt from"node:path";Zt();Y();Ee();tt();B();import AE from"path";var _E=["outcome","scope","nonGoals","acceptanceExamples"],Xj=[..._E,"constraints","decisions","openQuestions","verificationExpectations"];function Mp(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}function un(e,t){return AE.join(e.specsDir,t,"spec.md")}Ee();se();Io();wn();Y();Il();Xe();Xi();mn();Eo();function vP(e){return e.state_version+1}function gP(e){return e.map(t=>({...t,result:"pending",reason:null}))}function wP(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:ut(e.summary),completed_at:e.completedAt}}function Jl(e){let t=ne(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=(e.now??new Date).toISOString(),i=Ot(t,wP({state:t,outcome:"recovery",summary:e.reason,completedAt:r})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?gP(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return ne({...i,phase:"build",status:"active",state_version:vP(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:a,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,stop_reason:void 0,next_action:"submit-builder-candidate"}})}q();Ui();import{promises as km}from"node:fs";import yn from"node:path";function Do(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Bo(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 rt(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 bm(e,t){return e===null?null:rt(e,t)}function qo(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 yP(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 NP(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Lo(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Gl(e,t){if(e===null)return null;let r=rt(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Ul(e,t){let r=rt(e,t);if(!yn.isAbsolute(r))throw new Error(`${t} must be absolute`);return yn.resolve(r)}function bP(e,t){let r=`Native local checks[${t}]`,i=Do(e,r);if(Bo(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((l,f)=>rt(l,`${r}.argv[${f}]`,!0)),a=Lo(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Gl(i.startedAt,`${r}.startedAt`),s=Gl(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=qo(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:rt(i.id,`${r}.id`),name:rt(i.name,`${r}.name`),operationId:rt(i.operationId,`${r}.operationId`),status:a,repeatable:NP(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:qo(i.executionCount,`${r}.executionCount`),argv:n,cwd:Ul(i.cwd,`${r}.cwd`),exitCode:yP(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:rt(i.log,`${r}.log`)}}function Kl(e){let t="Native local execution state",r=Do(e,t);if(Bo(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==Gi)throw new Error(`Native local execution schema must be ${Gi}`);let i=Do(r.workspace,"Native local workspace");Bo(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Do(r.execution,"Native local execution");Bo(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Gl(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:rt(o.operationId,"Native local execution.operationId"),stage:Lo(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Lo(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:bm(o.executionId,"Native local execution.executionId"),status:Lo(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:qo(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(bP);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:Gi,change:rt(r.change,"Native local change"),basedOnStateVersion:qo(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Ul(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Ul(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:bm(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function ht(e){return Kl({schema:Gi,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:yn.resolve(e.projectRoot),worktreeRoot:yn.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Yl(e){let t;try{t=await km.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 Kl(r)}async function it(e,t,r={}){let i=Kl(t);await km.mkdir(yn.dirname(e),{recursive:!0}),await U(e,i,r)}me();eo();Xe();Fr();Xi();mn();Eo();q();Zt();mn();import{promises as kP}from"node:fs";function Ft(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
152
|
+
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function pt(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function SP(e){return e.archived?pe(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?pe(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?pe(e.language,"Verification passed; ready to archive","验收通过,可归档"):pe(e.language,"Verification passed","验收通过")}function EP(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?pe(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?SP(e):e.verification_result==="blocked"?pe(t,"Blocked","已阻塞"):e.verification_result==="fail"?pe(t,"Failed","未通过"):pe(t,"Pending","待处理")}function PP(e){if(e.verification?.assurance==="semantic-verification-unavailable")return pe(e.language,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查");if(e.verification_result==="fail")return pe(e.language,"Fix unresolved acceptance criteria and verify again","修复未通过的验收项后重新验证");if(e.verification_result==="blocked")return pe(e.language,"Resolve the reported blockers and resume verification","解决报告中的阻塞项后恢复验证");let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===pn?pn:"host-attested"),r=t===pn&&(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 xP(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,i=d=>Dc(r,d),n=(d,u)=>pe(r,d,u),a=e.acceptance.map(d=>`| ${pt(d.id)} | ${pt(d.result)} | ${pt(d.source)} | ${pt(d.text)} | ${pt(Ft(d.reason))} |`).join(`
|
|
153
|
+
`),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(d=>{let u=d.argv_display.map(Ft).join(" ");return`| ${pt(Ft(d.name))} | ${pt(u||"—")} | ${pt(d.cwd_ref)} | ${d.status} | ${d.exit_code??"—"} | ${d.duration_ms} ms |`})].join(`
|
|
154
154
|
`),s=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(d=>`- **${d.owner}**: ${Ft(d.reason)}${d.acceptance_ids.length>0?` (acceptance: ${d.acceptance_ids.join(", ")})`:""} — next: \`${d.resolution_action}\``).join(`
|
|
155
155
|
`),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(d=>`- ${Ft(d)}`).join(`
|
|
156
|
-
`),l=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(d=>`| ${d.goal_cycle} | ${d.iteration} | ${d.attempt} | ${d.outcome} | ${d.unresolved_ids.join(", ")||"—"} | ${
|
|
156
|
+
`),l=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(d=>`| ${d.goal_cycle} | ${d.iteration} | ${d.attempt} | ${d.outcome} | ${d.unresolved_ids.join(", ")||"—"} | ${pt(Ft(d.summary))} | ${d.completed_at} |`)].join(`
|
|
157
157
|
`),f=t?.finalVerification.layers?`
|
|
158
158
|
## ${n("Supervisor evidence layers","Supervisor 分层证据")}
|
|
159
159
|
|
|
@@ -207,13 +207,13 @@ ${e.history_overflow.dropped_entries>0?`${n("Earlier history entries folded into
|
|
|
207
207
|
`:""}## ${i("conclusion")}
|
|
208
208
|
|
|
209
209
|
${Ft(e.verification.summary)}
|
|
210
|
-
`}function CP(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 Nn(e){let t;try{t=await kP.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=CP(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function bn(e){await de(e.file,xP(e.state,e.supervisor))}B();Zt();Xr();Ce();var xm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,HP="comet-state.yaml",DP="state.json",tH=Ta("en");function Ie(e,t){if(!xm.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=pt.join(e.changesDir,t);if(!J(e.changesDir,r))throw new Error("Native change path escaped");return r}function be(e,t){return pt.join(Ie(e,t),HP)}function Vt(e,t){return pt.join(xe(e,t),DP)}async function kn(e,t){try{let r=await vr.readFile(be(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Ql(e){return $(e).currentBranch}async function Fe(e,t){return te(be(e,t))}async function Zl(e){let t=await Ht({file:be(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=pt.join(Ie(e.paths,t.name),"verification.md");await V(e.paths.nativeRoot,r),await vr.rm(r,{force:!0})}return t}async function BP(e){let t=Ie(e.paths,e.state.name),r=pt.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await vr.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(!xm.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=pt.join(t,...s.split("/")),l=await vr.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let f=pt.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let u=await vr.lstat(f);if(!u.isFile()||u.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(u){if(u.code!=="ENOENT")throw u}a.push({capability:o.name,operation:d,source:s})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function LP(e){let t=Ie(e.paths,e.state.name),r=await F({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(Mp(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let a of e.specChanges){if(a.source===null){n.push({...a,contentHash:null});continue}let o=await F({root:t,ref:a.source,maxBytes:null,includeHash:!1});i.push({capability:a.capability,source:o.ref,markdown:o.text}),n.push({...a,contentHash:H("comet.native.shape-artifact-content.v1",o.text)})}return{acceptance:Za({briefMarkdown:r.text,specs:i}),formalHash:H("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:H("comet.native.shape-artifact-content.v1",r.text)},specs:n})}}function qP(e){return H("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function eu(e){let t=await BP(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,f)=>{let d=e.state.spec_changes[f];return d!==void 0&&l.capability===d.capability&&l.source===d.source&&(l.operation===d.operation||r?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await LP({...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:f})=>({source:l,text:f}));if(!ip(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await mr({changeDir:Ie(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:$o({...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&&qP({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?Oo({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 FP(e){let t=await Fe(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 Ho({paths:e.paths,state:t});if(!i||!i.confirmed||!i.allDone)return{state:t,parentAdvance:{...r,blocker:i&&!i.confirmed?"Supervisor child declarations require Shape confirmation":null}};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{state:t,parentAdvance:{...r,blocker:"Native parent verification failed; add and confirm a repair child"}};let n=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选需要独立代码审查后再进入验证":"All Children are complete; the Supervisor parent candidate needs an independent code review before verification.";return{state:t,parentAdvance:{...r,message:n}}}async function Cm(e){let t=await zl({paths:e.childPaths,childName:e.childState.name,targetBranch:e.childState.workspace.target_branch});if(!t.candidate)return{parentState:null,parentAdvance:{trigger:"v1-archive",parent:null,advanced:!1,message:null,blocker:t.blockers.length>0?t.blockers.join("; "):null}};let r=await FP({paths:t.candidate.paths,name:t.candidate.state.name,trigger:"v1-archive"});return{parentState:r.state,parentAdvance:r.parentAdvance}}async function Rm(e){let t=await Fe(e.paths,e.name),r=await Dt(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 qe(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 vr.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=sm(n);if(i||a.stateVersion!==n.stateVersion){let o=await VP({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 vr.rm(i.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await fr(e.paths,cm(n,t)),{state:t,action:"recorded-final-verification"}}async function Am(e){return re(e.paths,`set portable workspace finish ${e.name}`,async()=>{let t=await Fe(e.paths,e.name);if(t.workspace.isolation==="current")throw new Error("Native current-workspace isolation does not accept a finish action");let r={...t,state_version:t.state_version+1,workspace:{...t.workspace,finish:e.finish}},i=await Zl({paths:e.paths,previous:t,next:r});return await rt(Vt(e.paths,t.name),ft({portableState:i,projectRoot:e.paths.projectRoot,branch:Ql(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i.verification!==null&&await bn({file:pt.join(Ie(e.paths,t.name),"verification.md"),state:i}),i})}async function _m(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...Ot(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:lt(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await Zl({paths:e.paths,previous:t,next:i});return await rt(Vt(e.paths,t.name),ft({portableState:n,projectRoot:e.paths.projectRoot,branch:Ql(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function VP(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={...Ot(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:lt(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 Zl({paths:e.paths,previous:t,next:i});return await rt(Vt(e.paths,t.name),ft({portableState:n,projectRoot:e.paths.projectRoot,branch:Ql(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Mo(e){if(e.state.verification===null)return"not-applicable";let t=pt.join(Ie(e.paths,e.state.name),"verification.md");return await Nn({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await bn({file:t,state:e.state}),"rebuilt")}wn();Ye();Fr();B();Fi();import{promises as MP}from"fs";import WP from"path";var tu="comet.selection.v2",zP=16*1024;function Wo(e){return WP.join(e,".comet","current-change.json")}function JP(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Im(e){return e===null||typeof e=="string"}function GP(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!JP(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!Im(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:tu,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==tu)throw new Error(`current change selection schema must be ${tu}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Im(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function Tm(e){let t;try{let i=Wo(e),{bytes:n}=await rr(i,zP,{label:"current change selection"});t=n.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...GP(t)}}async function jm(e){await MP.rm(Wo(e),{force:!0})}async function $m(e,t,r){let i=await Tm(e);return i.status!=="selected"||i.selection.workflow!==t||i.selection.change!==r?!1:(await jm(e),!0)}Y();Ce();me();var hH=16*1024;function ru(e){return Wo(e.projectRoot)}async function zo(e,t){return await Wi(e.projectRoot),$m(e.projectRoot,"native",t)}var En=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}};function iu(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function nu(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let r=X.join(e.archiveDir,t);if(!J(e.archiveDir,r))throw new Error("Native Archive path escaped");return r}async function Sn(e){try{return await ie.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Om(e,t){let r=X.normalize(X.resolve(e)),i=X.normalize(X.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}async function Hm(e,t){let r;try{r=await ie.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let i=[];for(let n of r){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=X.join(e.archiveDir,n.name);try{let o=await te(X.join(a,"comet-state.yaml"));o.name===t&&i.push({dir:a,state:o})}catch{}}if(i.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return i[0]??null}async function ou(e,t){let r=await Dt(e,{kind:"archive",change:t});return r?.kind==="archive"?r.journal:null}async function Dm(e,t){return await ou(e,t)!==null||await Hm(e,t)!==null}async function gr(e,t){await ie.mkdir(e.transactionsDir,{recursive:!0}),await U(sr(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Bm(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let r=ge(e.paths.projectRoot);r.some(a=>Om(a,e.paths.projectRoot))||r.push(e.paths.projectRoot);let i=[];for(let a of r){let o=await ye(a);if(!o)continue;let s=await ct(a,o.native.artifact_root);i.some(c=>Om(c.changesDir,s.changesDir))||i.push(s)}i.length===0&&i.push(e.paths);let n=new Set;for(let a of i){let o;try{o=await ie.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let c=await te(X.join(a.changesDir,s.name,"comet-state.yaml"));c.status!=="done"&&c.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.name)}catch{let c=await No(a,s.name).catch(()=>null);c?.state&&c.state.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function KP(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function YP(e){let t=X.join(e.paths.specsDir,e.change.capability),r=X.join(t,"spec.md");if(!J(e.paths.specsDir,r))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await ie.lstat(e.paths.specsDir)}catch(c){if(c.code==="ENOENT")return;throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await ie.lstat(t)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[o,s]=await Promise.all([ie.realpath(e.paths.specsDir),ie.realpath(t)]);if(!J(o,s))throw new Error("Native canonical capability path escaped");try{let c=await ie.lstat(r);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await ie.unlink(r)}catch(c){if(c.code!=="ENOENT")throw c}await ie.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let i=X.join(Ie(e.paths,e.state.name),e.change.source);await de(i,e.change.content,{containedRoot:e.paths.nativeRoot}),await ie.mkdir(t,{recursive:!0}),await de(r,e.change.content,{containedRoot:e.paths.nativeRoot})}function su(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function XP(e,t){let r=Ie(e,t.name),i=[];for(let n of t.spec_changes){if(n.source===null){i.push({...n,content:null});continue}let a=await F({root:r,ref:n.source,maxBytes:null,includeHash:!1});i.push({...n,content:a.text})}return i}function QP(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(su(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function au(e,t){for(let r of t.spec_changes.slice(0,t.next_spec_index)){let i=`${r.capability}/spec.md`,n=X.join(e.specsDir,i);if(r.operation==="remove"){if(!await Sn(n))continue}else try{if((await F({root:e.specsDir,ref:i,maxBytes:null,includeHash:!1})).text===r.content)continue}catch(a){if(a.code!=="ENOENT")throw a}throw new Error(`Canonical Spec ${i} changed after Archive applied it; preserve the concurrent edit and resolve it before resuming Archive`)}}async function cu(e){let t=await Fe(e.paths,e.name),r=[];try{su(t)}catch(o){r.push(o.message)}let i=await ou(e.paths,e.name);if(i)try{await au(e.paths,i)}catch(o){r.push(o.message)}if(i===null)try{let o=await eu({paths:e.paths,state:t});o.drifted&&r.push(o.reason??"Native confirmed requirements changed")}catch(o){r.push(o.message)}let n=t.verification===null?"missing":await Nn({file:X.join(Ie(e.paths,t.name),"verification.md"),stateVersion:t.state_version});n!=="aligned"&&r.push(`verification.md is ${n}`);let a=await Bm({paths:e.paths,state:t});return a.length>0&&r.push(`capabilities are also declared by: ${a.join(", ")}`),{ready:r.length===0,blockers:r,capabilityPeers:a,archiveDir:nu(e.paths,iu(t)),stateVersion:t.state_version}}async function Lm(e){return re(e.paths,`archive portable change ${e.name}`,async()=>{let t=KP(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let r=await ou(e.paths,e.name),i=Ie(e.paths,e.name),n=await Sn(i),a=n?null:await Hm(e.paths,e.name),o;if(n)o=await Fe(e.paths,e.name);else if(r)o=await te(X.join(nu(e.paths,r.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);let s=await qe(e.paths,e.name);if(n&&!o.archived&&r===null){let u=await eu({paths:e.paths,state:o});if(u.drifted){let p=u.reason??"Native confirmed requirements changed";throw await _m({paths:e.paths,state:o,reason:p}),new Error(`${p}; Native change returned to Shape and requires confirmation`)}}if(n&&!o.archived&&s?.finalVerification.status==="pending"&&o.verification_result==="pass"){let u=await Rm({paths:e.paths,name:e.name});if(o=u.state,u.action==="rerun-final-verification")throw new Error("Native Supervisor final verification must be rerun for the current integration commit");u.action==="recorded-final-verification"&&(s=await qe(e.paths,e.name))}let c=nu(e.paths,r?.archive_ref??iu(o)),l=await Sn(c);if(r&&QP(r,o),n&&l)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!r&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await zo(e.paths,o.name),await ie.rm(xe(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!r){if(!o.archived)su(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let u=await Bm({paths:e.paths,state:o});if(!o.archived&&u.length>0&&t!==o.name)throw new En(u);r={schema:so,id:UP(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:iu(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await XP(e.paths,o),created_at:new Date().toISOString()},await gr(e.paths,r)}if(!n&&l&&r.status==="report-aligned")r={...r,status:"moved"},await gr(e.paths,r);else if(!n&&l&&r.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${r.status}; doctor intervention is required`);await au(e.paths,r);let f=r.spec_changes.slice(0,r.next_spec_index).map(({capability:u})=>X.relative(e.paths.projectRoot,X.join(e.paths.specsDir,u,"spec.md")).replaceAll("\\","/")),d=!1;if(r.status==="prepared"&&s&&!o.archived&&(s=(await gn({paths:e.paths,state:s,archiveOwnedPaths:f})).state,d=!0),r.status==="prepared"){for(let u=r.next_spec_index;u<r.spec_changes.length;u+=1)await YP({paths:e.paths,state:o,change:r.spec_changes[u]}),r={...r,next_spec_index:u+1},await gr(e.paths,r),await e.hooks?.afterSpecApplied?.(u);r={...r,status:"specs-applied"},await gr(e.paths,r)}if(await au(e.paths,r),r.status==="specs-applied"){if(s&&!o.archived&&!d&&(s=(await gn({paths:e.paths,state:s,archiveOwnedPaths:f})).state,d=!0),!o.archived){let u={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await Ht({file:be(e.paths,o.name),expectedStateVersion:o.state_version,next:u,containedRoot:e.paths.nativeRoot})}r={...r,status:"state-finalized"},await gr(e.paths,r),await e.hooks?.afterFinalState?.()}if(r.status==="state-finalized"){let u=await Sn(i)?i:c;if(await bn({file:X.join(u,"verification.md"),state:o,...s?{supervisor:s}:{}}),await Nn({file:X.join(u,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");r={...r,status:"report-aligned"},await gr(e.paths,r),s&&!d&&(await gn({paths:e.paths,state:s,archiveOwnedPaths:f}),d=!0),await e.hooks?.afterReportAligned?.()}if(r.status==="report-aligned"){if(s&&!d&&await gn({paths:e.paths,state:s,archiveOwnedPaths:f}),await ie.mkdir(e.paths.archiveDir,{recursive:!0}),await Sn(c))throw new Error(`Native Archive target already exists: ${c}`);await ie.rename(i,c),r={...r,status:"moved"},await gr(e.paths,r),await e.hooks?.afterMove?.()}return r.status==="moved"&&(await zo(e.paths,o.name),await ie.rm(xe(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await ie.rm(sr(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:c,transactionId:r.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}Ui();function mt(e,t,r){return e.language==="zh-CN"?r:t}function ZP(e,t){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:mt(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:mt(e,"Reply A or B","回复 A 或 B"),agentInstruction:mt(e,"Relay the two coordination choices and wait for the user decision. After the user chooses, execute the prepare-shape-confirmation commandArgs with the selected --coordination-mode. Do not combine mode selection with final confirmation; confirmation of the complete Shape is a separate await-user step.","转述这两个推进方式并等待用户选择。用户选择后,使用对应的 --coordination-mode 执行 prepare-shape-confirmation 的完整 commandArgs;不要把推进方式选择和最终确认合并执行,完整 Shape 的确认是后续单独的 await-user 步骤。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return r(mt(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return r(mt(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:i})=>i==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return r(mt(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 ex(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 tx(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:mt(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:mt(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Fm(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function wr(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function rx(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function qm(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function ix(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function nx(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 Mt(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Fm({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[wr("summary","--summary"),rx(e.name,e.flag)]}}function lu(e){return[Mt({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Mt({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function vt(e,t,r={}){let i=ix(t)&&e.coordination_mode===void 0,n=ZP(e,i),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[wr("summary","--summary")],commandAlternatives:[Mt({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:[wr("summary","--summary")],commandAlternatives:[Mt({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...lu({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:[wr("summary","--summary")],commandAlternatives:[Mt({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Mt({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:[wr("summary","--summary")],commandAlternatives:[Mt({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...lu({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:[wr("summary","--summary")],commandAlternatives:lu({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?Fm({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:nx({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?[qm("coordination-mode","--coordination-mode",np)]:[]],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:f})=>f==="verified");if(s)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}}],runnerAction:o("none")};let c=t.children.some(({status:f})=>f==="blocked"||f==="needs-reverify"),l=t.children.some(({status:f})=>f==="ready"||f==="active");return{...a,disposition:c&&!l?"blocked":"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:c&&!l?["resolve-child-blocker"]:["ready-children"],inputOptions:[wr("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${mt(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:c?[l]:[]}}],runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;return s==="blocked"?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:s==="preview"?r.archiveBlockers&&r.archiveBlockers.length>0?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}:l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[qm("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...tx(e)],userCommunication:ex(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Mt({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")}}ke();q();Ee();Y();me();dl();Fr();eo();import{randomUUID as ax}from"node:crypto";import{promises as Pn}from"node:fs";import ox from"node:path";Ye();B();Wr();var Vm=["evidence.md","repair.md","archive.md","checkpoint.md"],sx="verification.md";async function cx(e,t){let r=await Dt(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function Mm(e,t){await Pn.mkdir(e.transactionsDir,{recursive:!0}),await U(sr(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Wm(e,t,r={}){let i=r.removeVerificationReport===!1?Vm:[...Vm,sx];await Promise.all([Pn.rm(xe(e,t),{recursive:!0,force:!0}),Pn.rm(Zc(e,t),{recursive:!0,force:!0}),...i.map(n=>Pn.rm(ox.join(Ne(e,t),n),{force:!0}))])}async function zm(e,t){await rt(Vt(e,t.name),ft({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function Jm(e,t){try{let r=await on(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 Gm(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=$(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 lx(e){let t=Ne(e.paths,e.state.name),r=await F({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 F({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Za({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Um(e,t){let r=await No(e,t);if(r.status==="runtime-incompatible")throw new Lt(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function Km(e){return re(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await cx(e.paths,e.name),r=await kn(e.paths,e.name)?await te(be(e.paths,e.name)):null;if(!t&&r)return await Wm(e.paths,e.name,{removeVerificationReport:!1}),await zm(e.paths,r),r;let i=null,n=null;for(t||(i=await Um(e.paths,e.name),n=await Jm(e.paths,e.name),Gm(e.paths,n),t={schema:oo,id:ax(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Mm(e.paths,t));;){let a=lp(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await Um(e.paths,e.name),n??=await Jm(e.paths,e.name),Gm(e.paths,n),r=cp({state:i,acceptance:await lx({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await Yi(be(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Wm(e.paths,e.name):a.action==="commit-transaction"&&(r??=await te(be(e.paths,e.name)),await zm(e.paths,r)),t={...t,status:a.nextStatus},await Mm(e.paths,t)}return await Pn.rm(sr(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??te(be(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}ke();import{promises as Xm}from"node:fs";import Qm from"node:path";me();Io();se();wn();import{promises as uu}from"node:fs";import ux from"node:path";var dx=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),fx=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),hx=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task"]),px=new Set(["status","summary"]);function Jo(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Go(e,t,r){let i=new Set(Object.keys(e)),n=[...t].filter(o=>!i.has(o)),a=[...i].filter(o=>!t.has(o));return n.length===0&&a.length===0?null:`${r} fields must be exact (missing: ${n.join(", ")||"none"}; unexpected: ${a.join(", ")||"none"})`}function mx(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function yr(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function vx(e,t,r,i){let n=Jo(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=Go(n,dx,"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=Jo(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=Go(o,fx,"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=Jo(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=Go(c,px,"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[f,d]of n.children.entries()){let u=Jo(d,`Native Supervisor child ${f}`);if(!u)return`Native Supervisor child ${f} must be an object`;let{acceptanceScope:p,contractHash:g,...h}=u,m=Go(h,hx,`Native Supervisor child ${f}`);if(m)return m;let v=r.children[f],y=v.covers.length>0?v.covers.map(w=>({id:w,source:r.acceptance_index?.[w]?.source??"brief.md",text:r.acceptance_index?.[w]?.text??w})):[{id:`child:${v.name}`,source:"children.yaml",text:v.summary??v.name}];if(p!==void 0&&JSON.stringify(p)!==JSON.stringify(y)||g!==void 0&&g!==H("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${v.name} acceptance scope does not match the legacy contract`;if(u.name!==v.name||u.summary!==v.summary||!mx(u.dependsOn,v.depends_on))return`Native Supervisor child ${v.name} does not match the legacy children contract`;let b=v.depends_on.length===0?"ready":"pending";if(u.status!==b)return`Native Supervisor child ${v.name} has progressed beyond its initial ${b} status`;if(u.baseCommit!==null||u.candidateCommit!==null||u.verifiedCommit!==null||u.integrationCommit!==null||u.verification!==null||u.blocker!==null||u.projectRoot!==null||u.task!==null)return`Native Supervisor child ${v.name} contains execution progress`;if(!Array.isArray(u.checks)||u.checks.length!==0)return`Native Supervisor child ${v.name} contains integration checks`}return null}async function du(e){let t=Ao(e.paths,e.state.name),r;try{let c=await uu.lstat(t);if(!c.isFile()||c.isSymbolicLink())return yr(t,"","Native Supervisor overlay is not a regular file");r=await uu.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:yr(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return yr(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=ux.join(e.paths.changesDir,e.state.name),a;try{a=await mr({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return yr(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 qe(e.paths,e.state.name)}catch(c){return yr(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return yr(t,r,"Native Supervisor overlay disappeared during inspection");let s=vx(i,e.state,a.contract,o);return s?yr(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 Ym(e){let t=await du({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 uu.rm(t.file,{force:!1})}Ye();Xi();function gx(e,t){let r=$(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 wx(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function yx(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:Ot(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:lt(t),completed_at:i});return ne({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?wx(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 Nx(e){try{let t=await Yl(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 Zm(e){return re(e.paths,`recover portable change ${e.name}`,async()=>{let t=await Fe(e.paths,e.name);if(t.status==="done")return await Mo({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=gx(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await du({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 Ym({paths:e.paths,state:t,expected:i}),n=!0);let a=Vt(e.paths,e.name),o=await Nx(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason;if(s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed"&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(g=>g.status==="planned"||g.status==="running"?{...g,status:"interrupted"}:g)},await rt(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await Mo({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(g=>g.status==="interrupted"&&!g.repeatable):void 0;if(l){let g=Jl({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Ht({file:be(e.paths,t.name),expectedStateVersion:t.state_version,next:g,containedRoot:e.paths.nativeRoot}),await Xm.rm(Qm.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let h=ft({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await rt(a,h,{containedRoot:e.paths.runtimeDir}),{state:t,local:h,action:"resume-stable-boundary",reason:s,message:`Native check ${l.id} was not repeatable; the change returned to Build for a new candidate.`}}let f=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",d=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",u=f||d;if(u){let g=yx(t,d?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",d);t=await Ht({file:be(e.paths,t.name),expectedStateVersion:t.state_version,next:g,containedRoot:e.paths.nativeRoot})}let p=ft({portableState:t,projectRoot:e.paths.projectRoot,branch:$(e.paths.projectRoot).currentBranch});return await Xm.mkdir(Qm.dirname(Vt(e.paths,t.name)),{recursive:!0}),await rt(a,p,{containedRoot:e.paths.runtimeDir}),await Mo({paths:e.paths,state:t}),{state:t,local:p,action:u?"reverify":"resume-stable-boundary",reason:s,message:u?"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.`}})}Fr();xo();Gr();ke();import{accessSync as Cx,constants as Rx,promises as Ax}from"node:fs";import it from"node:path";Y();ko();Wr();xo();var bx=6e4,Q=class extends Error{constructor(r,i,n){super(r,n);this.pullRequest=i;this.name="NativePullRequestFinishError"}pullRequest};function fu(e,t){try{return dr("gh",t,{cwd:e,timeoutMs:bx}).trim()}catch(r){throw new Error(`gh ${t.join(" ")} failed: ${r.message}`,{cause:r})}}function hu(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a JSON object`);return e}function pu(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} must be valid JSON`,{cause:r})}}function ev(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Nr(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string`);return e}function tv(e,t){let r=Nr(e,t),i;try{i=new URL(r)}catch(n){throw new Error(`${t} must be an absolute HTTP URL`,{cause:n})}if(i.protocol!=="https:"&&i.protocol!=="http:")throw new Error(`${t} must be an absolute HTTP URL`);return r}function Ko(e,t){let r=Nr(e,t);if(!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/iu.test(r))throw new Error(`${t} must be a Git object ID`);return r.toLowerCase()}function rv(e,t){let r=hu(e,t);if(Nr(r.state,`${t}.state`)!=="OPEN")throw new Error(`${t}.state must be OPEN`);return{number:ev(r.number,`${t}.number`),url:tv(r.url,`${t}.url`),baseBranch:Nr(r.baseRefName,`${t}.baseRefName`),headBranch:Nr(r.headRefName,`${t}.headRefName`),headSha:Ko(r.headRefOid,`${t}.headRefOid`),state:"OPEN"}}function kx(e){let t=hu(e,"pull request finish provider output.pullRequest");return{number:ev(t.number,"pull request finish provider output.pullRequest.number"),url:tv(t.url,"pull request finish provider output.pullRequest.url"),baseBranch:Nr(t.baseBranch,"pull request finish provider output.pullRequest.baseBranch"),headBranch:Nr(t.headBranch,"pull request finish provider output.pullRequest.headBranch"),headSha:Ko(t.headSha,"pull request finish provider output.pullRequest.headSha")}}function Sx(e){let t=hu(pu(e,"pull request finish provider output"),"pull request finish provider output");if(t.schema!=="comet.native.pull-request-finish-result.v1")throw new Error("pull request finish provider output.schema must be comet.native.pull-request-finish-result.v1");if(t.disposition!=="created"&&t.disposition!=="reused")throw new Error("pull request finish provider output.disposition must be created or reused");if(t.remoteVerified!==!0)throw new Error("pull request finish provider did not confirm repository-owned remote verification");let r=kx(t.pullRequest);return{schema:"comet.native.pull-request-finish-result.v1",disposition:t.disposition,remoteVerified:!0,pullRequest:r}}function mu(e){let t=fu(e.projectRoot,["pr","list","--state","open","--base",e.baseBranch,"--head",e.headBranch,"--limit","2","--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=pu(t,"gh pr list output");if(!Array.isArray(r))throw new Error("gh pr list output must be a JSON array");if(r.length>1)throw new Error(`Multiple open pull requests match ${e.headBranch} -> ${e.baseBranch}`);return r.length===0?null:rv(r[0],"gh pr list output[0]")}function iv(e){let t=fu(e.projectRoot,["pr","view",String(e.pullRequest.number),"--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=rv(pu(t,"gh pr view output"),"gh pr view output"),i=Ko(e.headSha,"Native Archive head SHA");if(r.number!==e.pullRequest.number||r.url!==e.pullRequest.url)throw new Q("Pull request provider result does not match the pull request observed from GitHub",r);if(r.baseBranch!==e.baseBranch)throw new Q(`Pull request base branch mismatch: expected ${e.baseBranch}, got ${r.baseBranch}`,r);if(r.headBranch!==e.headBranch)throw new Q(`Pull request head branch mismatch: expected ${e.headBranch}, got ${r.headBranch}`,r);if(r.headSha!==i)throw new Q(`Pull request head SHA mismatch: expected ${i}, got ${r.headSha}`,r);return r}function Uo(e){try{return mu(e)}catch{return null}}function Ex(e){return JSON.stringify({schema:"comet.native.pull-request-finish-input.v1",projectRoot:e.projectRoot,change:{name:e.changeName,branch:e.headBranch,headSha:e.headSha},target:{branch:e.baseBranch},remote:e.remote,transactionId:e.transactionId,existingPullRequest:e.existingPullRequest},null,2)}function Px(e){let t=e.existingPullRequest,r=t?"reused":"created";if(!t)try{let a=fu(e.projectRoot,["pr","create","--base",e.baseBranch,"--head",e.headBranch,"--fill"]).split(/\r?\n/u).map(o=>o.trim()).find(o=>/^https?:\/\//u.test(o));if(!a)throw new Error("GitHub CLI did not return a pull request URL");if(t=mu(e),!t)throw new Error("GitHub CLI created a pull request that could not be observed uniquely");if(t.url!==a)throw new Q("GitHub CLI returned a pull request URL that does not match the remotely observed pull request",t)}catch(n){if(n instanceof Q)throw n;let a=Uo(e);if(!a)throw new Q(n.message,null,{cause:n});t=a,r="reused"}let i;try{i=iv({...e,pullRequest:t})}catch(n){throw n instanceof Q?n:new Q(`Final GitHub pull request verification failed: ${n.message}`,t,{cause:n})}return{provider:"github-fill",disposition:r,pullRequest:i,remoteVerified:!0}}function xx(e){let[t,...r]=e.config.command,i;try{let o=dr(t,r,{cwd:e.projectRoot,timeoutMs:e.config.timeout_ms,input:`${Ex(e)}
|
|
211
|
-
`}).trim();i=Sx(o)}catch(o){if(o instanceof Q)throw o;let s=Uo(e)??e.existingPullRequest;throw new Q(`Repository pull request finish provider failed: ${o.message}`,s,{cause:o})}let n={...i.pullRequest,state:"OPEN"};if(n.baseBranch!==e.baseBranch||n.headBranch!==e.headBranch||n.headSha!==Ko(e.headSha,"Native Archive head SHA")){let o=Uo(e)??e.existingPullRequest;throw new Q("Repository pull request finish provider returned a pull request outside the authorized base, head, or head SHA",o)}let a;try{a=iv({...e,pullRequest:n})}catch(o){if(o instanceof Q)throw o;let s=Uo(e)??e.existingPullRequest??n;throw new Q(`Final repository pull request verification failed: ${o.message}`,s,{cause:o})}return{provider:"repository-command",disposition:i.disposition,pullRequest:a,remoteVerified:!0}}function nv(e){let t=mu(e);return e.config?xx({...e,existingPullRequest:t,config:e.config}):Px({...e,existingPullRequest:t})}var xn=class extends Error{constructor(r){super(r.message??"Native workspace finish is blocked");this.result=r;this.name="NativeWorkspaceFinishError"}result},gt=class extends Error{constructor(r,i,n="Native workspace finish is blocked"){super(`${n}; remaining paths: ${r.join(", ")}`);this.paths=r;this.workspaceRoot=i;this.name="NativeWorkspaceFinishPreparationError"}paths;workspaceRoot};function vu(e,t){let r=
|
|
210
|
+
`}function CP(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 Nn(e){let t;try{t=await kP.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=CP(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function bn(e){await de(e.file,xP(e.state,e.supervisor))}B();Zt();Xr();Ce();var xm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,HP="comet-state.yaml",DP="state.json",tH=Ta("en");function Ie(e,t){if(!xm.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=mt.join(e.changesDir,t);if(!J(e.changesDir,r))throw new Error("Native change path escaped");return r}function be(e,t){return mt.join(Ie(e,t),HP)}function Vt(e,t){return mt.join(xe(e,t),DP)}async function kn(e,t){try{let r=await vr.readFile(be(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Ql(e){return $(e).currentBranch}async function Ve(e,t){return te(be(e,t))}async function Zl(e){let t=await Ht({file:be(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=mt.join(Ie(e.paths,t.name),"verification.md");await V(e.paths.nativeRoot,r),await vr.rm(r,{force:!0})}return t}async function BP(e){let t=Ie(e.paths,e.state.name),r=mt.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await vr.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(!xm.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=mt.join(t,...s.split("/")),l=await vr.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let f=mt.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let u=await vr.lstat(f);if(!u.isFile()||u.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(u){if(u.code!=="ENOENT")throw u}a.push({capability:o.name,operation:d,source:s})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function LP(e){let t=Ie(e.paths,e.state.name),r=await F({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(Mp(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let a of e.specChanges){if(a.source===null){n.push({...a,contentHash:null});continue}let o=await F({root:t,ref:a.source,maxBytes:null,includeHash:!1});i.push({capability:a.capability,source:o.ref,markdown:o.text}),n.push({...a,contentHash:H("comet.native.shape-artifact-content.v1",o.text)})}return{acceptance:Za({briefMarkdown:r.text,specs:i}),formalHash:H("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:H("comet.native.shape-artifact-content.v1",r.text)},specs:n})}}function qP(e){return H("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function eu(e){let t=await BP(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,f)=>{let d=e.state.spec_changes[f];return d!==void 0&&l.capability===d.capability&&l.source===d.source&&(l.operation===d.operation||r?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await LP({...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:f})=>({source:l,text:f}));if(!ip(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await mr({changeDir:Ie(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:$o({...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&&qP({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?Oo({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 FP(e){let t=await Ve(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 Ho({paths:e.paths,state:t});if(!i||!i.confirmed||!i.allDone)return{state:t,parentAdvance:{...r,blocker:i&&!i.confirmed?"Supervisor child declarations require Shape confirmation":null}};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{state:t,parentAdvance:{...r,blocker:"Native parent verification failed; add and confirm a repair child"}};let n=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选需要独立代码审查后再进入验证":"All Children are complete; the Supervisor parent candidate needs an independent code review before verification.";return{state:t,parentAdvance:{...r,message:n}}}async function Cm(e){let t=await zl({paths:e.childPaths,childName:e.childState.name,targetBranch:e.childState.workspace.target_branch});if(!t.candidate)return{parentState:null,parentAdvance:{trigger:"v1-archive",parent:null,advanced:!1,message:null,blocker:t.blockers.length>0?t.blockers.join("; "):null}};let r=await FP({paths:t.candidate.paths,name:t.candidate.state.name,trigger:"v1-archive"});return{parentState:r.state,parentAdvance:r.parentAdvance}}async function Rm(e){let t=await Ve(e.paths,e.name),r=await Dt(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 Fe(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 vr.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=sm(n);if(i||a.stateVersion!==n.stateVersion){let o=await VP({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 vr.rm(i.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await fr(e.paths,cm(n,t)),{state:t,action:"recorded-final-verification"}}async function Am(e){return re(e.paths,`set portable workspace finish ${e.name}`,async()=>{let t=await Ve(e.paths,e.name);if(t.workspace.isolation==="current")throw new Error("Native current-workspace isolation does not accept a finish action");let r={...t,state_version:t.state_version+1,workspace:{...t.workspace,finish:e.finish}},i=await Zl({paths:e.paths,previous:t,next:r});return await it(Vt(e.paths,t.name),ht({portableState:i,projectRoot:e.paths.projectRoot,branch:Ql(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i.verification!==null&&await bn({file:mt.join(Ie(e.paths,t.name),"verification.md"),state:i}),i})}async function _m(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...Ot(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:ut(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await Zl({paths:e.paths,previous:t,next:i});return await it(Vt(e.paths,t.name),ht({portableState:n,projectRoot:e.paths.projectRoot,branch:Ql(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function VP(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={...Ot(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:ut(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 Zl({paths:e.paths,previous:t,next:i});return await it(Vt(e.paths,t.name),ht({portableState:n,projectRoot:e.paths.projectRoot,branch:Ql(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Mo(e){if(e.state.verification===null)return"not-applicable";let t=mt.join(Ie(e.paths,e.state.name),"verification.md");return await Nn({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await bn({file:t,state:e.state}),"rebuilt")}wn();Xe();Fr();B();Fi();import{promises as MP}from"fs";import WP from"path";var tu="comet.selection.v2",zP=16*1024;function Wo(e){return WP.join(e,".comet","current-change.json")}function JP(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Im(e){return e===null||typeof e=="string"}function GP(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!JP(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!Im(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:tu,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==tu)throw new Error(`current change selection schema must be ${tu}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Im(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function Tm(e){let t;try{let i=Wo(e),{bytes:n}=await rr(i,zP,{label:"current change selection"});t=n.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...GP(t)}}async function jm(e){await MP.rm(Wo(e),{force:!0})}async function $m(e,t,r){let i=await Tm(e);return i.status!=="selected"||i.selection.workflow!==t||i.selection.change!==r?!1:(await jm(e),!0)}Y();Ce();me();var hH=16*1024;function ru(e){return Wo(e.projectRoot)}async function zo(e,t){return await Wi(e.projectRoot),$m(e.projectRoot,"native",t)}var En=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}};function iu(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function nu(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let r=X.join(e.archiveDir,t);if(!J(e.archiveDir,r))throw new Error("Native Archive path escaped");return r}async function Sn(e){try{return await ie.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Om(e,t){let r=X.normalize(X.resolve(e)),i=X.normalize(X.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}async function Hm(e,t){let r;try{r=await ie.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let i=[];for(let n of r){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=X.join(e.archiveDir,n.name);try{let o=await te(X.join(a,"comet-state.yaml"));o.name===t&&i.push({dir:a,state:o})}catch{}}if(i.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return i[0]??null}async function ou(e,t){let r=await Dt(e,{kind:"archive",change:t});return r?.kind==="archive"?r.journal:null}async function Dm(e,t){return await ou(e,t)!==null||await Hm(e,t)!==null}async function gr(e,t){await ie.mkdir(e.transactionsDir,{recursive:!0}),await U(sr(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Bm(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let r=ge(e.paths.projectRoot);r.some(a=>Om(a,e.paths.projectRoot))||r.push(e.paths.projectRoot);let i=[];for(let a of r){let o=await ye(a);if(!o)continue;let s=await lt(a,o.native.artifact_root);i.some(c=>Om(c.changesDir,s.changesDir))||i.push(s)}i.length===0&&i.push(e.paths);let n=new Set;for(let a of i){let o;try{o=await ie.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let c=await te(X.join(a.changesDir,s.name,"comet-state.yaml"));c.status!=="done"&&c.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.name)}catch{let c=await No(a,s.name).catch(()=>null);c?.state&&c.state.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function KP(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function YP(e){let t=X.join(e.paths.specsDir,e.change.capability),r=X.join(t,"spec.md");if(!J(e.paths.specsDir,r))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await ie.lstat(e.paths.specsDir)}catch(c){if(c.code==="ENOENT")return;throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await ie.lstat(t)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[o,s]=await Promise.all([ie.realpath(e.paths.specsDir),ie.realpath(t)]);if(!J(o,s))throw new Error("Native canonical capability path escaped");try{let c=await ie.lstat(r);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await ie.unlink(r)}catch(c){if(c.code!=="ENOENT")throw c}await ie.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let i=X.join(Ie(e.paths,e.state.name),e.change.source);await de(i,e.change.content,{containedRoot:e.paths.nativeRoot}),await ie.mkdir(t,{recursive:!0}),await de(r,e.change.content,{containedRoot:e.paths.nativeRoot})}function su(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function XP(e,t){let r=Ie(e,t.name),i=[];for(let n of t.spec_changes){if(n.source===null){i.push({...n,content:null});continue}let a=await F({root:r,ref:n.source,maxBytes:null,includeHash:!1});i.push({...n,content:a.text})}return i}function QP(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(su(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function au(e,t){for(let r of t.spec_changes.slice(0,t.next_spec_index)){let i=`${r.capability}/spec.md`,n=X.join(e.specsDir,i);if(r.operation==="remove"){if(!await Sn(n))continue}else try{if((await F({root:e.specsDir,ref:i,maxBytes:null,includeHash:!1})).text===r.content)continue}catch(a){if(a.code!=="ENOENT")throw a}throw new Error(`Canonical Spec ${i} changed after Archive applied it; preserve the concurrent edit and resolve it before resuming Archive`)}}async function cu(e){let t=await Ve(e.paths,e.name),r=[];try{su(t)}catch(o){r.push(o.message)}let i=await ou(e.paths,e.name);if(i)try{await au(e.paths,i)}catch(o){r.push(o.message)}if(i===null)try{let o=await eu({paths:e.paths,state:t});o.drifted&&r.push(o.reason??"Native confirmed requirements changed")}catch(o){r.push(o.message)}let n=t.verification===null?"missing":await Nn({file:X.join(Ie(e.paths,t.name),"verification.md"),stateVersion:t.state_version});n!=="aligned"&&r.push(`verification.md is ${n}`);let a=await Bm({paths:e.paths,state:t});return a.length>0&&r.push(`capabilities are also declared by: ${a.join(", ")}`),{ready:r.length===0,blockers:r,capabilityPeers:a,archiveDir:nu(e.paths,iu(t)),stateVersion:t.state_version}}async function Lm(e){return re(e.paths,`archive portable change ${e.name}`,async()=>{let t=KP(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let r=await ou(e.paths,e.name),i=Ie(e.paths,e.name),n=await Sn(i),a=n?null:await Hm(e.paths,e.name),o;if(n)o=await Ve(e.paths,e.name);else if(r)o=await te(X.join(nu(e.paths,r.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);let s=await Fe(e.paths,e.name);if(n&&!o.archived&&r===null){let u=await eu({paths:e.paths,state:o});if(u.drifted){let p=u.reason??"Native confirmed requirements changed";throw await _m({paths:e.paths,state:o,reason:p}),new Error(`${p}; Native change returned to Shape and requires confirmation`)}}if(n&&!o.archived&&s?.finalVerification.status==="pending"&&o.verification_result==="pass"){let u=await Rm({paths:e.paths,name:e.name});if(o=u.state,u.action==="rerun-final-verification")throw new Error("Native Supervisor final verification must be rerun for the current integration commit");u.action==="recorded-final-verification"&&(s=await Fe(e.paths,e.name))}let c=nu(e.paths,r?.archive_ref??iu(o)),l=await Sn(c);if(r&&QP(r,o),n&&l)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!r&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await zo(e.paths,o.name),await ie.rm(xe(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!r){if(!o.archived)su(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let u=await Bm({paths:e.paths,state:o});if(!o.archived&&u.length>0&&t!==o.name)throw new En(u);r={schema:so,id:UP(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:iu(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await XP(e.paths,o),created_at:new Date().toISOString()},await gr(e.paths,r)}if(!n&&l&&r.status==="report-aligned")r={...r,status:"moved"},await gr(e.paths,r);else if(!n&&l&&r.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${r.status}; doctor intervention is required`);await au(e.paths,r);let f=r.spec_changes.slice(0,r.next_spec_index).map(({capability:u})=>X.relative(e.paths.projectRoot,X.join(e.paths.specsDir,u,"spec.md")).replaceAll("\\","/")),d=!1;if(r.status==="prepared"&&s&&!o.archived&&(s=(await gn({paths:e.paths,state:s,archiveOwnedPaths:f})).state,d=!0),r.status==="prepared"){for(let u=r.next_spec_index;u<r.spec_changes.length;u+=1)await YP({paths:e.paths,state:o,change:r.spec_changes[u]}),r={...r,next_spec_index:u+1},await gr(e.paths,r),await e.hooks?.afterSpecApplied?.(u);r={...r,status:"specs-applied"},await gr(e.paths,r)}if(await au(e.paths,r),r.status==="specs-applied"){if(s&&!o.archived&&!d&&(s=(await gn({paths:e.paths,state:s,archiveOwnedPaths:f})).state,d=!0),!o.archived){let u={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await Ht({file:be(e.paths,o.name),expectedStateVersion:o.state_version,next:u,containedRoot:e.paths.nativeRoot})}r={...r,status:"state-finalized"},await gr(e.paths,r),await e.hooks?.afterFinalState?.()}if(r.status==="state-finalized"){let u=await Sn(i)?i:c;if(await bn({file:X.join(u,"verification.md"),state:o,...s?{supervisor:s}:{}}),await Nn({file:X.join(u,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");r={...r,status:"report-aligned"},await gr(e.paths,r),s&&!d&&(await gn({paths:e.paths,state:s,archiveOwnedPaths:f}),d=!0),await e.hooks?.afterReportAligned?.()}if(r.status==="report-aligned"){if(s&&!d&&await gn({paths:e.paths,state:s,archiveOwnedPaths:f}),await ie.mkdir(e.paths.archiveDir,{recursive:!0}),await Sn(c))throw new Error(`Native Archive target already exists: ${c}`);await ie.rename(i,c),r={...r,status:"moved"},await gr(e.paths,r),await e.hooks?.afterMove?.()}return r.status==="moved"&&(await zo(e.paths,o.name),await ie.rm(xe(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await ie.rm(sr(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:c,transactionId:r.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}Ui();function Te(e,t,r){return e.language==="zh-CN"?r:t}function ZP(e,t){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:Te(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:Te(e,"Reply A or B","回复 A 或 B"),agentInstruction:Te(e,"Relay the two coordination choices and wait for the user decision. After the user chooses, execute the prepare-shape-confirmation commandArgs with the selected --coordination-mode. Do not combine mode selection with final confirmation; confirmation of the complete Shape is a separate await-user step.","转述这两个推进方式并等待用户选择。用户选择后,使用对应的 --coordination-mode 执行 prepare-shape-confirmation 的完整 commandArgs;不要把推进方式选择和最终确认合并执行,完整 Shape 的确认是后续单独的 await-user 步骤。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return r(Te(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return r(Te(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:i})=>i==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{required:!0,message:Te(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:Te(e,"Accept the result","接受结果"),agentInstruction:Te(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")}:r(Te(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 ex(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 tx(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:Te(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Te(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Fm(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function wr(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function rx(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function qm(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function ix(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function nx(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 Mt(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Fm({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[wr("summary","--summary"),rx(e.name,e.flag)]}}function lu(e){return[Mt({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Mt({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function vt(e,t,r={}){let i=ix(t)&&e.coordination_mode===void 0,n=ZP(e,i),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[wr("summary","--summary")],commandAlternatives:[Mt({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:[wr("summary","--summary")],commandAlternatives:[Mt({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...lu({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:[wr("summary","--summary")],commandAlternatives:[Mt({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Mt({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:[wr("summary","--summary")],commandAlternatives:[Mt({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...lu({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:[wr("summary","--summary")],commandAlternatives:lu({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?Fm({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:nx({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?[qm("coordination-mode","--coordination-mode",np)]:[]],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:f})=>f==="verified");if(s)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}}],runnerAction:o("none")};let c=t.children.some(({status:f})=>f==="blocked"||f==="needs-reverify"),l=t.children.some(({status:f})=>f==="ready"||f==="active");return{...a,disposition:c&&!l?"blocked":"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:c&&!l?["resolve-child-blocker"]:["ready-children"],inputOptions:[wr("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${Te(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:c?[l]:[]}}],runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;return s==="blocked"?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:s==="preview"?r.archiveBlockers&&r.archiveBlockers.length>0?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}:l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[qm("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...tx(e)],userCommunication:ex(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Mt({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")}}ke();q();Ee();Y();me();dl();Fr();eo();import{randomUUID as ax}from"node:crypto";import{promises as Pn}from"node:fs";import ox from"node:path";Xe();B();Wr();var Vm=["evidence.md","repair.md","archive.md","checkpoint.md"],sx="verification.md";async function cx(e,t){let r=await Dt(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function Mm(e,t){await Pn.mkdir(e.transactionsDir,{recursive:!0}),await U(sr(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Wm(e,t,r={}){let i=r.removeVerificationReport===!1?Vm:[...Vm,sx];await Promise.all([Pn.rm(xe(e,t),{recursive:!0,force:!0}),Pn.rm(Zc(e,t),{recursive:!0,force:!0}),...i.map(n=>Pn.rm(ox.join(Ne(e,t),n),{force:!0}))])}async function zm(e,t){await it(Vt(e,t.name),ht({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function Jm(e,t){try{let r=await on(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 Gm(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=$(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 lx(e){let t=Ne(e.paths,e.state.name),r=await F({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 F({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Za({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Um(e,t){let r=await No(e,t);if(r.status==="runtime-incompatible")throw new Lt(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function Km(e){return re(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await cx(e.paths,e.name),r=await kn(e.paths,e.name)?await te(be(e.paths,e.name)):null;if(!t&&r)return await Wm(e.paths,e.name,{removeVerificationReport:!1}),await zm(e.paths,r),r;let i=null,n=null;for(t||(i=await Um(e.paths,e.name),n=await Jm(e.paths,e.name),Gm(e.paths,n),t={schema:oo,id:ax(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Mm(e.paths,t));;){let a=lp(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await Um(e.paths,e.name),n??=await Jm(e.paths,e.name),Gm(e.paths,n),r=cp({state:i,acceptance:await lx({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await Yi(be(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Wm(e.paths,e.name):a.action==="commit-transaction"&&(r??=await te(be(e.paths,e.name)),await zm(e.paths,r)),t={...t,status:a.nextStatus},await Mm(e.paths,t)}return await Pn.rm(sr(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??te(be(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}ke();import{promises as Xm}from"node:fs";import Qm from"node:path";me();Io();se();wn();import{promises as uu}from"node:fs";import ux from"node:path";var dx=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),fx=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),hx=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task"]),px=new Set(["status","summary"]);function Jo(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Go(e,t,r){let i=new Set(Object.keys(e)),n=[...t].filter(o=>!i.has(o)),a=[...i].filter(o=>!t.has(o));return n.length===0&&a.length===0?null:`${r} fields must be exact (missing: ${n.join(", ")||"none"}; unexpected: ${a.join(", ")||"none"})`}function mx(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function yr(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function vx(e,t,r,i){let n=Jo(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=Go(n,dx,"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=Jo(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=Go(o,fx,"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=Jo(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=Go(c,px,"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[f,d]of n.children.entries()){let u=Jo(d,`Native Supervisor child ${f}`);if(!u)return`Native Supervisor child ${f} must be an object`;let{acceptanceScope:p,contractHash:g,...h}=u,m=Go(h,hx,`Native Supervisor child ${f}`);if(m)return m;let v=r.children[f],y=v.covers.length>0?v.covers.map(w=>({id:w,source:r.acceptance_index?.[w]?.source??"brief.md",text:r.acceptance_index?.[w]?.text??w})):[{id:`child:${v.name}`,source:"children.yaml",text:v.summary??v.name}];if(p!==void 0&&JSON.stringify(p)!==JSON.stringify(y)||g!==void 0&&g!==H("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${v.name} acceptance scope does not match the legacy contract`;if(u.name!==v.name||u.summary!==v.summary||!mx(u.dependsOn,v.depends_on))return`Native Supervisor child ${v.name} does not match the legacy children contract`;let b=v.depends_on.length===0?"ready":"pending";if(u.status!==b)return`Native Supervisor child ${v.name} has progressed beyond its initial ${b} status`;if(u.baseCommit!==null||u.candidateCommit!==null||u.verifiedCommit!==null||u.integrationCommit!==null||u.verification!==null||u.blocker!==null||u.projectRoot!==null||u.task!==null)return`Native Supervisor child ${v.name} contains execution progress`;if(!Array.isArray(u.checks)||u.checks.length!==0)return`Native Supervisor child ${v.name} contains integration checks`}return null}async function du(e){let t=Ao(e.paths,e.state.name),r;try{let c=await uu.lstat(t);if(!c.isFile()||c.isSymbolicLink())return yr(t,"","Native Supervisor overlay is not a regular file");r=await uu.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:yr(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return yr(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=ux.join(e.paths.changesDir,e.state.name),a;try{a=await mr({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return yr(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 Fe(e.paths,e.state.name)}catch(c){return yr(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return yr(t,r,"Native Supervisor overlay disappeared during inspection");let s=vx(i,e.state,a.contract,o);return s?yr(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 Ym(e){let t=await du({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 uu.rm(t.file,{force:!1})}Xe();Xi();function gx(e,t){let r=$(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 wx(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function yx(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:Ot(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:ut(t),completed_at:i});return ne({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?wx(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 Nx(e){try{let t=await Yl(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 Zm(e){return re(e.paths,`recover portable change ${e.name}`,async()=>{let t=await Ve(e.paths,e.name);if(t.status==="done")return await Mo({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=gx(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await du({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 Ym({paths:e.paths,state:t,expected:i}),n=!0);let a=Vt(e.paths,e.name),o=await Nx(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason;if(s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed"&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(g=>g.status==="planned"||g.status==="running"?{...g,status:"interrupted"}:g)},await it(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await Mo({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(g=>g.status==="interrupted"&&!g.repeatable):void 0;if(l){let g=Jl({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Ht({file:be(e.paths,t.name),expectedStateVersion:t.state_version,next:g,containedRoot:e.paths.nativeRoot}),await Xm.rm(Qm.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let h=ht({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await it(a,h,{containedRoot:e.paths.runtimeDir}),{state:t,local:h,action:"resume-stable-boundary",reason:s,message:`Native check ${l.id} was not repeatable; the change returned to Build for a new candidate.`}}let f=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",d=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",u=f||d;if(u){let g=yx(t,d?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",d);t=await Ht({file:be(e.paths,t.name),expectedStateVersion:t.state_version,next:g,containedRoot:e.paths.nativeRoot})}let p=ht({portableState:t,projectRoot:e.paths.projectRoot,branch:$(e.paths.projectRoot).currentBranch});return await Xm.mkdir(Qm.dirname(Vt(e.paths,t.name)),{recursive:!0}),await it(a,p,{containedRoot:e.paths.runtimeDir}),await Mo({paths:e.paths,state:t}),{state:t,local:p,action:u?"reverify":"resume-stable-boundary",reason:s,message:u?"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.`}})}Fr();xo();Gr();ke();import{accessSync as Cx,constants as Rx,promises as Ax}from"node:fs";import nt from"node:path";Y();ko();Wr();xo();var bx=6e4,Q=class extends Error{constructor(r,i,n){super(r,n);this.pullRequest=i;this.name="NativePullRequestFinishError"}pullRequest};function fu(e,t){try{return dr("gh",t,{cwd:e,timeoutMs:bx}).trim()}catch(r){throw new Error(`gh ${t.join(" ")} failed: ${r.message}`,{cause:r})}}function hu(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a JSON object`);return e}function pu(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} must be valid JSON`,{cause:r})}}function ev(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Nr(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string`);return e}function tv(e,t){let r=Nr(e,t),i;try{i=new URL(r)}catch(n){throw new Error(`${t} must be an absolute HTTP URL`,{cause:n})}if(i.protocol!=="https:"&&i.protocol!=="http:")throw new Error(`${t} must be an absolute HTTP URL`);return r}function Ko(e,t){let r=Nr(e,t);if(!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/iu.test(r))throw new Error(`${t} must be a Git object ID`);return r.toLowerCase()}function rv(e,t){let r=hu(e,t);if(Nr(r.state,`${t}.state`)!=="OPEN")throw new Error(`${t}.state must be OPEN`);return{number:ev(r.number,`${t}.number`),url:tv(r.url,`${t}.url`),baseBranch:Nr(r.baseRefName,`${t}.baseRefName`),headBranch:Nr(r.headRefName,`${t}.headRefName`),headSha:Ko(r.headRefOid,`${t}.headRefOid`),state:"OPEN"}}function kx(e){let t=hu(e,"pull request finish provider output.pullRequest");return{number:ev(t.number,"pull request finish provider output.pullRequest.number"),url:tv(t.url,"pull request finish provider output.pullRequest.url"),baseBranch:Nr(t.baseBranch,"pull request finish provider output.pullRequest.baseBranch"),headBranch:Nr(t.headBranch,"pull request finish provider output.pullRequest.headBranch"),headSha:Ko(t.headSha,"pull request finish provider output.pullRequest.headSha")}}function Sx(e){let t=hu(pu(e,"pull request finish provider output"),"pull request finish provider output");if(t.schema!=="comet.native.pull-request-finish-result.v1")throw new Error("pull request finish provider output.schema must be comet.native.pull-request-finish-result.v1");if(t.disposition!=="created"&&t.disposition!=="reused")throw new Error("pull request finish provider output.disposition must be created or reused");if(t.remoteVerified!==!0)throw new Error("pull request finish provider did not confirm repository-owned remote verification");let r=kx(t.pullRequest);return{schema:"comet.native.pull-request-finish-result.v1",disposition:t.disposition,remoteVerified:!0,pullRequest:r}}function mu(e){let t=fu(e.projectRoot,["pr","list","--state","open","--base",e.baseBranch,"--head",e.headBranch,"--limit","2","--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=pu(t,"gh pr list output");if(!Array.isArray(r))throw new Error("gh pr list output must be a JSON array");if(r.length>1)throw new Error(`Multiple open pull requests match ${e.headBranch} -> ${e.baseBranch}`);return r.length===0?null:rv(r[0],"gh pr list output[0]")}function iv(e){let t=fu(e.projectRoot,["pr","view",String(e.pullRequest.number),"--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=rv(pu(t,"gh pr view output"),"gh pr view output"),i=Ko(e.headSha,"Native Archive head SHA");if(r.number!==e.pullRequest.number||r.url!==e.pullRequest.url)throw new Q("Pull request provider result does not match the pull request observed from GitHub",r);if(r.baseBranch!==e.baseBranch)throw new Q(`Pull request base branch mismatch: expected ${e.baseBranch}, got ${r.baseBranch}`,r);if(r.headBranch!==e.headBranch)throw new Q(`Pull request head branch mismatch: expected ${e.headBranch}, got ${r.headBranch}`,r);if(r.headSha!==i)throw new Q(`Pull request head SHA mismatch: expected ${i}, got ${r.headSha}`,r);return r}function Uo(e){try{return mu(e)}catch{return null}}function Ex(e){return JSON.stringify({schema:"comet.native.pull-request-finish-input.v1",projectRoot:e.projectRoot,change:{name:e.changeName,branch:e.headBranch,headSha:e.headSha},target:{branch:e.baseBranch},remote:e.remote,transactionId:e.transactionId,existingPullRequest:e.existingPullRequest},null,2)}function Px(e){let t=e.existingPullRequest,r=t?"reused":"created";if(!t)try{let a=fu(e.projectRoot,["pr","create","--base",e.baseBranch,"--head",e.headBranch,"--fill"]).split(/\r?\n/u).map(o=>o.trim()).find(o=>/^https?:\/\//u.test(o));if(!a)throw new Error("GitHub CLI did not return a pull request URL");if(t=mu(e),!t)throw new Error("GitHub CLI created a pull request that could not be observed uniquely");if(t.url!==a)throw new Q("GitHub CLI returned a pull request URL that does not match the remotely observed pull request",t)}catch(n){if(n instanceof Q)throw n;let a=Uo(e);if(!a)throw new Q(n.message,null,{cause:n});t=a,r="reused"}let i;try{i=iv({...e,pullRequest:t})}catch(n){throw n instanceof Q?n:new Q(`Final GitHub pull request verification failed: ${n.message}`,t,{cause:n})}return{provider:"github-fill",disposition:r,pullRequest:i,remoteVerified:!0}}function xx(e){let[t,...r]=e.config.command,i;try{let o=dr(t,r,{cwd:e.projectRoot,timeoutMs:e.config.timeout_ms,input:`${Ex(e)}
|
|
211
|
+
`}).trim();i=Sx(o)}catch(o){if(o instanceof Q)throw o;let s=Uo(e)??e.existingPullRequest;throw new Q(`Repository pull request finish provider failed: ${o.message}`,s,{cause:o})}let n={...i.pullRequest,state:"OPEN"};if(n.baseBranch!==e.baseBranch||n.headBranch!==e.headBranch||n.headSha!==Ko(e.headSha,"Native Archive head SHA")){let o=Uo(e)??e.existingPullRequest;throw new Q("Repository pull request finish provider returned a pull request outside the authorized base, head, or head SHA",o)}let a;try{a=iv({...e,pullRequest:n})}catch(o){if(o instanceof Q)throw o;let s=Uo(e)??e.existingPullRequest??n;throw new Q(`Final repository pull request verification failed: ${o.message}`,s,{cause:o})}return{provider:"repository-command",disposition:i.disposition,pullRequest:a,remoteVerified:!0}}function nv(e){let t=mu(e);return e.config?xx({...e,existingPullRequest:t,config:e.config}):Px({...e,existingPullRequest:t})}var xn=class extends Error{constructor(r){super(r.message??"Native workspace finish is blocked");this.result=r;this.name="NativeWorkspaceFinishError"}result},gt=class extends Error{constructor(r,i,n="Native workspace finish is blocked"){super(`${n}; remaining paths: ${r.join(", ")}`);this.paths=r;this.workspaceRoot=i;this.name="NativeWorkspaceFinishPreparationError"}paths;workspaceRoot};function vu(e,t){let r=nt.relative(e,t);return r===""||!nt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${nt.sep}`)}function Wt(e,t){let r=nt.relative(e,t).replaceAll("\\","/");if(!r||r===".."||r.startsWith("../")||nt.isAbsolute(r))throw new Error(`Native workspace finish path escaped the project: ${t}`);return r}function cv(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function av(e,t,r,i=[]){let n=[...Ur(e.projectRoot)?[".comet/config.yaml"]:[],Wt(e.projectRoot,Ne(e,t.name)),Wt(e.projectRoot,ru(e))];r&&n.push(Wt(e.projectRoot,r));for(let a of r?t.spec_changes:i)n.push(Wt(e.projectRoot,un(e,a.capability)));return n}function ov(e,t){let r=Jr(e).filter(i=>!cv(i,t));if(r.length>0)throw new gt(r,e)}function _x(e,t){return t.map(r=>nt.resolve(e,...r.split("/")))}function Ix(e){let t=Jr(e).filter(r=>!(r===".comet/config.yaml"&&Ur(e)));if(t.length>0)throw new gt(_x(e,t),e,`Native merge target worktree is not clean: ${e}`)}function lv(e){return e.split("\0").filter(Boolean)}function Tx(e,t){return lv(C(e,["ls-files","-z","--",t]))}function jx(e,t){return lv(C(e,["ls-files","--others","--exclude-standard","-z","--",t]))}function sv(e){try{if(C(e,["config","--get","user.name"])&&C(e,["config","--get","user.email"]))return}catch{}throw new Error("Native workspace finish requires configured Git user.name and user.email")}function $x(e,t){for(let r of ge(e))if($(r).currentBranch===t)return r;return null}function Ox(e,t){try{dr(e,t,{timeoutMs:1e4})}catch(r){throw new Error(`${e} is required for the selected Native workspace finish`,{cause:r})}}function Hx(e,t){if(!t)return;let r=t.command[0];try{if(nt.posix.isAbsolute(r)||nt.win32.isAbsolute(r))throw new Error("configured executable must not be an absolute path");if(/[\\/]/u.test(r)){let n=nt.resolve(e,r);if(!vu(e,n))throw new Error("configured executable escapes the project root");Cx(n,Rx.X_OK);return}dr(process.platform==="win32"?"where":"which",[r],{timeoutMs:1e4})}catch(i){throw new Error(`Configured Native pull request finish executable is not available: ${r}`,{cause:i})}}async function Yo(e){let{paths:t,state:r}=e,i=r.workspace,n=$(t.projectRoot);if(i.isolation==="current"){if(!n.isGitWorktree)return null;if(!n.primaryWorktreeRoot||!n.currentBranch)throw new Error("Native current workspace finish requires a registered Git branch");sv(t.projectRoot);let c=av(t,r,e.archiveDir,e.appliedSpecChanges);return ov(t.projectRoot,c),{finish:"keep",changeRoot:t.projectRoot,primaryRoot:n.primaryWorktreeRoot,changeBranch:n.currentBranch,targetBranch:n.currentBranch,targetRoot:t.projectRoot,remote:null,isolation:"current",pullRequestFinish:null}}if(!i.finish||!i.change_branch||!i.target_branch)throw new Error("Native isolated workspace finish is not persisted");if(i.change_branch===i.target_branch)throw new Error("Native change and target branches must be different for workspace finish");if(!n.primaryWorktreeRoot||n.currentBranch!==i.change_branch)throw new Error(`Native workspace finish requires branch ${i.change_branch} in the current registered worktree`);sv(t.projectRoot);let a=av(t,r,e.archiveDir,e.appliedSpecChanges);ov(t.projectRoot,a);let o=i.isolation==="branch"?t.projectRoot:$x(n.primaryWorktreeRoot,i.target_branch);if(i.finish==="merge"&&i.isolation==="worktree"){if(!o)throw new Error(`Native merge finish requires a registered worktree on target branch ${i.target_branch}`);Ix(o)}let s=i.finish==="push"||i.finish==="pull-request"?zp(t.projectRoot,i.change_branch):null;return i.finish==="pull-request"&&(Ox("gh",["--version"]),Hx(t.projectRoot,e.pullRequestFinish)),{finish:i.finish,changeRoot:t.projectRoot,primaryRoot:n.primaryWorktreeRoot,changeBranch:i.change_branch,targetBranch:i.target_branch,targetRoot:o,remote:s,isolation:i.isolation,pullRequestFinish:e.pullRequestFinish??null}}async function Dx(e){try{return await Ax.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Bx(e){return{action:e.finish,status:e.finish==="keep"?"kept":"completed",commit:null,remote:e.remote,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:e.targetRoot,cleanup:{performed:!1,reason:null},blockedPaths:[],message:null,recoveryArgs:null}}async function Lx(e){if(e.isolation!=="worktree")return{performed:!1,reason:null};if(vu(e.changeRoot,process.cwd()))return{performed:!1,reason:"invocation-working-directory-is-the-change-worktree"};try{return await dn(e.changeRoot),C(e.primaryRoot,["worktree","remove",e.changeRoot]),{performed:!0,reason:null}}catch(t){return{performed:!1,reason:`worktree-cleanup-failed: ${t.message}`}}}async function uv(e){let t=Bx(e.plan),r=null;try{let i=[Wt(e.paths.projectRoot,Ne(e.paths,e.name)),Wt(e.paths.projectRoot,e.archiveDir),...e.state.spec_changes.map(l=>Wt(e.paths.projectRoot,un(e.paths,l.capability))),Wt(e.paths.projectRoot,ru(e.paths))],n=Jr(e.plan.changeRoot).filter(l=>!cv(l,i)&&!(l===".comet/config.yaml"&&Ur(e.plan.changeRoot)));if(n.length>0)throw t.blockedPaths=n,new Error(`Native Archive produced or encountered paths outside the authorized finish scope: ${n.join(", ")}`);let a=[],o=new Set;for(let l of i){let f=nt.resolve(e.paths.projectRoot,...l.split("/"));if(Tx(e.plan.changeRoot,l).length>0&&a.push(l),await Dx(f))for(let u of jx(e.plan.changeRoot,l))o.add(u)}if(a.length>0&&C(e.plan.changeRoot,["add","-u","--",...a]),o.size>0&&C(e.plan.changeRoot,["add","--",...o]),C(e.plan.changeRoot,["diff","--cached","--name-only","-z"])&&C(e.plan.changeRoot,["commit","-m",`chore(native): archive ${e.name}`]),t.commit=C(e.plan.changeRoot,["rev-parse","HEAD"]),!Kr(e.plan.changeRoot))throw new Error("Native archive commit left unexpected working-tree changes");if(e.plan.finish==="keep")return t;if(e.plan.finish==="push"||e.plan.finish==="pull-request"){C(e.plan.changeRoot,["push","--set-upstream",e.plan.remote,e.plan.changeBranch]),t.pushed=!0,e.plan.finish==="pull-request"&&(t.pullRequest=nv({projectRoot:e.plan.changeRoot,changeName:e.name,transactionId:e.transactionId,remote:e.plan.remote,baseBranch:e.plan.targetBranch,headBranch:e.plan.changeBranch,headSha:t.commit,config:e.plan.pullRequestFinish}),t.pullRequestUrl=t.pullRequest.pullRequest.url);let l=vu(e.plan.changeRoot,process.cwd());return e.plan.isolation==="worktree"&&!l?(await dn(e.plan.changeRoot),C(e.plan.primaryRoot,["worktree","remove",e.plan.changeRoot]),t.cleanup={performed:!0,reason:null}):e.plan.isolation==="worktree"&&(t.cleanup={performed:!1,reason:"invocation-working-directory-is-the-change-worktree"}),t}let c=e.plan.targetRoot??e.plan.changeRoot;return e.plan.isolation==="branch"&&(C(c,["switch",e.plan.targetBranch]),r=c),C(c,["merge","--no-ff","--no-edit",e.plan.changeBranch]),t.merged=!0,t.targetRoot=c,t.cleanup=await Lx(e.plan),t}catch(i){if(i instanceof Q&&i.pullRequest&&(t.pullRequestUrl=i.pullRequest.url),r!==null){let n;try{C(r,["merge","--abort"])}catch{}try{$(r).currentBranch===e.plan.targetBranch&&C(r,["switch",e.plan.changeBranch]),n=$(r).currentBranch===e.plan.changeBranch}catch{n=!1}n||(t.targetRoot=r)}throw t.status="blocked",t.message=i.message,t.recoveryArgs=e.plan.finish==="pull-request"?["comet","native","archive",e.name,"--confirmed"]:e.plan.finish==="merge"&&t.targetRoot?["git","-C",t.targetRoot,"status","--short"]:["git","-C",e.plan.changeRoot,"status","--short"],new xn(t)}}Fi();import Rn from"path";import{realpathSync as PC}from"fs";ke();var wt={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function dv(e){return e?e.command?`${wt.next} ${e.command}`:e.ask_user?`${wt.next} ${e.ask_user}`:null:null}function fv(e,t){let r=[e.summary],i=dv(e.next);return i&&r.push(i),e.user_message&&r.push("",wt.relay,e.user_message),t!==void 0&&r.push("",wt.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
212
212
|
`)}
|
|
213
213
|
`}function hv(e,t,r){let i=[e.summary],n=dv(e.next);return n&&i.push(n),e.user_message&&i.push("",wt.relay,e.user_message),i.push("",`${wt.detail} ${t}`),r!==void 0&&i.push("",wt.details,JSON.stringify(r,null,2)),i.join(`
|
|
214
|
-
`)}nn();se();Ee();Y();se();var qx=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});Xr();
|
|
215
|
-
`)}}let r=t.continuation;if(bv(r))return hC(r,NC(t),bC(t,yu(r)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:R(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 NC(e){if(wu(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(wu(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return dC(r.acceptance)}return null}function bC(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return R(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?R(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function Ev(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:R("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:R("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:R("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:R("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:R("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:R("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:R("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:R("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:R("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}jl();var Pv=["--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."],bu=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","
|
|
216
|
-
comet native spec sync <change-name> <capability> --input <json-file>`,purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal.","sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections without changing prose or acceptance."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},"spec sync":{usage:"comet native spec sync <change-name> <capability> --input <json-file>",purpose:"Sync local Markdown link destinations in an already confirmed target spec; semantic edits require Shape.",options:["--input <json-file> Fields: expectedStateVersion, actor, reason, affectedAcceptanceIds, replacements [{from,to}]. Include all acceptance IDs from the affected spec."],output:"The audited portable state, preserved unaffected acceptance results and Build continuation for re-verification."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"
|
|
214
|
+
`)}nn();se();Ee();Y();se();var qx=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});Xr();et();Wr();Y();Ce();B();rn();q();Y();tt();zi();me();B();et();ur();se();se();Fo();Yr();tt();var pv={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:[]},Vx=_e("comet-native-runtime:v3:scope-reopen"),pB=[{skillVersion:"3",skillHash:_e("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:_e("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:_e("comet-native-runtime:v1")}];nn();tt();nn();tt();Nl();ao();var vv=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],UB=new Set(vv),Kx=new Set([...vv,"minimum_runtime_version","revision"]),KB=new Set([...Kx,"operation"]),YB=512*1024,Yx=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),XB=new Set([...Yx,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);Qa();Ee();Y();Ee();Qa();se();var rL={maxAcceptanceCriteria:Xa.maxCriteria};var sL={maxSpecs:64,maxFileBytes:jn,maxTotalBytes:4*1024*1024};Xr();tn();Yr();Fo();import{execFile as aC}from"node:child_process";So();_l();Y();import{promisify as oC}from"node:util";Y();q();Y();tt();B();et();si();ur();var gL={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};me();q();Xl();B();We();var BL=512*1024;Xr();me();ur();var Cn=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};tn();Vo();Yr();var sq=64*1024;var cq=3600*1e3;var lq=oC(aC);Vo();var Xo=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}};Wr();tt();et();var Gq={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};q();We();B();et();vo();var iF=16*1024*1024,nF=256*1024,aF=16*1024;Y();q();Zt();Y();Xr();var dF=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});tt();zi();me();B();et();vo();var e1=16*1024*1024,Qo=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"},Zo=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"};Y();B();Ce();function R(e,t,r){return e==="zh-CN"?r:t}var gu={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function yv(e,t){return typeof e=="string"&&gu[e]?R(t,gu[e].en,gu[e].zh):typeof e=="string"?e:""}function wu(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 dC(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 Nv(e,t){let r=[];e.failed>0&&r.push(R(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(R(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(R(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=R(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function bv(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 yu(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function fC(e,t,r){return e==="done"?R(r,"complete","已完成"):e==="await-user"?R(r,"waiting for a user decision","等待用户决定"):e==="blocked"?R(r,"paused: needs attention","已暂停,需要处理"):t?R(r,"waiting for a user decision","等待用户决定"):R(r,"ready to continue","可继续推进")}function hC(e,t,r){let i=yu(e),n=[];r&&n.push(r);let a=R(i,`Change ${e.change}`,`需求 ${e.change}`),o=yv(e.phase,i),s=fC(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(Nv(t,i));let c=e.userCommunication,l=kv(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function kv(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:R(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:R(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:R(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function pC(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function mC(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=yv(e.phase,t),n=e.status==="await-user"?R(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?R(t,"paused","已暂停"):e.status==="done"?R(t,"complete","已完成"):R(t,"in progress","进行中"),a=wu(e.acceptance)?`${R(t,", ",",")}${Nv(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function vC(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 gC(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 wC(e){if(e.healthy){let i=e.repaired?R("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):R("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=yC(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:R("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:R("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function yC(e){return bv(e)?kv(e,yu(e)):void 0}function Sv(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(gC(t))return wC(t);if(pC(t)){let i=vC(t.items);return{summary:[t.total===t.items.length?R(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):R(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>mC(a,i))].join(`
|
|
215
|
+
`)}}let r=t.continuation;if(bv(r))return hC(r,NC(t),bC(t,yu(r)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:R(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 NC(e){if(wu(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(wu(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return dC(r.acceptance)}return null}function bC(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return R(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?R(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function Ev(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:R("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:R("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:R("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:R("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:R("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:R("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:R("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:R("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:R("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}jl();var Pv=["--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."],bu=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","spec sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:Pv,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:`comet native spec remove <change-name> <capability>
|
|
216
|
+
comet native spec sync <change-name> <capability> --input <json-file>`,purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal.","sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections without changing prose or acceptance."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},"spec sync":{usage:"comet native spec sync <change-name> <capability> --input <json-file>",purpose:"Sync local Markdown link destinations in an already confirmed target spec; semantic edits require Shape.",options:["--input <json-file> Fields: expectedStateVersion, actor, reason, affectedAcceptanceIds, replacements [{from,to}]. Include all acceptance IDs from the affected spec."],output:"The audited portable state, preserved unaffected acceptance results and Build continuation for re-verification."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"A compact summary and NEXT action by default. Use --json to read the portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required. Fill command-template placeholders before executing NEXT commands."},check:{usage:"comet native check <change-name>",purpose:"Legacy-only verification command; not supported for current portable changes.",output:"For current changes, run comet native status <change-name> --json and follow the continuation to dispatch verification through comet native next."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page, or a named details/history page.","--details Include one fixed-size page of acceptance, Spec, handoff, verification, history, workspace, and report details."],output:"A compact v2 status page or one compact Loop projection with local execution availability. Use --details and --cursor to read fixed-size detail pages; parent changes expose childSummary and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--coordination-mode multi-session|single-session] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
|
|
217
217
|
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>]
|
|
218
218
|
comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm the persisted Shape boundary with both expected guards, or confirm an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Select how a multi-child Supervisor proceeds while preparing its Shape confirmation; final Shape confirmation is a later, separate step.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a failed or unavailable Verifier when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--max-parallel <n> Supervisor task concurrency cap; defaults to 2, use 1 for serial fallback.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits, review. review fields: status=passed, summary, reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."," Supervisor task fields: supervisor-builder-result (child, runId, candidateCommit), supervisor-builder-failure (child, runId, reason), supervisor-verifier-result (child, runId, verdict, verification data), supervisor-reconnect (child, runId), supervisor-cancel (child, runId, reason), or supervisor-integrate (child, checks)."," supervisor-checks fields: kind, child, runId, checks (non-empty repeatable Runtime check plans), materials [{name,content}]. Returns checkExecution with operationId, status and receiptRef. Repeated running plans return the same handle."," supervisor-verifier-result evidence fields: summary, checks (informal notes), acceptance [{id,result,reason}], receiptRef. verdict is pass, fail or blocked; every task acceptance ID must appear exactly once. Runtime receipts determine formal check status; receiptRef may be null for fail or blocked."," supervisor-integrate checks are non-empty Runtime check plans executed after the merge in the integration worktree, not declared statuses."],output:'A compact portable state summary, explicit skill-coordinated label, Runtime-owned check results, scoped verifierDispatch, bounded request-check response, continuation.runnerAction, machine-readable continuation.inputOptions, and continuation.userCommunication with a user-ready message and Agent relay guidance. Read acceptance text and other long fields from paged status --details output. Human-readable verification statuses include "Host independently verified", "Checks completed, but your confirmation is required", "Full verification was unavailable; only automatic checks completed", and "You accepted the incomplete verification result". This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.',examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed --expected-state-version <n> --expected-action confirm-shape','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
|
|
219
219
|
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 Nu(e,t){return`${e}:
|
|
@@ -226,9 +226,9 @@ ${t.map(r=>` ${r}`).join(`
|
|
|
226
226
|
`}:e.error?{exitCode:e.exitCode,stderr:i?hv(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:fv(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==_v(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
227
227
|
${wt.details}
|
|
228
228
|
${JSON.stringify(e.data,null,2)}
|
|
229
|
-
`}:{exitCode:e.exitCode,stdout:e.text}}async function $v(e,t){let r=Cv(e,"change name"),i=Zr(e,"--dry-run"),n=ei(e,"--expect-preflight"),a=Zr(e,"--confirmed"),o=ei(e,"--finish"),s=ei(e,"--serial-first");if(s!==void 0&&!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(s))throw new Z("--serial-first must be one Native change name");let c=o;if(c!==void 0&&c!=="merge"&&c!=="push"&&c!=="pull-request"&&c!=="keep")throw new Z("--finish must be merge, push, pull-request, or keep");let l=await Av(t),f=await kn(l.paths,r),d=f?await Dt(l.paths,{kind:"archive",change:r}):null,u=d?.kind==="archive"?d.journal.spec_changes.slice(0,d.journal.next_spec_index):[],p=f?!1:await Dm(l.paths,r);if(f||p){if(n)throw new Z("Portable Native Archive does not use preflight hashes");if(i&&a)throw new Z("--confirmed is only valid when executing Archive");if(s&&s!==r)throw new Z("--serial-first must name the change being archived");if(!i&&c)throw new Z("--finish is only valid with --dry-run");Su(e);let h=f&&!i&&d?.kind!=="archive"?await Zm({paths:l.paths,name:r}):null,m=h?.state??(f?await
|
|
229
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}async function $v(e,t){let r=Cv(e,"change name"),i=Zr(e,"--dry-run"),n=ei(e,"--expect-preflight"),a=Zr(e,"--confirmed"),o=ei(e,"--finish"),s=ei(e,"--serial-first");if(s!==void 0&&!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(s))throw new Z("--serial-first must be one Native change name");let c=o;if(c!==void 0&&c!=="merge"&&c!=="push"&&c!=="pull-request"&&c!=="keep")throw new Z("--finish must be merge, push, pull-request, or keep");let l=await Av(t),f=await kn(l.paths,r),d=f?await Dt(l.paths,{kind:"archive",change:r}):null,u=d?.kind==="archive"?d.journal.spec_changes.slice(0,d.journal.next_spec_index):[],p=f?!1:await Dm(l.paths,r);if(f||p){if(n)throw new Z("Portable Native Archive does not use preflight hashes");if(i&&a)throw new Z("--confirmed is only valid when executing Archive");if(s&&s!==r)throw new Z("--serial-first must name the change being archived");if(!i&&c)throw new Z("--finish is only valid with --dry-run");Su(e);let h=f&&!i&&d?.kind!=="archive"?await Zm({paths:l.paths,name:r}):null,m=h?.state??(f?await Ve(l.paths,r):null);if(h?.action==="reverify"||h?.action==="await-user")return ti(i?"archive --dry-run":"archive",{archived:!1,state:h.state,recovery:h,continuation:vt(h.state)},`${h.message}
|
|
230
230
|
`);if(i){if(!m)return ti("archive --dry-run",{change:r,ready:!0,archiveRecovery:!0,continuation:{disposition:"continue",reason:"Resume the interrupted Native Archive transaction.",commandArgs:["comet","native","archive",r,"--confirmed"],inputOptions:[],runnerAction:null}},`Native Archive recovery is ready for ${r}
|
|
231
|
-
`);c&&(m=await Am({paths:l.paths,name:r,finish:c}));let N=await cu({paths:l.paths,name:r}),P="capabilities are also declared by:",x=N.blockers.filter(zt=>!zt.startsWith(P)),k=[],_=m.workspace.isolation!=="current"&&m.workspace.finish===null;if(_&&x.push("Native branch and worktree isolation require a workspace finish choice"),!_)try{await Yo({paths:l.paths,state:m,appliedSpecChanges:u,pullRequestFinish:l.config.native.finish?.pull_request})}catch(zt){let Eu=zt.message;x.push(Eu),k.push({message:Eu,paths:zt instanceof gt?zt.paths:[],workspaceRoot:zt instanceof gt?zt.workspaceRoot:l.paths.projectRoot})}let ue=N.capabilityPeers.length>0&&s!==r,ae=ue&&x.length===0?vt(m,null,{archiveMode:"preview"}):null,j=ae?{...ae,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["choose-first-archive"],requiresUserDecision:!0,userCommunication:{required:!0,message:m.language==="zh-CN"?`当前规格也由 ${N.capabilityPeers.join(", ")} 修改。是否先归档 ${r}?其他 change 随后需要对齐最新规格。`:`The same specifications are changed by ${N.capabilityPeers.join(", ")}. Archive ${r} first? The other changes must then align with the latest specifications.`,suggestedReply:m.language==="zh-CN"?`先归档 ${r}`:`Archive ${r} first`,agentInstruction:"Wait for the ordering decision, then execute the matching dry-run commandAlternative."},commandAlternatives:[{name:"archive-this-change-first",commandArgs:["comet","native","archive",r,"--dry-run","--serial-first",r],description:`Archive ${r} before ${N.capabilityPeers.join(", ")}`,inputOptions:[],requiredInputs:[]}],runnerAction:{...ae.runnerAction,kind:"none"}}:_?vt(m):vt(m,null,{archiveMode:"preview",archiveBlockers:x}),
|
|
231
|
+
`);c&&(m=await Am({paths:l.paths,name:r,finish:c}));let N=await cu({paths:l.paths,name:r}),P="capabilities are also declared by:",x=N.blockers.filter(zt=>!zt.startsWith(P)),k=[],_=m.workspace.isolation!=="current"&&m.workspace.finish===null;if(_&&x.push("Native branch and worktree isolation require a workspace finish choice"),!_)try{await Yo({paths:l.paths,state:m,appliedSpecChanges:u,pullRequestFinish:l.config.native.finish?.pull_request})}catch(zt){let Eu=zt.message;x.push(Eu),k.push({message:Eu,paths:zt instanceof gt?zt.paths:[],workspaceRoot:zt instanceof gt?zt.workspaceRoot:l.paths.projectRoot})}let ue=N.capabilityPeers.length>0&&s!==r,ae=ue&&x.length===0?vt(m,null,{archiveMode:"preview"}):null,j=ae?{...ae,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["choose-first-archive"],requiresUserDecision:!0,userCommunication:{required:!0,message:m.language==="zh-CN"?`当前规格也由 ${N.capabilityPeers.join(", ")} 修改。是否先归档 ${r}?其他 change 随后需要对齐最新规格。`:`The same specifications are changed by ${N.capabilityPeers.join(", ")}. Archive ${r} first? The other changes must then align with the latest specifications.`,suggestedReply:m.language==="zh-CN"?`先归档 ${r}`:`Archive ${r} first`,agentInstruction:"Wait for the ordering decision, then execute the matching dry-run commandAlternative."},commandAlternatives:[{name:"archive-this-change-first",commandArgs:["comet","native","archive",r,"--dry-run","--serial-first",r],description:`Archive ${r} before ${N.capabilityPeers.join(", ")}`,inputOptions:[],requiredInputs:[]}],runnerAction:{...ae.runnerAction,kind:"none"}}:_?vt(m):vt(m,null,{archiveMode:"preview",archiveBlockers:x}),at=[...x,...ue?[`${P} ${N.capabilityPeers.join(", ")}`]:[]];return ti("archive --dry-run",{...N,ready:at.length===0,blockers:at,...k.length>0?{workspaceFinishBlockers:k}:{},workspaceFinish:m.workspace.finish,continuation:s===r&&j.commandArgs?{...j,commandArgs:[...j.commandArgs,"--serial-first",r]}:j},`Native Archive preview: ${at.length===0?"ready":"blocked"}
|
|
232
232
|
`)}if(l.config.native.archive_confirmation==="required"&&!a)throw new Z("archive requires --confirmed when native.archive_confirmation is required");if(m&&m.workspace.isolation!=="current"&&m.workspace.finish===null){let N=vt(m);return{command:"archive",exitCode:65,data:{change:r,archived:!1,workspaceFinish:null,continuation:N},error:{code:"usage",message:"Native branch and worktree isolation require a workspace finish choice; follow continuation.commandAlternatives and run its dry-run command"}}}let v=null;if(m)try{v=await Yo({paths:l.paths,state:m,appliedSpecChanges:u,pullRequestFinish:l.config.native.finish?.pull_request})}catch(N){let P=N.message,x=N instanceof gt?N.paths:[],k=N instanceof gt?N.workspaceRoot:l.paths.projectRoot,_={action:m.workspace.finish??"keep",status:"blocked",commit:null,remote:null,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:k,cleanup:{performed:!1,reason:null},blockedPaths:x,message:P,recoveryArgs:["git","-C",k,"status","--short"]};return{command:"archive",exitCode:73,data:{change:r,archived:!1,state:m,workspaceFinish:m.workspace.finish,workspaceFinishResult:_,continuation:vt(m,null,{archiveMode:"blocked",archiveBlockers:[P]})},error:{code:"conflict",message:P}}}let y;try{y=await Lm({paths:l.paths,name:r,...s?{serialFirstChange:s}:{}})}catch(N){if(!(N instanceof En)||!m)throw N;let P=await cu({paths:l.paths,name:r}),x=N.peers.length>0?["comet","native","archive",r,"--confirmed","--serial-first",r]:["comet","native","archive",r,"--confirmed"];return{command:"archive",exitCode:73,data:{...P,workspaceFinish:m.workspace.finish,workspaceFinishResult:null,continuation:{disposition:"await-user",reason:N.message,commandArgs:x,inputOptions:N.peers.length>0?["serial-first-change"]:[],runnerAction:null}},error:{code:"conflict",message:N.message}}}m=y.state,!v&&m&&(v=await Yo({paths:l.paths,state:m,archiveDir:y.archiveDir,pullRequestFinish:l.config.native.finish?.pull_request}));let b=null;if(v)try{b=await uv({paths:l.paths,state:y.state,name:r,archiveDir:y.archiveDir,transactionId:y.transactionId,plan:v})}catch(N){if(!(N instanceof xn))throw N;return{command:"archive",exitCode:73,data:{...y,workspaceFinish:y.state.workspace.finish,workspaceFinishResult:N.result,continuation:{disposition:"blocked",reason:N.message,commandArgs:N.result.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:N.message}}}let w=b?.merged===!0?await Cm({childPaths:l.paths,childState:y.state}):null;return ti("archive",{...y,artifactRefs:["brief.md",...y.state.verification_report?[y.state.verification_report]:[]].map(N=>jv.relative(t,jv.join(y.archiveDir,N)).replaceAll("\\","/")),workspaceFinish:y.state.workspace.finish,workspaceFinishResult:b,...w?{parentAdvance:w.parentAdvance}:{},...w?.parentState?{parentState:w.parentState}:{},continuation:vt(w?.parentState??y.state)},`Archived Native change ${r} to ${y.archiveDir}
|
|
233
233
|
`)}if(s)throw new Z("--serial-first is only valid for portable Native changes");if(!i&&c)throw new Z("--finish is only valid with --dry-run");if(Su(e),i)return{command:"archive --dry-run",exitCode:65,data:{change:r,migrationRequired:!0,repairCommand:`comet native doctor ${r} --repair`},error:{code:"invalid-data",message:`Native active change ${r} must migrate before Archive preview`}};let g=await Km({paths:l.paths,name:r});return ti("archive",{migration:{from:"legacy",to:g.schema,completed:!0},state:g,continuation:vt(g)},`Migrated Native change ${r}; follow the returned portable continuation before Archive
|
|
234
234
|
`)}async function Ov(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{Zr(n,"--json"),Zr(n,"--verbose"),c=ei(n,"--project-root");let d=[...n,...a],u=await Rv(c);l=await t(d,u)}catch(d){l=Iv(e,d)}let f=Tv(l,o,s);return f.stdout&&process.stdout.write(f.stdout),f.stderr&&process.stderr.write(f.stderr+(f.stderr.endsWith(`
|