@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 Cp=Object.create;var Qc=Object.defineProperty;var Pp=Object.getOwnPropertyDescriptor;var Rp=Object.getOwnPropertyNames;var Ap=Object.getPrototypeOf,_p=Object.prototype.hasOwnProperty;var Ti=(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 y=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var w=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Ip=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Rp(t))!_p.call(e,n)&&n!==r&&Qc(e,n,{get:()=>t[n],enumerable:!(i=Pp(t,n))||i.enumerable});return e};var vr=(e,t,r)=>(r=e!=null?Cp(Ap(e)):{},Ip(t||!e||!e.__esModule?Qc(r,"default",{value:e,enumerable:!0}):r,e));function Ja(){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 Ht,gr,Zc,wr=y(()=>{"use strict";Ht="comet.native.v4",gr="comet.native.local-execution.v4",Zc=["multi-session","single-session"]});import{execFileSync as Lp}from"child_process";import ji from"path";function Ka(e,t){return Lp("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Bp(e,t){let r=ji.normalize(e),i=ji.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function
|
|
5
|
-
`,r)}var O=y(()=>{"use strict";Pe()});function Kp(e){return e.toLowerCase().startsWith(".env")}function Nr(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>Kp(i))?"environment-file":r.some(i=>Up.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>Gp.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var Gp,Up,br=y(()=>{"use strict";Gp=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Up=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});import{createHash as Yp}from"node:crypto";import{promises as ve}from"node:fs";import se from"node:path";import{TextDecoder as Xp}from"node:util";function Ya(e,t){let r=se.relative(e,t);return r===""||!se.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${se.sep}`)}function Qp(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=Nr(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 Zp(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function em(e,t){return _({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Hi(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return pe(r,i)?_(r,i):_(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function il(e){let t=await ve.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await ve.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function tm(e,t){let r=se.resolve(e),i=se.resolve(t);if(!Ya(r,i))throw new Error("Native artifact path is outside its root");let n=[await il(r)],a=r;for(let o of se.relative(r,i).split(se.sep).filter(Boolean)){a=se.join(a,o);let s=await il(a);if(!Ya(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function nl(e){for(let t of e){let r=await ve.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!em(t,r)||await ve.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function M(e){let t=Qp(e.ref),r=e.maxBytes===null?null:Zp(e.maxBytes??Di),i=se.resolve(e.root,...t.split("/")),n=await tm(e.root,se.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await ve.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 ve.realpath(i);if(!Ya(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await ve.open(i,"r");try{let[l,c,f]=await Promise.all([s.stat(),ve.lstat(i),ve.realpath(i)]);if(await nl(n),!l.isFile()||!c.isFile()||c.isSymbolicLink()||f!==o||!Hi(a,l)||!Hi(l,c))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,S=await s.read(p,0,Math.min(p.length,b),null);if(S.bytesRead===0)break;if(u+=S.bytesRead,r!==null&&u>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,S.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),ve.lstat(i),ve.realpath(i)]);if(await nl(n),!h.isFile()||h.isSymbolicLink()||v!==o||!Hi(l,m)||!Hi(l,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,u),N;try{N=new Xp("utf-8",{fatal:!0}).decode(g)}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:Yp("sha256").update(g).digest("hex"),text:N}}finally{await s.close()}}var Di,ge=y(()=>{"use strict";br();Pe();Di=1024*1024});var P=w(z=>{"use strict";var Xa=Symbol.for("yaml.alias"),al=Symbol.for("yaml.document"),Li=Symbol.for("yaml.map"),ol=Symbol.for("yaml.pair"),Qa=Symbol.for("yaml.scalar"),Bi=Symbol.for("yaml.seq"),Fe=Symbol.for("yaml.node.type"),rm=e=>!!e&&typeof e=="object"&&e[Fe]===Xa,im=e=>!!e&&typeof e=="object"&&e[Fe]===al,nm=e=>!!e&&typeof e=="object"&&e[Fe]===Li,am=e=>!!e&&typeof e=="object"&&e[Fe]===ol,sl=e=>!!e&&typeof e=="object"&&e[Fe]===Qa,om=e=>!!e&&typeof e=="object"&&e[Fe]===Bi;function cl(e){if(e&&typeof e=="object")switch(e[Fe]){case Li:case Bi:return!0}return!1}function sm(e){if(e&&typeof e=="object")switch(e[Fe]){case Xa:case Li:case Qa:case Bi:return!0}return!1}var cm=e=>(sl(e)||cl(e))&&!!e.anchor;z.ALIAS=Xa;z.DOC=al;z.MAP=Li;z.NODE_TYPE=Fe;z.PAIR=ol;z.SCALAR=Qa;z.SEQ=Bi;z.hasAnchor=cm;z.isAlias=rm;z.isCollection=cl;z.isDocument=im;z.isMap=nm;z.isNode=sm;z.isPair=am;z.isScalar=sl;z.isSeq=om});var kr=w(Za=>{"use strict";var F=P(),Z=Symbol("break visit"),ll=Symbol("skip children"),Re=Symbol("remove node");function Vi(e,t){let r=ul(t);F.isDocument(e)?Lt(null,e.contents,r,Object.freeze([e]))===Re&&(e.contents=null):Lt(null,e,r,Object.freeze([]))}Vi.BREAK=Z;Vi.SKIP=ll;Vi.REMOVE=Re;function Lt(e,t,r,i){let n=dl(e,t,r,i);if(F.isNode(n)||F.isPair(n))return fl(e,i,n),Lt(e,n,r,i);if(typeof n!="symbol"){if(F.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=Lt(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Z)return Z;o===Re&&(t.items.splice(a,1),a-=1)}}}else if(F.isPair(t)){i=Object.freeze(i.concat(t));let a=Lt("key",t.key,r,i);if(a===Z)return Z;a===Re&&(t.key=null);let o=Lt("value",t.value,r,i);if(o===Z)return Z;o===Re&&(t.value=null)}}return n}async function Mi(e,t){let r=ul(t);F.isDocument(e)?await Bt(null,e.contents,r,Object.freeze([e]))===Re&&(e.contents=null):await Bt(null,e,r,Object.freeze([]))}Mi.BREAK=Z;Mi.SKIP=ll;Mi.REMOVE=Re;async function Bt(e,t,r,i){let n=await dl(e,t,r,i);if(F.isNode(n)||F.isPair(n))return fl(e,i,n),Bt(e,n,r,i);if(typeof n!="symbol"){if(F.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await Bt(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Z)return Z;o===Re&&(t.items.splice(a,1),a-=1)}}}else if(F.isPair(t)){i=Object.freeze(i.concat(t));let a=await Bt("key",t.key,r,i);if(a===Z)return Z;a===Re&&(t.key=null);let o=await Bt("value",t.value,r,i);if(o===Z)return Z;o===Re&&(t.value=null)}}return n}function ul(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 dl(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(F.isMap(t))return r.Map?.(e,t,i);if(F.isSeq(t))return r.Seq?.(e,t,i);if(F.isPair(t))return r.Pair?.(e,t,i);if(F.isScalar(t))return r.Scalar?.(e,t,i);if(F.isAlias(t))return r.Alias?.(e,t,i)}function fl(e,t,r){let i=t[t.length-1];if(F.isCollection(i))i.items[e]=r;else if(F.isPair(i))e==="key"?i.key=r:i.value=r;else if(F.isDocument(i))i.contents=r;else{let n=F.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Za.visit=Vi;Za.visitAsync=Mi});var eo=w(pl=>{"use strict";var hl=P(),lm=kr(),um={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},dm=e=>e.replace(/[!,[\]{}]/g,t=>um[t]),Sr=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+dm(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&&hl.isNode(t.contents)){let a={};lm.visit(t.contents,(o,s)=>{hl.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
|
-
`)}};Sr.defaultYaml={explicit:!1,version:"1.2"};Sr.defaultTags={"!!":"tag:yaml.org,2002:"};pl.Directives=Sr});var Fi=w(Er=>{"use strict";var ml=P(),fm=kr();function hm(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 vl(e){let t=new Set;return fm.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function gl(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function pm(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=vl(e));let o=gl(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(ml.isScalar(o.node)||ml.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}}Er.anchorIsValid=hm;Er.anchorNames=vl;Er.createNodeAnchors=pm;Er.findNewAnchor=gl});var to=w(wl=>{"use strict";function xr(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=xr(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=xr(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=xr(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=xr(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}wl.applyReviver=xr});var Ze=w(Nl=>{"use strict";var mm=P();function yl(e,t,r){if(Array.isArray(e))return e.map((i,n)=>yl(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!mm.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}Nl.toJS=yl});var qi=w(kl=>{"use strict";var vm=to(),bl=P(),gm=Ze(),ro=class{constructor(t){Object.defineProperty(this,bl.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(!bl.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=gm.toJS(this,"",o);if(typeof n=="function")for(let{count:l,res:c}of o.anchors.values())n(c,l);return typeof a=="function"?vm.applyReviver(a,{"":s},"",s):s}};kl.NodeBase=ro});var Cr=w(Sl=>{"use strict";var wm=Fi(),ym=kr(),Vt=P(),Nm=qi(),bm=Ze(),io=class extends Nm.NodeBase{constructor(t){super(Vt.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=[],ym.visit(t,{Node:(a,o)=>{(Vt.isAlias(o)||Vt.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 l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let s=i.get(o);if(s||(bm.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=Wi(n,o,i)),s.count*s.aliasCount>a)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(wm.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 Wi(e,t,r){if(Vt.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Vt.isCollection(t)){let i=0;for(let n of t.items){let a=Wi(e,n,r);a>i&&(i=a)}return i}else if(Vt.isPair(t)){let i=Wi(e,t.key,r),n=Wi(e,t.value,r);return Math.max(i,n)}return 1}Sl.Alias=io});var H=w(no=>{"use strict";var km=P(),Sm=qi(),Em=Ze(),xm=e=>!e||typeof e!="function"&&typeof e!="object",et=class extends Sm.NodeBase{constructor(t){super(km.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Em.toJS(this.value,t,r)}toString(){return String(this.value)}};et.BLOCK_FOLDED="BLOCK_FOLDED";et.BLOCK_LITERAL="BLOCK_LITERAL";et.PLAIN="PLAIN";et.QUOTE_DOUBLE="QUOTE_DOUBLE";et.QUOTE_SINGLE="QUOTE_SINGLE";no.Scalar=et;no.isScalarValue=xm});var Pr=w(xl=>{"use strict";var Cm=Cr(),yt=P(),El=H(),Pm="tag:yaml.org,2002:";function Rm(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 Am(e,t,r){if(yt.isDocument(e)&&(e=e.contents),yt.isNode(e))return e;if(yt.isPair(e)){let d=r.schema[yt.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,l;if(i&&e&&typeof e=="object"){if(l=s.get(e),l)return l.anchor??(l.anchor=n(e)),new Cm.Alias(l.anchor);l={anchor:null,node:null},s.set(e,l)}t?.startsWith("!!")&&(t=Pm+t.slice(2));let c=Rm(e,t,o.tags);if(!c){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new El.Scalar(e);return l&&(l.node=d),d}c=e instanceof Map?o[yt.MAP]:Symbol.iterator in Object(e)?o[yt.SEQ]:o[yt.MAP]}a&&(a(c),delete r.onTagObj);let f=c?.createNode?c.createNode(r.schema,e,r):typeof c?.nodeClass?.from=="function"?c.nodeClass.from(r.schema,e,r):new El.Scalar(e);return t?f.tag=t:c.default||(f.tag=c.tag),l&&(l.node=f),f}xl.createNode=Am});var Ji=w(zi=>{"use strict";var _m=Pr(),
|
|
4
|
+
var Cp=Object.create;var Qc=Object.defineProperty;var Pp=Object.getOwnPropertyDescriptor;var Rp=Object.getOwnPropertyNames;var Ap=Object.getPrototypeOf,_p=Object.prototype.hasOwnProperty;var Ti=(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 y=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var w=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Ip=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Rp(t))!_p.call(e,n)&&n!==r&&Qc(e,n,{get:()=>t[n],enumerable:!(i=Pp(t,n))||i.enumerable});return e};var vr=(e,t,r)=>(r=e!=null?Cp(Ap(e)):{},Ip(t||!e||!e.__esModule?Qc(r,"default",{value:e,enumerable:!0}):r,e));function Ja(){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 Ht,gr,Zc,wr=y(()=>{"use strict";Ht="comet.native.v4",gr="comet.native.local-execution.v4",Zc=["multi-session","single-session"]});import{execFileSync as Lp}from"child_process";import ji from"path";function Ka(e,t){return Lp("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function Bp(e,t){let r=ji.normalize(e),i=ji.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function pe(e){try{let t=ji.resolve(Ka(e,["rev-parse","--show-toplevel"])),i=Ka(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?ji.resolve(i.slice(9)):t,a=null;try{a=Ka(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Bp(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}var Me=y(()=>{"use strict"});function Qe(e){return e!==0&&e!==0n&&e!=="0"}function me(e,t){return Qe(e.dev)&&Qe(t.dev)&&Qe(e.ino)&&Qe(t.ino)}function _(e,t){let r=Qe(e.dev)&&Qe(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Qe(e.ino)&&Qe(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var yr=y(()=>{"use strict"});var Re=y(()=>{"use strict";yr()});import{randomUUID as Vp}from"crypto";import{promises as q}from"fs";import ve from"path";function $i(e,t){let r=ve.relative(e,t);return r===""||!ve.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ve.sep}`)}function Mp(e,t){return _({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Oi(e,t){return _({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function Fp(e,t){return Oi(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function rl(e){let t=await q.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 q.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Dt(e){for(let t of e){let r=await q.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Mp(t,r)||await q.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function qp(e,t,r){let[i,n]=await Promise.all([q.lstat(e),q.realpath(e),r?Dt(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!Oi(i,t)||r&&!$i(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function Wp(e,t){let r=ve.resolve(e),i=ve.resolve(t);if(!$i(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await rl(r)],a=ve.relative(r,i).split(ve.sep).filter(Boolean),o=r;for(let s of a){await Dt(n),o=ve.join(o,s);try{await q.mkdir(o)}catch(c){if(c.code!=="EEXIST")throw c}let l=await rl(o);if(!$i(n[0].realPath,l.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(l)}return await Dt(n),n}async function zp(e){let t;try{t=await q.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 Jp(e,t,r={}){let i=ve.dirname(e),n=r.containedRoot?await Wp(r.containedRoot,i):null;n||await q.mkdir(i,{recursive:!0});let a=ve.join(i,`.${ve.basename(e)}.${Vp()}.tmp`),o,s,l;try{if(await r.beforeTemporaryOpen?.(),o=await q.open(a,"wx"),s=await o.stat(),n){let[c,f]=await Promise.all([q.lstat(a),q.realpath(a)]);if(await Dt(n),!c.isFile()||c.isSymbolicLink()||!Oi(s,c)||!$i(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(),l=await o.stat(),!Oi(s,l))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!l)throw new Error("Native atomic write temporary file was not written");if(l=await qp(a,l,n),await r.beforeCommit?.(),n){await Dt(n);let c=await q.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!l||!Fp(c,l))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await q.link(a,e),await q.unlink(a)):await q.rename(a,e),await zp(i)}catch(c){if(await o?.close(),!n)await q.rm(a,{force:!0});else try{await Dt(n),await q.rm(a,{force:!0})}catch{}throw c}}async function se(e,t,r={}){await Jp(e,t,r)}async function U(e,t,r={}){await se(e,JSON.stringify(t,null,2)+`
|
|
5
|
+
`,r)}var O=y(()=>{"use strict";Re()});function Kp(e){return e.toLowerCase().startsWith(".env")}function Nr(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>Kp(i))?"environment-file":r.some(i=>Up.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>Gp.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var Gp,Up,br=y(()=>{"use strict";Gp=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Up=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});import{createHash as Yp}from"node:crypto";import{promises as ge}from"node:fs";import ce from"node:path";import{TextDecoder as Xp}from"node:util";function Ya(e,t){let r=ce.relative(e,t);return r===""||!ce.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ce.sep}`)}function Qp(e){let t=ce.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})||ce.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=Nr(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 Zp(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function em(e,t){return _({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Hi(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return me(r,i)?_(r,i):_(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function il(e){let t=await ge.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await ge.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function tm(e,t){let r=ce.resolve(e),i=ce.resolve(t);if(!Ya(r,i))throw new Error("Native artifact path is outside its root");let n=[await il(r)],a=r;for(let o of ce.relative(r,i).split(ce.sep).filter(Boolean)){a=ce.join(a,o);let s=await il(a);if(!Ya(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function nl(e){for(let t of e){let r=await ge.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!em(t,r)||await ge.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function M(e){let t=Qp(e.ref),r=e.maxBytes===null?null:Zp(e.maxBytes??Di),i=ce.resolve(e.root,...t.split("/")),n=await tm(e.root,ce.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await ge.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 ge.realpath(i);if(!Ya(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await ge.open(i,"r");try{let[l,c,f]=await Promise.all([s.stat(),ge.lstat(i),ge.realpath(i)]);if(await nl(n),!l.isFile()||!c.isFile()||c.isSymbolicLink()||f!==o||!Hi(a,l)||!Hi(l,c))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,S=await s.read(p,0,Math.min(p.length,b),null);if(S.bytesRead===0)break;if(u+=S.bytesRead,r!==null&&u>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,S.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),ge.lstat(i),ge.realpath(i)]);if(await nl(n),!h.isFile()||h.isSymbolicLink()||v!==o||!Hi(l,m)||!Hi(l,h))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,u),N;try{N=new Xp("utf-8",{fatal:!0}).decode(g)}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:Yp("sha256").update(g).digest("hex"),text:N}}finally{await s.close()}}var Di,we=y(()=>{"use strict";br();Re();Di=1024*1024});var P=w(z=>{"use strict";var Xa=Symbol.for("yaml.alias"),al=Symbol.for("yaml.document"),Li=Symbol.for("yaml.map"),ol=Symbol.for("yaml.pair"),Qa=Symbol.for("yaml.scalar"),Bi=Symbol.for("yaml.seq"),Fe=Symbol.for("yaml.node.type"),rm=e=>!!e&&typeof e=="object"&&e[Fe]===Xa,im=e=>!!e&&typeof e=="object"&&e[Fe]===al,nm=e=>!!e&&typeof e=="object"&&e[Fe]===Li,am=e=>!!e&&typeof e=="object"&&e[Fe]===ol,sl=e=>!!e&&typeof e=="object"&&e[Fe]===Qa,om=e=>!!e&&typeof e=="object"&&e[Fe]===Bi;function cl(e){if(e&&typeof e=="object")switch(e[Fe]){case Li:case Bi:return!0}return!1}function sm(e){if(e&&typeof e=="object")switch(e[Fe]){case Xa:case Li:case Qa:case Bi:return!0}return!1}var cm=e=>(sl(e)||cl(e))&&!!e.anchor;z.ALIAS=Xa;z.DOC=al;z.MAP=Li;z.NODE_TYPE=Fe;z.PAIR=ol;z.SCALAR=Qa;z.SEQ=Bi;z.hasAnchor=cm;z.isAlias=rm;z.isCollection=cl;z.isDocument=im;z.isMap=nm;z.isNode=sm;z.isPair=am;z.isScalar=sl;z.isSeq=om});var kr=w(Za=>{"use strict";var F=P(),Z=Symbol("break visit"),ll=Symbol("skip children"),Ae=Symbol("remove node");function Vi(e,t){let r=ul(t);F.isDocument(e)?Lt(null,e.contents,r,Object.freeze([e]))===Ae&&(e.contents=null):Lt(null,e,r,Object.freeze([]))}Vi.BREAK=Z;Vi.SKIP=ll;Vi.REMOVE=Ae;function Lt(e,t,r,i){let n=dl(e,t,r,i);if(F.isNode(n)||F.isPair(n))return fl(e,i,n),Lt(e,n,r,i);if(typeof n!="symbol"){if(F.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=Lt(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Z)return Z;o===Ae&&(t.items.splice(a,1),a-=1)}}}else if(F.isPair(t)){i=Object.freeze(i.concat(t));let a=Lt("key",t.key,r,i);if(a===Z)return Z;a===Ae&&(t.key=null);let o=Lt("value",t.value,r,i);if(o===Z)return Z;o===Ae&&(t.value=null)}}return n}async function Mi(e,t){let r=ul(t);F.isDocument(e)?await Bt(null,e.contents,r,Object.freeze([e]))===Ae&&(e.contents=null):await Bt(null,e,r,Object.freeze([]))}Mi.BREAK=Z;Mi.SKIP=ll;Mi.REMOVE=Ae;async function Bt(e,t,r,i){let n=await dl(e,t,r,i);if(F.isNode(n)||F.isPair(n))return fl(e,i,n),Bt(e,n,r,i);if(typeof n!="symbol"){if(F.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await Bt(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Z)return Z;o===Ae&&(t.items.splice(a,1),a-=1)}}}else if(F.isPair(t)){i=Object.freeze(i.concat(t));let a=await Bt("key",t.key,r,i);if(a===Z)return Z;a===Ae&&(t.key=null);let o=await Bt("value",t.value,r,i);if(o===Z)return Z;o===Ae&&(t.value=null)}}return n}function ul(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 dl(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(F.isMap(t))return r.Map?.(e,t,i);if(F.isSeq(t))return r.Seq?.(e,t,i);if(F.isPair(t))return r.Pair?.(e,t,i);if(F.isScalar(t))return r.Scalar?.(e,t,i);if(F.isAlias(t))return r.Alias?.(e,t,i)}function fl(e,t,r){let i=t[t.length-1];if(F.isCollection(i))i.items[e]=r;else if(F.isPair(i))e==="key"?i.key=r:i.value=r;else if(F.isDocument(i))i.contents=r;else{let n=F.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Za.visit=Vi;Za.visitAsync=Mi});var eo=w(pl=>{"use strict";var hl=P(),lm=kr(),um={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},dm=e=>e.replace(/[!,[\]{}]/g,t=>um[t]),Sr=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+dm(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&&hl.isNode(t.contents)){let a={};lm.visit(t.contents,(o,s)=>{hl.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
|
+
`)}};Sr.defaultYaml={explicit:!1,version:"1.2"};Sr.defaultTags={"!!":"tag:yaml.org,2002:"};pl.Directives=Sr});var Fi=w(Er=>{"use strict";var ml=P(),fm=kr();function hm(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 vl(e){let t=new Set;return fm.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function gl(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function pm(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=vl(e));let o=gl(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(ml.isScalar(o.node)||ml.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}}Er.anchorIsValid=hm;Er.anchorNames=vl;Er.createNodeAnchors=pm;Er.findNewAnchor=gl});var to=w(wl=>{"use strict";function xr(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=xr(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=xr(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=xr(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=xr(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}wl.applyReviver=xr});var Ze=w(Nl=>{"use strict";var mm=P();function yl(e,t,r){if(Array.isArray(e))return e.map((i,n)=>yl(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!mm.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}Nl.toJS=yl});var qi=w(kl=>{"use strict";var vm=to(),bl=P(),gm=Ze(),ro=class{constructor(t){Object.defineProperty(this,bl.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(!bl.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=gm.toJS(this,"",o);if(typeof n=="function")for(let{count:l,res:c}of o.anchors.values())n(c,l);return typeof a=="function"?vm.applyReviver(a,{"":s},"",s):s}};kl.NodeBase=ro});var Cr=w(Sl=>{"use strict";var wm=Fi(),ym=kr(),Vt=P(),Nm=qi(),bm=Ze(),io=class extends Nm.NodeBase{constructor(t){super(Vt.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=[],ym.visit(t,{Node:(a,o)=>{(Vt.isAlias(o)||Vt.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 l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let s=i.get(o);if(s||(bm.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=Wi(n,o,i)),s.count*s.aliasCount>a)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(wm.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 Wi(e,t,r){if(Vt.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Vt.isCollection(t)){let i=0;for(let n of t.items){let a=Wi(e,n,r);a>i&&(i=a)}return i}else if(Vt.isPair(t)){let i=Wi(e,t.key,r),n=Wi(e,t.value,r);return Math.max(i,n)}return 1}Sl.Alias=io});var H=w(no=>{"use strict";var km=P(),Sm=qi(),Em=Ze(),xm=e=>!e||typeof e!="function"&&typeof e!="object",et=class extends Sm.NodeBase{constructor(t){super(km.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Em.toJS(this.value,t,r)}toString(){return String(this.value)}};et.BLOCK_FOLDED="BLOCK_FOLDED";et.BLOCK_LITERAL="BLOCK_LITERAL";et.PLAIN="PLAIN";et.QUOTE_DOUBLE="QUOTE_DOUBLE";et.QUOTE_SINGLE="QUOTE_SINGLE";no.Scalar=et;no.isScalarValue=xm});var Pr=w(xl=>{"use strict";var Cm=Cr(),yt=P(),El=H(),Pm="tag:yaml.org,2002:";function Rm(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 Am(e,t,r){if(yt.isDocument(e)&&(e=e.contents),yt.isNode(e))return e;if(yt.isPair(e)){let d=r.schema[yt.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,l;if(i&&e&&typeof e=="object"){if(l=s.get(e),l)return l.anchor??(l.anchor=n(e)),new Cm.Alias(l.anchor);l={anchor:null,node:null},s.set(e,l)}t?.startsWith("!!")&&(t=Pm+t.slice(2));let c=Rm(e,t,o.tags);if(!c){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new El.Scalar(e);return l&&(l.node=d),d}c=e instanceof Map?o[yt.MAP]:Symbol.iterator in Object(e)?o[yt.SEQ]:o[yt.MAP]}a&&(a(c),delete r.onTagObj);let f=c?.createNode?c.createNode(r.schema,e,r):typeof c?.nodeClass?.from=="function"?c.nodeClass.from(r.schema,e,r):new El.Scalar(e);return t?f.tag=t:c.default||(f.tag=c.tag),l&&(l.node=f),f}xl.createNode=Am});var Ji=w(zi=>{"use strict";var _m=Pr(),_e=P(),Im=qi();function ao(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 _m.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 Cl=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,oo=class extends Im.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=>_e.isNode(i)||_e.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(Cl(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(_e.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,ao(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(_e.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&&_e.isScalar(a)?a.value:a:_e.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!_e.isPair(r))return!1;let i=r.value;return i==null||t&&_e.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 _e.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(_e.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,ao(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};zi.Collection=oo;zi.collectionFromPath=ao;zi.isEmptyPath=Cl});var Rr=w(Gi=>{"use strict";var Tm=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function so(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var jm=(e,t,r)=>e.endsWith(`
|
|
7
7
|
`)?so(r,t):r.includes(`
|
|
8
8
|
`)?`
|
|
9
9
|
`+so(r,t):(e.endsWith(" ")?"":" ")+r;Gi.indentComment=so;Gi.lineComment=jm;Gi.stringifyComment=Tm});var Rl=w(Ar=>{"use strict";var $m="flow",co="block",Ui="quoted";function Om(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 l=Math.max(1+a,1+n-t.length);if(e.length<=l)return e;let c=[],f={},d=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?c.push(0):d=n-i);let u,p,m=!1,h=-1,v=-1,g=-1;r===co&&(h=Pl(e,h,t.length),h!==-1&&(d=h+l));for(let b;b=e[h+=1];){if(r===Ui&&b==="\\"){switch(v=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}g=h}if(b===`
|
|
@@ -12,7 +12,7 @@ var Cp=Object.create;var Qc=Object.defineProperty;var Pp=Object.getOwnPropertyDe
|
|
|
12
12
|
`&&S!==" "&&(u=h)}if(h>=d)if(u)c.push(u),d=u+l,u=void 0;else if(r===Ui){for(;p===" "||p===" ";)p=b,b=e[h+=1],m=!0;let S=h>g+1?h-2:v-1;if(f[S])return e;c.push(S),f[S]=!0,d=S+l,u=void 0}else m=!0}p=b}if(m&&s&&s(),c.length===0)return e;o&&o();let N=e.slice(0,c[0]);for(let b=0;b<c.length;++b){let S=c[b],x=c[b+1]||e.length;S===0?N=`
|
|
13
13
|
${t}${e.slice(0,x)}`:(r===Ui&&f[S]&&(N+=`${e[S]}\\`),N+=`
|
|
14
14
|
${t}${e.slice(S+1,x)}`)}return N}function Pl(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}Ar.FOLD_BLOCK=co;Ar.FOLD_FLOW=$m;Ar.FOLD_QUOTED=Ui;Ar.foldFlowLines=Om});var Ir=w(Al=>{"use strict";var
|
|
15
|
+
`);i=t,n=t+1,a=e[n]}return i}Ar.FOLD_BLOCK=co;Ar.FOLD_FLOW=$m;Ar.FOLD_QUOTED=Ui;Ar.foldFlowLines=Om});var Ir=w(Al=>{"use strict";var ye=H(),tt=Rl(),Yi=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Xi=e=>/^(%|---|\.\.\.)/m.test(e);function Hm(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 _r(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Xi(e)?" ":""),o="",s=0;for(let l=0,c=r[l];c;c=r[++l])if(c===" "&&r[l+1]==="\\"&&r[l+2]==="n"&&(o+=r.slice(s,l)+"\\ ",l+=1,s=l,c="\\"),c==="\\")switch(r[l+1]){case"u":{o+=r.slice(s,l);let f=r.substr(l+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(l,6)}l+=5,s=l+1}break;case"n":if(i||r[l+2]==='"'||r.length<n)l+=1;else{for(o+=r.slice(s,l)+`
|
|
17
17
|
|
|
18
18
|
`;r[l+2]==="\\"&&r[l+3]==="n"&&r[l+4]!=='"';)o+=`
|
|
@@ -21,20 +21,20 @@ ${t}${e.slice(S+1,x)}`)}return N}function Pl(e,t,r){let i=t,n=t+1,a=e[n];for(;a=
|
|
|
21
21
|
${r}`)+"'";return t.implicitKey?i:tt.foldFlowLines(i,r,tt.FOLD_FLOW,Yi(t,!1))}function Mt(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=_r;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=lo:a&&!n?i=_r:i=r?lo:_r}return i(e,t)}var uo;try{uo=new RegExp(`(^|(?<!
|
|
22
22
|
))
|
|
23
23
|
+(?!
|
|
24
|
-
|$)`,"g")}catch{uo=/\n+(?!\n|$)/g}function Ki({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:l}=i.options;if(!o||/\n[\t ]+$/.test(r))return Mt(r,i);let c=i.indent||(i.forceBlockIndent||Xi(r)?" ":""),f=o==="literal"?!0:o==="folded"||t===
|
|
24
|
+
|$)`,"g")}catch{uo=/\n+(?!\n|$)/g}function Ki({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:l}=i.options;if(!o||/\n[\t ]+$/.test(r))return Mt(r,i);let c=i.indent||(i.forceBlockIndent||Xi(r)?" ":""),f=o==="literal"?!0:o==="folded"||t===ye.Scalar.BLOCK_FOLDED?!1:t===ye.Scalar.BLOCK_LITERAL?!0:!Hm(r,l,c.length);if(!r)return f?`|
|
|
25
25
|
`:`>
|
|
26
26
|
`;let d,u;for(u=r.length;u>0;--u){let x=r[u-1];if(x!==`
|
|
27
27
|
`&&x!==" "&&x!==" ")break}let p=r.substring(u),m=p.indexOf(`
|
|
28
28
|
`);m===-1?d="-":r===p||m!==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(uo,`$&${c}`));let h=!1,v,g=-1;for(v=0;v<r.length;++v){let x=r[v];if(x===" ")h=!0;else if(x===`
|
|
30
30
|
`)g=v;else break}let N=r.substring(0,g<v?g+1:v);N&&(r=r.substring(N.length),N=N.replace(/\n+/g,`$&${c}`));let S=(h?c?"2":"1":"")+d;if(e&&(S+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!f){let x=r.replace(/\n+/g,`
|
|
31
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${c}`),E=!1,I=Yi(i,!0);o!=="folded"&&t!==
|
|
31
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${c}`),E=!1,I=Yi(i,!0);o!=="folded"&&t!==ye.Scalar.BLOCK_FOLDED&&(I.onOverflow=()=>{E=!0});let k=tt.foldFlowLines(`${N}${x}${p}`,c,tt.FOLD_BLOCK,I);if(!E)return`>${S}
|
|
32
32
|
${c}${k}`}return r=r.replace(/\n+/g,`$&${c}`),`|${S}
|
|
33
33
|
${c}${N}${r}${p}`}function Dm(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:l,indentStep:c,inFlow:f}=t;if(s&&a.includes(`
|
|
34
34
|
`)||f&&/[[\]{},]/.test(a))return Mt(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||f||!a.includes(`
|
|
35
|
-
`)?Mt(a,t):Ki(e,t,r,i);if(!s&&!f&&n!==
|
|
35
|
+
`)?Mt(a,t):Ki(e,t,r,i);if(!s&&!f&&n!==ye.Scalar.PLAIN&&a.includes(`
|
|
36
36
|
`))return Ki(e,t,r,i);if(Xi(a)){if(l==="")return t.forceBlockIndent=!0,Ki(e,t,r,i);if(s&&l===c)return Mt(a,t)}let d=a.replace(/\n+/g,`$&
|
|
37
|
-
${l}`);if(o){let u=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:m}=t.doc.schema;if(m.some(u)||p?.some(u))return Mt(a,t)}return s?d:tt.foldFlowLines(d,l,tt.FOLD_FLOW,Yi(t,!1))}function Lm(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!==
|
|
37
|
+
${l}`);if(o){let u=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:m}=t.doc.schema;if(m.some(u)||p?.some(u))return Mt(a,t)}return s?d:tt.foldFlowLines(d,l,tt.FOLD_FLOW,Yi(t,!1))}function Lm(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!==ye.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=ye.Scalar.QUOTE_DOUBLE);let l=f=>{switch(f){case ye.Scalar.BLOCK_FOLDED:case ye.Scalar.BLOCK_LITERAL:return n||a?Mt(o.value,t):Ki(o,t,r,i);case ye.Scalar.QUOTE_DOUBLE:return _r(o.value,t);case ye.Scalar.QUOTE_SINGLE:return lo(o.value,t);case ye.Scalar.PLAIN:return Dm(o,t,r,i);default:return null}},c=l(s);if(c===null){let{defaultKeyType:f,defaultStringType:d}=t.options,u=n&&f||d;if(c=l(u),c===null)throw new Error(`Unsupported default string type ${u}`)}return c}Al.stringifyString=Lm});var Tr=w(fo=>{"use strict";var Bm=Fi(),rt=P(),Vm=Rr(),Mm=Ir();function Fm(e,t){let r=Object.assign({blockQuote:!0,commentString:Vm.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 qm(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(rt.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 Wm(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(rt.isScalar(e)||rt.isCollection(e))&&e.anchor;a&&Bm.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 zm(e,t,r,i){if(rt.isPair(e))return e.toString(t,r,i);if(rt.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=rt.isNode(e)?e:t.doc.createNode(e,{onTagObj:l=>n=l});n??(n=qm(t.doc.schema.tags,a));let o=Wm(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):rt.isScalar(a)?Mm.stringifyString(a,t,r,i):a.toString(t,r,i);return o?rt.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
38
38
|
${t.indent}${s}`:s}fo.createStringifyContext=Fm;fo.stringify=zm});var jl=w(Tl=>{"use strict";var qe=P(),_l=H(),Il=Tr(),jr=Rr();function Jm({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:l,options:{commentString:c,indentSeq:f,simpleKeys:d}}=r,u=qe.isNode(e)&&e.comment||null;if(d){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(qe.isCollection(e)||!qe.isNode(e)&&typeof e=="object"){let I="With simple keys, collection cannot be used as a key value";throw new Error(I)}}let p=!d&&(!e||u&&t==null&&!r.inFlow||qe.isCollection(e)||(qe.isScalar(e)?e.type===_l.Scalar.BLOCK_FOLDED||e.type===_l.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+l});let m=!1,h=!1,v=Il.stringify(e,r,()=>m=!0,()=>h=!0);if(!p&&!r.inFlow&&v.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 m&&i&&i(),v===""?"?":p?`? ${v}`:v}else if(a&&!d||t==null&&p)return v=`? ${v}`,u&&!m?v+=jr.lineComment(v,r.indent,c(u)):h&&n&&n(),v;m&&(u=null),p?(u&&(v+=jr.lineComment(v,r.indent,c(u))),v=`? ${v}
|
|
39
39
|
${s}:`):(v=`${v}:`,u&&(v+=jr.lineComment(v,r.indent,c(u))));let g,N,b;qe.isNode(t)?(g=!!t.spaceBefore,N=t.commentBefore,b=t.comment):(g=!1,N=null,b=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!p&&!u&&qe.isScalar(t)&&(r.indentAtStart=v.length+1),h=!1,!f&&l.length>=2&&!r.inFlow&&!p&&qe.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let S=!1,x=Il.stringify(t,r,()=>S=!0,()=>h=!0),E=" ";if(u||g||N){if(E=g?`
|
|
40
40
|
`:"",N){let I=c(N);E+=`
|
|
@@ -58,7 +58,7 @@ ${n.key.commentBefore}`:i.commentBefore),i.comment){let a=n.value??n.key;a.comme
|
|
|
58
58
|
${a.comment}`:i.comment}i=n}e.items[r]=vn.isPair(i)?i:new To.Pair(i)}}else t("Expected a sequence for this tag");return e}function du(e,t,r){let{replacer:i}=r,n=new zv.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(a++),o));let s,l;if(Array.isArray(o))if(o.length===2)s=o[0],l=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let c=Object.keys(o);if(c.length===1)s=c[0],l=o[s];else throw new TypeError(`Expected tuple with one key, not ${c.length} keys`)}else s=o;n.items.push(To.createPair(s,l,r))}return n}var Jv={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:uu,createNode:du};gn.createPairs=du;gn.pairs=Jv;gn.resolvePairs=uu});var Oo=w($o=>{"use strict";var fu=P(),jo=Ze(),Dr=at(),Gv=ot(),hu=wn(),bt=class e extends Gv.YAMLSeq{constructor(){super(),this.add=Dr.YAMLMap.prototype.add.bind(this),this.delete=Dr.YAMLMap.prototype.delete.bind(this),this.get=Dr.YAMLMap.prototype.get.bind(this),this.has=Dr.YAMLMap.prototype.has.bind(this),this.set=Dr.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(fu.isPair(n)?(a=jo.toJS(n.key,"",r),o=jo.toJS(n.value,a,r)):a=jo.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(t,r,i){let n=hu.createPairs(t,r,i),a=new this;return a.items=n.items,a}};bt.tag="tag:yaml.org,2002:omap";var Uv={collection:"seq",identify:e=>e instanceof Map,nodeClass:bt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=hu.resolvePairs(e,t),i=[];for(let{key:n}of r.items)fu.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new bt,r)},createNode:(e,t,r)=>bt.from(e,t,r)};$o.YAMLOMap=bt;$o.omap=Uv});var wu=w(Ho=>{"use strict";var pu=H();function mu({value:e,source:t},r){return t&&(e?vu:gu).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var vu={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new pu.Scalar(!0),stringify:mu},gu={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new pu.Scalar(!1),stringify:mu};Ho.falseTag=gu;Ho.trueTag=vu});var yu=w(yn=>{"use strict";var Kv=H(),Do=Wt(),Yv={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Do.stringifyNumber},Xv={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Do.stringifyNumber(e)}},Qv={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new Kv.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let i=e.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:Do.stringifyNumber};yn.float=Qv;yn.floatExp=Xv;yn.floatNaN=Yv});var bu=w(Br=>{"use strict";var Nu=Wt(),Lr=e=>typeof e=="bigint"||Number.isInteger(e);function Nn(e,t,r,{intAsBigInt:i}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,r);return n==="-"?-1*a:a}function Lo(e,t,r){let{value:i}=e;if(Lr(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return Nu.stringifyNumber(e)}var Zv={identify:Lr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Nn(e,2,2,r),stringify:e=>Lo(e,2,"0b")},eg={identify:Lr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Nn(e,1,8,r),stringify:e=>Lo(e,8,"0")},tg={identify:Lr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Nn(e,0,10,r),stringify:Nu.stringifyNumber},rg={identify:Lr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Nn(e,2,16,r),stringify:e=>Lo(e,16,"0x")};Br.int=tg;Br.intBin=Zv;Br.intHex=rg;Br.intOct=eg});var Vo=w(Bo=>{"use strict";var Sn=P(),bn=it(),kn=at(),kt=class e extends kn.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Sn.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new bn.Pair(t.key,null):r=new bn.Pair(t,null),kn.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=kn.findPair(this.items,t);return!r&&Sn.isPair(i)?Sn.isScalar(i.key)?i.key.value:i.key:i}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=kn.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new bn.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(bn.createPair(o,null,i));return a}};kt.tag="tag:yaml.org,2002:set";var ig={collection:"map",identify:e=>e instanceof Set,nodeClass:kt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>kt.from(e,t,r),resolve(e,t){if(Sn.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new kt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Bo.YAMLSet=kt;Bo.set=ig});var Fo=w(En=>{"use strict";var ng=Wt();function Mo(e,t){let r=e[0],i=r==="-"||r==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=i.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return r==="-"?n(-1)*a:a}function ku(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return ng.stringifyNumber(e);let i="";t<0&&(i="-",t*=r(-1));let n=r(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var ag={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>Mo(e,r),stringify:ku},og={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>Mo(e,!1),stringify:ku},Su={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(Su.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),l=t[7]?Number((t[7]+"00").substr(1,3)):0,c=Date.UTC(r,i-1,n,a||0,o||0,s||0,l),f=t[8];if(f&&f!=="Z"){let d=Mo(f,!1);Math.abs(d)<30&&(d*=60),c-=6e4*d}return new Date(c)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};En.floatTime=og;En.intTime=ag;En.timestamp=Su});var Cu=w(xu=>{"use strict";var sg=Ft(),cg=dn(),lg=qt(),ug=Or(),dg=Io(),Eu=wu(),qo=yu(),xn=bu(),fg=rn(),hg=Oo(),pg=wn(),mg=Vo(),Wo=Fo(),vg=[sg.map,lg.seq,ug.string,cg.nullTag,Eu.trueTag,Eu.falseTag,xn.intBin,xn.intOct,xn.int,xn.intHex,qo.floatNaN,qo.floatExp,qo.float,dg.binary,fg.merge,hg.omap,pg.pairs,mg.set,Wo.intTime,Wo.floatTime,Wo.timestamp];xu.schema=vg});var Hu=w(Go=>{"use strict";var _u=Ft(),gg=dn(),Iu=qt(),wg=Or(),yg=So(),zo=xo(),Jo=Po(),Ng=au(),bg=cu(),Tu=Io(),Vr=rn(),ju=Oo(),$u=wn(),Pu=Cu(),Ou=Vo(),Cn=Fo(),Ru=new Map([["core",Ng.schema],["failsafe",[_u.map,Iu.seq,wg.string]],["json",bg.schema],["yaml11",Pu.schema],["yaml-1.1",Pu.schema]]),Au={binary:Tu.binary,bool:yg.boolTag,float:zo.float,floatExp:zo.floatExp,floatNaN:zo.floatNaN,floatTime:Cn.floatTime,int:Jo.int,intHex:Jo.intHex,intOct:Jo.intOct,intTime:Cn.intTime,map:_u.map,merge:Vr.merge,null:gg.nullTag,omap:ju.omap,pairs:$u.pairs,seq:Iu.seq,set:Ou.set,timestamp:Cn.timestamp},kg={"tag:yaml.org,2002:binary":Tu.binary,"tag:yaml.org,2002:merge":Vr.merge,"tag:yaml.org,2002:omap":ju.omap,"tag:yaml.org,2002:pairs":$u.pairs,"tag:yaml.org,2002:set":Ou.set,"tag:yaml.org,2002:timestamp":Cn.timestamp};function Sg(e,t,r){let i=Ru.get(t);if(i&&!e)return r&&!i.includes(Vr.merge)?i.concat(Vr.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Ru.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return r&&(n=n.concat(Vr.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Au[o]:o;if(!s){let l=JSON.stringify(o),c=Object.keys(Au).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${c}`)}return a.includes(s)||a.push(s),a},[])}Go.coreKnownTags=kg;Go.getTags=Sg});var Yo=w(Du=>{"use strict";var Uo=P(),Eg=Ft(),xg=qt(),Cg=Or(),Pn=Hu(),Pg=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Ko=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Pn.getTags(t,"compat"):t?Pn.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Pn.coreKnownTags:{},this.tags=Pn.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Uo.MAP,{value:Eg.map}),Object.defineProperty(this,Uo.SCALAR,{value:Cg.string}),Object.defineProperty(this,Uo.SEQ,{value:xg.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Pg:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Du.Schema=Ko});var Bu=w(Lu=>{"use strict";var Rg=P(),Xo=Tr(),Mr=Rr();function Ag(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let l=e.directives.toString(e);l?(r.push(l),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=Xo.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let l=a(e.commentBefore);r.unshift(Mr.indentComment(l,""))}let o=!1,s=null;if(e.contents){if(Rg.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let f=a(e.contents.commentBefore);r.push(Mr.indentComment(f,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let l=s?void 0:()=>o=!0,c=Xo.stringify(e.contents,n,()=>s=null,l);s&&(c+=Mr.lineComment(c,"",a(s))),(c[0]==="|"||c[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${c}`:r.push(c)}else r.push(Xo.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let l=a(e.comment);l.includes(`
|
|
59
59
|
`)?(r.push("..."),r.push(Mr.indentComment(l,""))):r.push(`... ${l}`)}else r.push("...");else{let l=e.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(Mr.indentComment(a(l),"")))}return r.join(`
|
|
60
60
|
`)+`
|
|
61
|
-
`}Lu.stringifyDocument=Ag});var Fr=w(Vu=>{"use strict";var _g=Cr(),zt=Ji(),
|
|
61
|
+
`}Lu.stringifyDocument=Ag});var Fr=w(Vu=>{"use strict";var _g=Cr(),zt=Ji(),le=P(),Ig=it(),Tg=Ze(),jg=Yo(),$g=Bu(),Qo=Fi(),Og=to(),Hg=Pr(),Zo=eo(),es=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,le.NODE_TYPE,{value:le.DOC});let n=null;typeof r=="function"||Array.isArray(r)?n=r:i===void 0&&r&&(i=r,r=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=a;let{version:o}=a;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Zo.Directives({version:o}),this.setSchema(o,i),this.contents=t===void 0?null:this.createNode(t,n,i)}clone(){let t=Object.create(e.prototype,{[le.NODE_TYPE]:{value:le.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=le.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Jt(this.contents)&&this.contents.add(t)}addIn(t,r){Jt(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=Qo.anchorNames(this);t.anchor=!r||i.has(r)?Qo.findNewAnchor(r||"a",i):r}return new _g.Alias(t.anchor)}createNode(t,r,i){let n;if(typeof r=="function")t=r.call({"":t},"",t),n=r;else if(Array.isArray(r)){let v=N=>typeof N=="number"||N instanceof String||N instanceof Number,g=r.filter(v).map(String);g.length>0&&(r=r.concat(g)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:l,onTagObj:c,tag:f}=i??{},{onAnchor:d,setAnchors:u,sourceObjects:p}=Qo.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:l??!1,onAnchor:d,onTagObj:c,replacer:n,schema:this.schema,sourceObjects:p},h=Hg.createNode(t,f,m);return s&&le.isCollection(h)&&(h.flow=!0),u(),h}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new Ig.Pair(n,a)}delete(t){return Jt(this.contents)?this.contents.delete(t):!1}deleteIn(t){return zt.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Jt(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return le.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return zt.isEmptyPath(t)?!r&&le.isScalar(this.contents)?this.contents.value:this.contents:le.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return le.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return zt.isEmptyPath(t)?this.contents!==void 0:le.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=zt.collectionFromPath(this.schema,[t],r):Jt(this.contents)&&this.contents.set(t,r)}setIn(t,r){zt.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=zt.collectionFromPath(this.schema,Array.from(t),r):Jt(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let i;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Zo.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Zo.Directives({version:t}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(i)this.schema=new jg.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},l=Tg.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:c,res:f}of s.anchors.values())a(f,c);return typeof o=="function"?Og.applyReviver(o,{"":l},"",l):l}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return $g.stringifyDocument(this,t)}};function Jt(e){if(le.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Vu.Document=es});var zr=w(Wr=>{"use strict";var qr=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},ts=class extends qr{constructor(t,r,i){super("YAMLParseError",t,r,i)}},rs=class extends qr{constructor(t,r,i){super("YAMLWarning",t,r,i)}},Dg=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
|
|
62
62
|
`),o=s+o}if(/[^ ]/.test(o)){let s=1,l=r.linePos[1];l?.line===i&&l.col>n&&(s=Math.max(1,Math.min(l.col-n,80-a)));let c=" ".repeat(a)+"^".repeat(s);r.message+=`:
|
|
63
63
|
|
|
64
64
|
${o}
|
|
@@ -117,24 +117,24 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
|
|
|
117
117
|
`});for(let l of Object.keys(e))l!=="type"&&l!=="offset"&&delete e[l];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function xd(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 gs(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})}}}An.createScalarToken=Kw;An.resolveAsScalar=Uw;An.setScalarValue=Yw});var Rd=w(Pd=>{"use strict";var Qw=e=>"type"in e?In(e):_n(e);function In(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=In(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=_n(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=_n(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=_n(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 _n({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=In(t)),r)for(let a of r)n+=a.source;return i&&(n+=In(i)),n}Pd.stringify=Qw});var Td=w(Id=>{"use strict";var ws=Symbol("break visit"),Zw=Symbol("skip children"),Ad=Symbol("remove item");function Et(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),_d(Object.freeze([]),e,t)}Et.BREAK=ws;Et.SKIP=Zw;Et.REMOVE=Ad;Et.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};Et.parentCollection=(e,t)=>{let r=Et.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 _d(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=_d(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===ws)return ws;s===Ad&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}Id.visit=Et});var Tn=w(ee=>{"use strict";var ys=Cd(),ey=Rd(),ty=Td(),Ns="\uFEFF",bs="",ks="",Ss="",ry=e=>!!e&&"items"in e,iy=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function ny(e){switch(e){case Ns:return"<BOM>";case bs:return"<DOC>";case ks:return"<FLOW_END>";case Ss:return"<SCALAR>";default:return JSON.stringify(e)}}function ay(e){switch(e){case Ns:return"byte-order-mark";case bs:return"doc-mode";case ks:return"flow-error-end";case Ss: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}ee.createScalarToken=ys.createScalarToken;ee.resolveAsScalar=ys.resolveAsScalar;ee.setScalarValue=ys.setScalarValue;ee.stringify=ey.stringify;ee.visit=ty.visit;ee.BOM=Ns;ee.DOCUMENT=bs;ee.FLOW_END=ks;ee.SCALAR=Ss;ee.isCollection=ry;ee.isScalar=iy;ee.prettyToken=ny;ee.tokenType=ay});var Cs=w($d=>{"use strict";var Kr=Tn();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}ee.createScalarToken=ys.createScalarToken;ee.resolveAsScalar=ys.resolveAsScalar;ee.setScalarValue=ys.setScalarValue;ee.stringify=ey.stringify;ee.visit=ty.visit;ee.BOM=Ns;ee.DOCUMENT=bs;ee.FLOW_END=ks;ee.SCALAR=Ss;ee.isCollection=ry;ee.isScalar=iy;ee.prettyToken=ny;ee.tokenType=ay});var Cs=w($d=>{"use strict";var Kr=Tn();function Ne(e){switch(e){case void 0:case" ":case`
|
|
121
121
|
`:case"\r":case" ":return!0;default:return!1}}var jd=new Set("0123456789ABCDEFabcdef"),oy=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),jn=new Set(",[]{}"),sy=new Set(` ,[]{}
|
|
122
122
|
\r `),Es=e=>!e||sy.has(e),xs=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]===Kr.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 Kr.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==="...")&&Ne(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]===Kr.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 Kr.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==="...")&&Ne(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&&!Ne(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===":")&&Ne(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(Es),"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("..."))&&Ne(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield Kr.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(Es),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ne(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=>Ne(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 Kr.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 Kr.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(Ne(a)||t&&jn.has(a))break;r=i}else if(Ne(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&&jn.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&&jn.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Kr.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(Es),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&&jn.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Kr.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(Es),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Ne(i)||r&&jn.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(;!Ne(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(oy.has(r))r=this.buffer[++t];else if(r==="%"&&jd.has(this.buffer[t+1])&&jd.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)}};$d.Lexer=xs});var Rs=w(Od=>{"use strict";var Ps=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}}}};Od.LineCounter=Ps});var _s=w(Vd=>{"use strict";var cy=Ti("process"),Hd=Tn(),ly=Cs();function st(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function Dd(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 Bd(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 $n(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 Ut(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 On(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 Ld(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!st(t.start,"explicit-key-ind")&&!st(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Bd(t.value)?t.value.end?On(t.value.end,t.sep):t.value.end=t.sep:On(t.start,t.sep),delete t.sep)}var As=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 ly.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,cy.env.LOG_TOKENS&&console.log("|",Hd.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=Hd.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"&&Ld(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&&Dd(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":{Dd(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=$n(this.peek(2)),i=Ut(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,19 +142,19 @@ ${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=$n(t),i=Ut(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=$n(t),i=Ut(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())}}};Vd.Parser=As});var zd=w(Xr=>{"use strict";var Md=vs(),uy=Fr(),Yr=zr(),dy=po(),fy=P(),hy=Rs(),Fd=_s();function qd(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new hy.LineCounter||null,prettyErrors:t}}function py(e,t={}){let{lineCounter:r,prettyErrors:i}=qd(t),n=new Fd.Parser(r?.addNewLine),a=new Md.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(Yr.prettifyError(e,r)),s.warnings.forEach(Yr.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Wd(e,t={}){let{lineCounter:r,prettyErrors:i}=qd(t),n=new Fd.Parser(r?.addNewLine),a=new Md.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 Yr.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(Yr.prettifyError(e,r)),o.warnings.forEach(Yr.prettifyError(e,r))),o}function my(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=Wd(e,r);if(!n)return null;if(n.warnings.forEach(a=>dy.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 vy(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 fy.isDocument(e)&&!i?e.toString(r):new uy.Document(e,i,r).toString(r)}Xr.parse=my;Xr.parseAllDocuments=py;Xr.parseDocument=Wd;Xr.stringify=vy});var Kt=w(A=>{"use strict";var gy=vs(),wy=Fr(),yy=Yo(),Is=zr(),Ny=Cr(),ct=P(),by=it(),ky=H(),Sy=at(),Ey=ot(),xy=Tn(),Cy=Cs(),Py=Rs(),Ry=_s(),Hn=zd(),Jd=kr();A.Composer=gy.Composer;A.Document=wy.Document;A.Schema=yy.Schema;A.YAMLError=Is.YAMLError;A.YAMLParseError=Is.YAMLParseError;A.YAMLWarning=Is.YAMLWarning;A.Alias=Ny.Alias;A.isAlias=ct.isAlias;A.isCollection=ct.isCollection;A.isDocument=ct.isDocument;A.isMap=ct.isMap;A.isNode=ct.isNode;A.isPair=ct.isPair;A.isScalar=ct.isScalar;A.isSeq=ct.isSeq;A.Pair=by.Pair;A.Scalar=ky.Scalar;A.YAMLMap=Sy.YAMLMap;A.YAMLSeq=Ey.YAMLSeq;A.CST=xy;A.Lexer=Cy.Lexer;A.LineCounter=Py.LineCounter;A.Parser=Ry.Parser;A.parse=Hn.parse;A.parseAllDocuments=Hn.parseAllDocuments;A.parseDocument=Hn.parseDocument;A.stringify=Hn.stringify;A.visit=Jd.visit;A.visitAsync=Jd.visitAsync});function Iy(e,t){return Ts[e][t]}function js(e){return Ud.get(e.trim().toLocaleLowerCase("en-US"))??null}function Dn(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${Iy(e,r)}
|
|
144
144
|
`).join(`
|
|
145
|
-
`)}var Ts,Ay,_y,Ud,Gd,xt=y(()=>{"use strict";Ts={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:"验证预期"}},Ay={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:"结论"}},_y={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:"结论"}},Ud=new Map,Gd=new Map;for(let e of Object.keys(Ts)){for(let[t,r]of Object.entries(Ts[e]))Ud.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Ay[e]))Gd.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(_y[e]))Gd.set(r.toLocaleLowerCase("en-US"),t)}});import lt from"path";function Hy(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||lt.posix.isAbsolute(r)||lt.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 Ct(e){let t=Hy(e,"native.artifact_root");return t.length===0?".":t.join("/")}function ef(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 Mn(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||lt.posix.isAbsolute(i)||lt.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 We(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function tf(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 Ds(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>Bn)throw new Error(`${t} exceeds ${Bn} 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>Vn)throw new Error(`${t} contains more than ${Vn} wildcard tokens`);return e}function Qd(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=>Ds(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function $s(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 Dy(e){if(e===void 0)return{...ne,include:[...ne.include],exclude:[...ne.exclude]};let t=We(e,"native.snapshot");return{include:Qd(t.include,"native.snapshot.include",ne.include),exclude:Qd(t.exclude,"native.snapshot.exclude",ne.exclude),max_files:$s(t.max_files,ne.max_files,"native.snapshot.max_files"),max_total_bytes:$s(t.max_total_bytes,ne.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:$s(t.max_duration_ms,ne.max_duration_ms,"native.snapshot.max_duration_ms")}}function Ly(e){if(e===void 0)return;let t=We(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=We(t.cleanup,"native.pending_root_move.cleanup"),l=s.kind,c=s.state,f=s.manifest_hash;if(l!=="forward-source"&&l!=="restart-staging"&&l!=="rollback-destination"&&l!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(c!=="prepared"&&c!=="quarantined"&&c!=="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:l,state:c,manifestHash:f}}return{id:r,fromArtifactRoot:Ct(i),toArtifactRoot:Ct(n),stage:a,...o?{cleanup:o}:{}}}function By(e){if(e===void 0)return;let t=We(e,"native.finish");if(t.pull_request===void 0)return{};let r=We(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(lt.posix.isAbsolute(i[0])||lt.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??Ty;if(!Number.isSafeInteger(n)||n<1||n>Xd)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Xd}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function Vy(e,t={}){let r=We(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??Hs;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Ly(r.pending_root_move),l=By(r.finish);return{artifact_root:Ct(i),language:tf(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:Dy(r.snapshot),...l?{finish:l}:{},...s?{pending_root_move:s}:{}}}function My(e){let t=We(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:ef(t.artifact_layout),language:tf(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function Fy(e){let r=We(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)=>Mn(i,`hook.allow_paths[${n}]`)))]}}function qy(e){if(e===void 0)return{...Ln};let t=We(e,"memory"),r=t.learning??Ln.learning,i=t.retrieval??Ln.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 Ls(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Wy(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")||lt.posix.isAbsolute(r)||lt.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>Kd)throw new Error(`${t} exceeds ${Kd} 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>Yd)throw new Error(`${t} contains more than ${Yd} wildcard tokens`);return r}function zy(e){let r=Ls(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)=>Wy(i,`knowledge.local.include[${n}]`)))]}}function Jy(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 Gy(e){let t=Ls(e,"knowledge.remote"),r=Jy(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 Uy(e){if(e===void 0)return{...Zd};let t=Ls(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:zy(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:Gy(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 Ky(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function Yy(e,t,r,i,n,a,o,s){let l=e.schema!==void 0;if(!(l||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!l)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 Zr(e,t={}){let r=(0,Os.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=Ky(n.ambient_resume),o=n.hook===void 0?void 0:Fy(n.hook),s=qy(n.memory),l=Uy(n.knowledge),c=n.native===void 0?void 0:Vy(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),f=n.classic===void 0?void 0:My(n.classic),d=Yy(n,o,s,l,c,f,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:l,...o?{hook:o}:{},...c?{native:c}:{},...f?{classic:f}:{}}}function Fn(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...Ln},knowledge:{...Zd},native:{artifact_root:Ct(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Hs,snapshot:{...ne,include:[...ne.include],exclude:[...ne.exclude]}}}}var Os,Qr,Bn,Vn,Kd,Yd,Hs,Ln,Zd,Ty,Xd,jy,$y,Oy,ne,ut=y(()=>{"use strict";Os=vr(Kt(),1),Qr=64*1024,Bn=1024,Vn=64,Kd=1024,Yd=64,Hs=5,Ln={learning:!0,retrieval:!0},Zd={provider:"local"},Ty=12e4,Xd=6e5,jy=[".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/**"],$y=["**/.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"],Oy=[...jy,...$y].sort((e,t)=>e.localeCompare(t,"en")),ne={include:["**/*"],exclude:[...Oy],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});import{constants as qn,promises as Pt}from"fs";function Bs(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function rf(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ei(e){return{dev:e.dev,ino:e.ino,birthtime:Bs(e)}}function Wn(e,t){let r=ei(e),i=ei(t);return pe(r,i)?_(r,i):_(r,i)&&Bs(e)===Bs(t)&&rf(e)===rf(t)&&e.size===t.size}async function Yt(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 Pt.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Ne("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Ne("too-large",`${i} exceeds ${t} bytes`);let o=await Pt.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ei(a)});let s=process.platform==="win32"?qn.O_RDONLY:qn.O_RDONLY|qn.O_NOFOLLOW|qn.O_NONBLOCK,l;try{l=await Pt.open(e,s)}catch(c){throw c.code==="ELOOP"?new Ne("not-regular-file",`${i} must be a regular file`,{cause:c}):c}try{let[c,f,d]=await Promise.all([l.stat({bigint:n}),Pt.lstat(e,{bigint:n}),Pt.realpath(e)]);if(!c.isFile()||!f.isFile()||f.isSymbolicLink()||d!==o||!Wn(a,c)||!Wn(a,f))throw new Ne("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:ei(c)}),await r.hooks?.afterOpen?.();let u=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let N=t+1-p,{bytesRead:b}=await l.read(m,0,Math.min(m.length,N),null);if(b===0)break;if(p+=b,p>t)throw new Ne("too-large",`${i} exceeds ${t} bytes`);u.push(Buffer.from(m.subarray(0,b)))}await r.hooks?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([l.stat({bigint:n}),Pt.lstat(e,{bigint:n}),Pt.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!Wn(a,h)||!Wn(a,v))throw new Ne("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:ei(h)}),{bytes:Buffer.concat(u,p),stat:h,realPath:g}}finally{await l.close()}}var Ne,ti=y(()=>{"use strict";yr();Ne=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as zn}from"fs";import dt from"path";function Xy(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Vs(e,t){let r=dt.relative(e,t);return r===""||!dt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${dt.sep}`)}async function nf(e,t){let r=dt.resolve(e),i=await zn.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return zn.realpath(r)}async function af(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=dt.join(n,r[a]);let o;try{o=await zn.lstat(n)}catch(f){if(Xy(f))return{exists:!1,kind:"missing"};throw f}let s=dt.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let l=a===r.length-1;if(!l&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(l&&(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 c=await zn.realpath(n);if(!Vs(t,c))throw new Error(`${i.label} resolves outside the project root`);if(l)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Xt(e,t,r){let i=Mn(t,r.label),n=dt.resolve(e),a=await nf(n,r.label),o=i.split("/"),s=dt.resolve(n,...o);if(!Vs(n,s))throw new Error(`${r.label} must stay inside the project root`);let l=await af(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:l.exists,kind:l.kind}}async function ft(e,t,r,i){let n=await Xt(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 nf(n.projectRoot,i.label);return Yt(n.target,r,{...i,verify:async(o,s)=>{if(!Vs(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await af(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var Rt=y(()=>{"use strict";ti();ut()});import{createHash as Qy}from"crypto";function Zy(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Jn(e,t={}){return(await Gn(e,t)).document}async function eN(e){try{return(await ft(e,ri,Qr,{label:ri})).bytes}catch(t){if(Zy(t))return null;throw t}}function tN(e){return e?{exists:!0,sha256:Qy("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Gn(e,t={}){let r=await eN(e);return{document:r?Zr(r.toString("utf8"),t):null,identity:tN(r)}}async function Ms(e){return(await Jn(e))?.config??null}var ri,Qt=y(()=>{"use strict";ut();Rt();ri=".comet/config.yaml"});var Zt=y(()=>{"use strict";yr()});var xC,Fs=y(()=>{"use strict";Zt();Qt();Rt();xC=16*1024});var zs=y(()=>{"use strict";Zt();ut();Qt();Rt();Fs()});import{existsSync as sf,promises as At}from"fs";import R from"path";import oN from"os";async function Js(e){try{return await At.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function cN(e){try{let t=await At.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function tr(e,t){let r=R.relative(e,t);return r===""||!R.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${R.sep}`)}async function er(e){let t=[],r=e;for(;!await Js(r);){let n=R.dirname(r);if(n===r)break;t.push(R.basename(r)),r=n}let i=await At.realpath(r);return R.resolve(i,...t.reverse())}async function Gs(e){try{return(await At.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Kn(e){let t=R.resolve(e);try{(await At.stat(t)).isDirectory()||(t=R.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=R.resolve(oN.homedir());for(;;){if(!(t===i&&r!==i)){let o=R.join(t,...Un.split("/")),s=t===r||await cN(o);if(await Js(o)&&s)return t}if(await Js(R.join(t,".git")))return t;let a=R.dirname(t);if(a===t)return r;t=a}}function Yn(e){return Ct(e)}async function lN(e,t){let r=Yn(t),i=R.resolve(e,...r.split("/")),n=await At.realpath(e),a=await er(i);if(!tr(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function rr(e,t){let r=Yn(t),i=await lN(e,r),n=R.join(i,"comet");if(await Gs(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([er(i),er(n)]);if(!tr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=R.resolve(e),l=R.join(s,".comet","runtime","native");if(await Gs(l))throw new Error("The Native Runtime root must not be a symbolic link");let[c,f]=await Promise.all([At.realpath(s),er(l)]);if(!tr(c,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:R.join(e,...Un.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:R.join(n,"specs"),changesDir:R.join(n,"changes"),archiveDir:R.join(n,"archive"),runtimeDir:l,changesRuntimeDir:R.join(l,"changes"),locksDir:R.join(l,"locks"),transactionsDir:R.join(l,"transactions")}}function cf(e){if(!sN.test(e))throw new Error(`Invalid Native change name: ${e}`)}function ht(e,t){cf(t);let r=R.join(e.changesRuntimeDir,t);if(!J(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Us(e,t){cf(t);let r=R.join(e.changesDir,t,"runtime");if(!J(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function be(e,t){let r=ht(e,t);if(sf(r))return r;let i=Us(e,t);return sf(i)?i:r}function Ks(e,t){if(!t.startsWith("runtime/")||R.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=R.resolve(e,...t.slice(8).split("/"));if(!J(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function ae(e,t){let r=R.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 tr(R.resolve(e),R.resolve(t))}async function T(e,t){let r=R.resolve(e),i=R.resolve(t);if(!tr(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Gs(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([er(r),er(i)]);if(!tr(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var Un,sN,$=y(()=>{"use strict";ut();Un=".comet/config.yaml",sN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});function dN(e="docs",t="en"){return Fn(e,t)}async function _e(e){let t=(await Jn(e))?.config??null;return t?.native?t:null}async function Xn(e){let t=await _e(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function lf(e){let t=await Kn(e.startPath),r=await _e(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Un} 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?Yn(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??dN(i??"docs"),a=await rr(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var ke=y(()=>{"use strict";ut();Qt();zs();O();$()});import{AsyncLocalStorage as fN}from"async_hooks";import{randomUUID as ff}from"crypto";import{promises as le}from"fs";import hf from"os";import K from"path";function pN(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function mN(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 mf(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 Zn(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return pe(r,i)?_(r,i):_(r,i)&&e.size===t.size}function Ys(e,t){return Zn(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function Ie(e){let t,r;try{let i=await Yt(e,uf,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof Ne?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${uf} 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:mN(JSON.parse(t.toString("utf8")),e),identity:mf(r)}}async function vN(e){return(await Ie(e))?.owner??null}function vf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==hf.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=kN(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function gN(e,t){try{await le.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await le.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Xs(e,t){let r=await Ie(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ys(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await le.mkdir(t,{recursive:!0});let i=K.join(t,`${K.basename(e.file)}.${e.owner.id}.${ff()}.removed`);try{await le.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Ie(i);if(!n||n.owner.id!==e.owner.id||!Zn(n.identity,e.identity))throw await gN(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await le.rm(i,{force:!0}),"removed"}function gf(e){return{id:ff(),pid:process.pid,hostname:hf.hostname(),createdAt:new Date().toISOString(),operation:e}}async function wf(e,t){let r;try{r=await le.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await vN(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=mf(await r.stat({bigint:!0}))}finally{await r.close()}let n=await
|
|
145
|
+
`)}var Ts,Ay,_y,Ud,Gd,xt=y(()=>{"use strict";Ts={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:"验证预期"}},Ay={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:"结论"}},_y={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:"结论"}},Ud=new Map,Gd=new Map;for(let e of Object.keys(Ts)){for(let[t,r]of Object.entries(Ts[e]))Ud.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Ay[e]))Gd.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(_y[e]))Gd.set(r.toLocaleLowerCase("en-US"),t)}});import lt from"path";function Hy(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||lt.posix.isAbsolute(r)||lt.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 Ct(e){let t=Hy(e,"native.artifact_root");return t.length===0?".":t.join("/")}function ef(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 Mn(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||lt.posix.isAbsolute(i)||lt.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 We(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function tf(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 Ds(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>Bn)throw new Error(`${t} exceeds ${Bn} 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>Vn)throw new Error(`${t} contains more than ${Vn} wildcard tokens`);return e}function Qd(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=>Ds(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function $s(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 Dy(e){if(e===void 0)return{...ne,include:[...ne.include],exclude:[...ne.exclude]};let t=We(e,"native.snapshot");return{include:Qd(t.include,"native.snapshot.include",ne.include),exclude:Qd(t.exclude,"native.snapshot.exclude",ne.exclude),max_files:$s(t.max_files,ne.max_files,"native.snapshot.max_files"),max_total_bytes:$s(t.max_total_bytes,ne.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:$s(t.max_duration_ms,ne.max_duration_ms,"native.snapshot.max_duration_ms")}}function Ly(e){if(e===void 0)return;let t=We(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=We(t.cleanup,"native.pending_root_move.cleanup"),l=s.kind,c=s.state,f=s.manifest_hash;if(l!=="forward-source"&&l!=="restart-staging"&&l!=="rollback-destination"&&l!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(c!=="prepared"&&c!=="quarantined"&&c!=="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:l,state:c,manifestHash:f}}return{id:r,fromArtifactRoot:Ct(i),toArtifactRoot:Ct(n),stage:a,...o?{cleanup:o}:{}}}function By(e){if(e===void 0)return;let t=We(e,"native.finish");if(t.pull_request===void 0)return{};let r=We(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(lt.posix.isAbsolute(i[0])||lt.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??Ty;if(!Number.isSafeInteger(n)||n<1||n>Xd)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Xd}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function Vy(e,t={}){let r=We(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??Hs;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Ly(r.pending_root_move),l=By(r.finish);return{artifact_root:Ct(i),language:tf(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:Dy(r.snapshot),...l?{finish:l}:{},...s?{pending_root_move:s}:{}}}function My(e){let t=We(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:ef(t.artifact_layout),language:tf(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function Fy(e){let r=We(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)=>Mn(i,`hook.allow_paths[${n}]`)))]}}function qy(e){if(e===void 0)return{...Ln};let t=We(e,"memory"),r=t.learning??Ln.learning,i=t.retrieval??Ln.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 Ls(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Wy(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")||lt.posix.isAbsolute(r)||lt.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>Kd)throw new Error(`${t} exceeds ${Kd} 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>Yd)throw new Error(`${t} contains more than ${Yd} wildcard tokens`);return r}function zy(e){let r=Ls(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)=>Wy(i,`knowledge.local.include[${n}]`)))]}}function Jy(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 Gy(e){let t=Ls(e,"knowledge.remote"),r=Jy(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 Uy(e){if(e===void 0)return{...Zd};let t=Ls(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:zy(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:Gy(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 Ky(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function Yy(e,t,r,i,n,a,o,s){let l=e.schema!==void 0;if(!(l||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!l)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 Zr(e,t={}){let r=(0,Os.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=Ky(n.ambient_resume),o=n.hook===void 0?void 0:Fy(n.hook),s=qy(n.memory),l=Uy(n.knowledge),c=n.native===void 0?void 0:Vy(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),f=n.classic===void 0?void 0:My(n.classic),d=Yy(n,o,s,l,c,f,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:l,...o?{hook:o}:{},...c?{native:c}:{},...f?{classic:f}:{}}}function Fn(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...Ln},knowledge:{...Zd},native:{artifact_root:Ct(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Hs,snapshot:{...ne,include:[...ne.include],exclude:[...ne.exclude]}}}}var Os,Qr,Bn,Vn,Kd,Yd,Hs,Ln,Zd,Ty,Xd,jy,$y,Oy,ne,ut=y(()=>{"use strict";Os=vr(Kt(),1),Qr=64*1024,Bn=1024,Vn=64,Kd=1024,Yd=64,Hs=5,Ln={learning:!0,retrieval:!0},Zd={provider:"local"},Ty=12e4,Xd=6e5,jy=[".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/**"],$y=["**/.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"],Oy=[...jy,...$y].sort((e,t)=>e.localeCompare(t,"en")),ne={include:["**/*"],exclude:[...Oy],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});import{constants as qn,promises as Pt}from"fs";function Bs(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function rf(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ei(e){return{dev:e.dev,ino:e.ino,birthtime:Bs(e)}}function Wn(e,t){let r=ei(e),i=ei(t);return me(r,i)?_(r,i):_(r,i)&&Bs(e)===Bs(t)&&rf(e)===rf(t)&&e.size===t.size}async function Yt(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 Pt.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new be("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new be("too-large",`${i} exceeds ${t} bytes`);let o=await Pt.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ei(a)});let s=process.platform==="win32"?qn.O_RDONLY:qn.O_RDONLY|qn.O_NOFOLLOW|qn.O_NONBLOCK,l;try{l=await Pt.open(e,s)}catch(c){throw c.code==="ELOOP"?new be("not-regular-file",`${i} must be a regular file`,{cause:c}):c}try{let[c,f,d]=await Promise.all([l.stat({bigint:n}),Pt.lstat(e,{bigint:n}),Pt.realpath(e)]);if(!c.isFile()||!f.isFile()||f.isSymbolicLink()||d!==o||!Wn(a,c)||!Wn(a,f))throw new be("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:ei(c)}),await r.hooks?.afterOpen?.();let u=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let N=t+1-p,{bytesRead:b}=await l.read(m,0,Math.min(m.length,N),null);if(b===0)break;if(p+=b,p>t)throw new be("too-large",`${i} exceeds ${t} bytes`);u.push(Buffer.from(m.subarray(0,b)))}await r.hooks?.beforeFinalCheck?.();let[h,v,g]=await Promise.all([l.stat({bigint:n}),Pt.lstat(e,{bigint:n}),Pt.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!Wn(a,h)||!Wn(a,v))throw new be("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:ei(h)}),{bytes:Buffer.concat(u,p),stat:h,realPath:g}}finally{await l.close()}}var be,ti=y(()=>{"use strict";yr();be=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as zn}from"fs";import dt from"path";function Xy(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Vs(e,t){let r=dt.relative(e,t);return r===""||!dt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${dt.sep}`)}async function nf(e,t){let r=dt.resolve(e),i=await zn.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return zn.realpath(r)}async function af(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=dt.join(n,r[a]);let o;try{o=await zn.lstat(n)}catch(f){if(Xy(f))return{exists:!1,kind:"missing"};throw f}let s=dt.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let l=a===r.length-1;if(!l&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(l&&(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 c=await zn.realpath(n);if(!Vs(t,c))throw new Error(`${i.label} resolves outside the project root`);if(l)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Xt(e,t,r){let i=Mn(t,r.label),n=dt.resolve(e),a=await nf(n,r.label),o=i.split("/"),s=dt.resolve(n,...o);if(!Vs(n,s))throw new Error(`${r.label} must stay inside the project root`);let l=await af(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:l.exists,kind:l.kind}}async function ft(e,t,r,i){let n=await Xt(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 nf(n.projectRoot,i.label);return Yt(n.target,r,{...i,verify:async(o,s)=>{if(!Vs(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await af(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var Rt=y(()=>{"use strict";ti();ut()});import{createHash as Qy}from"crypto";function Zy(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Jn(e,t={}){return(await Gn(e,t)).document}async function eN(e){try{return(await ft(e,ri,Qr,{label:ri})).bytes}catch(t){if(Zy(t))return null;throw t}}function tN(e){return e?{exists:!0,sha256:Qy("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Gn(e,t={}){let r=await eN(e);return{document:r?Zr(r.toString("utf8"),t):null,identity:tN(r)}}async function Ms(e){return(await Jn(e))?.config??null}var ri,Qt=y(()=>{"use strict";ut();Rt();ri=".comet/config.yaml"});var Zt=y(()=>{"use strict";yr()});var xC,Fs=y(()=>{"use strict";Zt();Qt();Rt();xC=16*1024});var zs=y(()=>{"use strict";Zt();ut();Qt();Rt();Fs()});import{existsSync as sf,promises as At}from"fs";import R from"path";import oN from"os";async function Js(e){try{return await At.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function cN(e){try{let t=await At.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function tr(e,t){let r=R.relative(e,t);return r===""||!R.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${R.sep}`)}async function er(e){let t=[],r=e;for(;!await Js(r);){let n=R.dirname(r);if(n===r)break;t.push(R.basename(r)),r=n}let i=await At.realpath(r);return R.resolve(i,...t.reverse())}async function Gs(e){try{return(await At.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Kn(e){let t=R.resolve(e);try{(await At.stat(t)).isDirectory()||(t=R.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=R.resolve(oN.homedir());for(;;){if(!(t===i&&r!==i)){let o=R.join(t,...Un.split("/")),s=t===r||await cN(o);if(await Js(o)&&s)return t}if(await Js(R.join(t,".git")))return t;let a=R.dirname(t);if(a===t)return r;t=a}}function Yn(e){return Ct(e)}async function lN(e,t){let r=Yn(t),i=R.resolve(e,...r.split("/")),n=await At.realpath(e),a=await er(i);if(!tr(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function rr(e,t){let r=Yn(t),i=await lN(e,r),n=R.join(i,"comet");if(await Gs(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([er(i),er(n)]);if(!tr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=R.resolve(e),l=R.join(s,".comet","runtime","native");if(await Gs(l))throw new Error("The Native Runtime root must not be a symbolic link");let[c,f]=await Promise.all([At.realpath(s),er(l)]);if(!tr(c,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:R.join(e,...Un.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:R.join(n,"specs"),changesDir:R.join(n,"changes"),archiveDir:R.join(n,"archive"),runtimeDir:l,changesRuntimeDir:R.join(l,"changes"),locksDir:R.join(l,"locks"),transactionsDir:R.join(l,"transactions")}}function cf(e){if(!sN.test(e))throw new Error(`Invalid Native change name: ${e}`)}function ht(e,t){cf(t);let r=R.join(e.changesRuntimeDir,t);if(!J(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Us(e,t){cf(t);let r=R.join(e.changesDir,t,"runtime");if(!J(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function ke(e,t){let r=ht(e,t);if(sf(r))return r;let i=Us(e,t);return sf(i)?i:r}function Ks(e,t){if(!t.startsWith("runtime/")||R.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=R.resolve(e,...t.slice(8).split("/"));if(!J(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function ae(e,t){let r=R.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 tr(R.resolve(e),R.resolve(t))}async function T(e,t){let r=R.resolve(e),i=R.resolve(t);if(!tr(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Gs(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([er(r),er(i)]);if(!tr(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var Un,sN,$=y(()=>{"use strict";ut();Un=".comet/config.yaml",sN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});function dN(e="docs",t="en"){return Fn(e,t)}async function Ie(e){let t=(await Jn(e))?.config??null;return t?.native?t:null}async function Xn(e){let t=await Ie(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 lf(e){let t=await Kn(e.startPath),r=await Ie(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Un} 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?Yn(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??dN(i??"docs"),a=await rr(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Se=y(()=>{"use strict";ut();Qt();zs();O();$()});import{AsyncLocalStorage as fN}from"async_hooks";import{randomUUID as ff}from"crypto";import{promises as ue}from"fs";import hf from"os";import K from"path";function pN(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function mN(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 mf(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 Zn(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)?_(r,i):_(r,i)&&e.size===t.size}function Ys(e,t){return Zn(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function Te(e){let t,r;try{let i=await Yt(e,uf,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof be?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${uf} 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:mN(JSON.parse(t.toString("utf8")),e),identity:mf(r)}}async function vN(e){return(await Te(e))?.owner??null}function vf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==hf.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=kN(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function gN(e,t){try{await ue.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await ue.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Xs(e,t){let r=await Te(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ys(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await ue.mkdir(t,{recursive:!0});let i=K.join(t,`${K.basename(e.file)}.${e.owner.id}.${ff()}.removed`);try{await ue.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Te(i);if(!n||n.owner.id!==e.owner.id||!Zn(n.identity,e.identity))throw await gN(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await ue.rm(i,{force:!0}),"removed"}function gf(e){return{id:ff(),pid:process.pid,hostname:hf.hostname(),createdAt:new Date().toISOString(),operation:e}}async function wf(e,t){let r;try{r=await ue.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await vN(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=mf(await r.stat({bigint:!0}))}finally{await r.close()}let n=await Te(e);if(!i||!n||n.owner.id!==t.id||!Zn(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function wN(e,t){let r=await T(e.runtimeDir,e.locksDir);await ue.mkdir(r,{recursive:!0});let i=await T(e.runtimeDir,K.join(r,pf));await ue.mkdir(i,{recursive:!0});let n=gf(t),a=K.join(i,`.${n.id}.tmp`),o=K.join(i,`${n.id}.claim`);try{let s=await wf(a,n);await ue.rename(a,o);let l=await Te(o);if(!l||!Zn(s,l.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:l.identity}}finally{await ue.rm(a,{force:!0})}}async function yN(e){let t=K.dirname(e.file),r=!1,i=K.basename(e.file);for(let n of await ue.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=K.join(t,n.name);if(K.resolve(a)!==K.resolve(e.file))try{let o=await Te(a),s=vf(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Xs(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function yf(e){let t=await Te(e.file);if(t){if(t.owner.id!==e.owner.id||!Ys(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Xs(t,K.dirname(e.file))}}async function NN(e,t){let r=Date.now()+hN;for(;;){let i=await wN(e,t);if(!await yN(i))return i;if(await yf(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 bN(e){let t=Qn.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return Qn.set(e,n),await t,()=>{r(),Qn.get(e)===n&&Qn.delete(e)}}async function Nf(e,t,r){let i=K.resolve(e.locksDir),n=df.getStore();if(n?.has(i))return r();let a=await bN(i);try{let o=await NN(e,t),s=new Map(n??[]);return s.set(i,o),await df.run(s,async()=>{try{return await r()}finally{await yf(o)}})}finally{a()}}async function ea(e,t,r){return Nf(e,`acquire ${t}`,async()=>{let i=await T(e.runtimeDir,e.locksDir);await ue.mkdir(i,{recursive:!0});let n=await T(e.runtimeDir,K.join(i,pN(t))),a=gf(r),o=await wf(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function ta(e){await Te(e.file)&&await Nf({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${K.basename(e.file)}`,async()=>{let t=await Te(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ys(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=K.join(e.locksDir,pf);await Xs(t,r)})}function kN(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function bf(e){return vf(await Te(e))}var uf,pf,hN,df,Qn,ni=y(()=>{"use strict";ti();$();Re();uf=16*1024,pf=".coordinator",hN=5e3,df=new fN,Qn=new Map});import{createHash as SN}from"crypto";function Ee(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function EN(e,t){t.has(e)&&Ee("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)||Ee("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&Ee("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Ee("symbol properties are not supported"),`[${e.map(i=>Qs(i,t)).join(",")}]`}finally{t.delete(e)}}function xN(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&Ee("only plain objects are supported"),t.has(e)&&Ee("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Ee("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))&&Ee("accessor properties are not supported"),`${JSON.stringify(o)}:${Qs(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function Qs(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)||Ee("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?EN(e,t):xN(e,t);case"bigint":case"function":case"symbol":case"undefined":return Ee(`${typeof e} values are not supported`)}return Ee("unsupported value type")}function Zs(e){return Qs(e,new Set)}function D(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 SN("sha256").update(`${e}
|
|
147
147
|
${Zs(t)}`).digest("hex")}var te=y(()=>{"use strict"});function Ef(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 kf(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 Sf(e){return e.includes("-->")||e.includes("--!>")}function*ra(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 l=a.indexOf(`
|
|
149
149
|
`,o),c=l===-1?a.slice(o):a.slice(o,l);if(yield{line:c,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=kf(c,t);else if(r)Sf(c)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(c)&&(i=null);else{let d=kf(c,null);if(d!==null)t=d;else{let u=c.trimStart();if(u.startsWith("<!--")&&!Sf(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(l===-1)break;o=l+1}}function ai(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function xf(e,t,r,i=[],n="content-hash"){let a=ai(r),o=t.replaceAll("\\","/").trim(),s=i.map(ai);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-${D(CN,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Cf(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 PN(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of ra(e)){n=s+1;let l=o?Ef(a):null;l?.level===1&&(js(l.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 ec(e,t="brief.md",r=ia.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=PN(e);if(n===null)return[];let a=null;for(let{line:c,body:f,index:d}of ra(e)){if(d<n.start||d>=n.end)continue;let u=f?/^( {0,3})[-*+][ \t]+/u.exec(c):null;if(u===null)continue;let p=u[1].length;a=a===null?p:Math.min(a,p)}let o=[],s=null,l=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:c,body:f,index:d}of ra(e)){if(d<n.start||d>=n.end)continue;let u=f?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(c):null;u&&u[1].length===a?(l(),s=[u[2]]):s!==null&&s.push(c)}return l(),Cf(o.map(c=>xf("brief-example",t,c.join(`
|
|
150
150
|
`),[],i)),"Brief",i)}function tc(e,t="spec.md",r=ia.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(xf("spec-scenario",t,[o.title,...o.body].join(`
|
|
151
|
-
`),o.context,i)),o=null}};for(let{line:l,body:c}of ra(e)){let f=c?Ef(l):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=ai(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(l);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f)}else o!==null&&c&&o.body.push(l)}return s(),Cf(n,"Specification",i)}var CN,aP,ia,na=y(()=>{"use strict";xt();te();CN="comet.native.acceptance.v1",aP=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),ia=Object.freeze({maxCriteria:1024})});import Pf from"node:path";function Rf(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Pf.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Pf.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function AN(e,t){return e.localeCompare(t,"en")}function aa(e){let t=Rf(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>AN(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=ec(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=Rf(a.source,`Native spec source for ${a.capability}`);i.push(...tc(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=ai(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 Af(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(!RN.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function rc(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var RN,oa=y(()=>{"use strict";na();RN=/^A[1-9]\d*$/u});import{promises as _N}from"node:fs";function Y(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function X(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 W(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 nc(e,t){return e===null?null:W(e,t)}function _f(e,t){let r=W(e,t);if(!$N.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function ir(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function j(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 HN(e,t){return e===null?null:j(e,t,Number.MIN_SAFE_INTEGER)}function L(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Te(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function ua(e,t){return Te(e,t,(r,i)=>W(r,`${t}[${i}]`))}function _t(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function nr(e,t){let r=W(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function ac(e,t,r=!1){let i=W(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 ue(e,t){let r=Y(e,t);return X(r,new Set(["text","truncated"]),t),{text:W(r.text,`${t}.text`,{empty:!0}),truncated:ir(r.truncated,`${t}.truncated`)}}function DN(e,t){let r=`Native spec_changes[${t}]`,i=Y(e,r);X(i,new Set(["capability","operation","source"]),r);let n=W(i.capability,`${r}.capability`);if(!TN.test(n))throw new Error(`${r}.capability is invalid`);let a=L(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:ac(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 LN(e){let t="Native workspace",r=Y(e,t);X(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=L(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=nc(r.change_branch,`${t}.change_branch`),a=nc(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:L(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 BN(e){let t="Native loop",r=Y(e,t);X(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=ua(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);_t(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:L(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:L(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:j(r.goal_cycle,`${t}.goal_cycle`,1),iteration:j(r.iteration,`${t}.iteration`),attempt:j(r.attempt,`${t}.attempt`),retry_epoch:j(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:j(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:j(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:j(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:nc(r.next_action,`${t}.next_action`)}}function VN(e,t){let r=`Native acceptance[${t}]`,i=Y(e,r);X(i,new Set(["id","source","text","result","reason"]),r);let n=W(i.id,`${r}.id`);if(!jN.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:ac(i.source,`${r}.source`),text:W(i.text,`${r}.text`),result:L(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:ue(i.reason,`${r}.reason`)}}function MN(e,t){let r=`Native builder_handoff.checks[${t}]`,i=Y(e,r);return X(i,new Set(["name","result","note"]),r),{name:ue(i.name,`${r}.name`),result:L(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:ue(i.note,`${r}.note`)}}function FN(e){let t="Native builder_handoff",r=Y(e,t);X(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=ua(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);_t(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:Y(r.review,`${t}.review`);return n&&X(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:W(r.candidate_id,`${t}.candidate_id`),identity_provider:W(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:W(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:j(r.iteration,`${t}.iteration`,1),summary:ue(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Te(r.checks,`${t}.checks`,MN),checks_truncated:ir(r.checks_truncated,`${t}.checks_truncated`),known_limits:Te(r.known_limits,`${t}.known_limits`,(a,o)=>ue(a,`${t}.known_limits[${o}]`)),known_limits_truncated:ir(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:L(n.status,["passed"],`${t}.review.status`),summary:ue(n.summary,`${t}.review.summary`),reviewer_execution_ref:W(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:nr(r.submitted_at,`${t}.submitted_at`)}}function qN(e,t){let r=`Native blockers[${t}]`,i=Y(e,r);X(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=ua(i.acceptance_ids,`${r}.acceptance_ids`);return _t(n,`${r}.acceptance_ids`),{owner:L(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:ue(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:L(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function WN(e,t){let r=`Native verification.checks[${t}]`,i=Y(e,r);return X(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:W(i.id,`${r}.id`),name:ue(i.name,`${r}.name`),argv_display:Te(i.argv_display,`${r}.argv_display`,(n,a)=>ue(n,`${r}.argv_display[${a}]`)),argv_truncated:ir(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:ac(i.cwd_ref,`${r}.cwd_ref`,!0),status:L(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:HN(i.exit_code,`${r}.exit_code`),duration_ms:j(i.duration_ms,`${r}.duration_ms`)}}function zN(e){let t="Native verification",r=Y(e,t);X(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Te(r.checks,`${t}.checks`,WN);_t(i.map(a=>a.id),`${t}.checks IDs`);let n=W(r.identity_provider,`${t}.identity_provider`);return{candidate_id:W(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:W(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:j(r.iteration,`${t}.iteration`,1),attempt:j(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":L(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:L(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:ue(r.summary,`${t}.summary`),risks:Te(r.risks,`${t}.risks`,(a,o)=>ue(a,`${t}.risks[${o}]`)),risks_truncated:ir(r.risks_truncated,`${t}.risks_truncated`),completed_at:nr(r.completed_at,`${t}.completed_at`)}}function If(e,t){let r=`Native history[${t}]`,i=Y(e,r);X(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=ua(i.unresolved_ids,`${r}.unresolved_ids`);return _t(n,`${r}.unresolved_ids`),{goal_cycle:j(i.goal_cycle,`${r}.goal_cycle`,1),iteration:j(i.iteration,`${r}.iteration`),attempt:j(i.attempt,`${r}.attempt`),outcome:L(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:ue(i.summary,`${r}.summary`),completed_at:nr(i.completed_at,`${r}.completed_at`)}}function JN(e){let t="Native history_overflow.outcome_counts",r=Y(e,t),i=["pass","fail","blocked","execution-error","recovery"];return X(r,new Set(i),t),{pass:j(r.pass,`${t}.pass`),fail:j(r.fail,`${t}.fail`),blocked:j(r.blocked,`${t}.blocked`),"execution-error":j(r["execution-error"],`${t}.execution-error`),recovery:j(r.recovery,`${t}.recovery`)}}function GN(e){let t="Native history_overflow",r=Y(e,t);X(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=j(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:nr(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:nr(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=JN(r.outcome_counts);if(Object.values(o).reduce((l,c)=>l+c,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 UN(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 KN(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 Ee(e){let t=Y(e,"Native portable state");if(X(t,ON,"Native portable state"),t.schema!==Ht)throw new Error(`Native portable state schema must be ${Ht}`);let r=W(t.name,"Native state name");if(!IN.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=Te(t.spec_changes,"Native spec_changes",DN);_t(i.map(s=>s.capability),"Native spec change capabilities");let n=Te(t.acceptance,"Native acceptance",VN);_t(n.map(s=>s.id),"Native acceptance IDs");let a=Te(t.history,"Native history",If);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Ht,name:r,language:L(t.language,["en","zh-CN"],"Native state language"),phase:L(t.phase,["shape","build","verify","archive"],"Native state phase"),status:L(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:j(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:_f(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:_f(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:L(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:LN(t.workspace),loop:BN(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:FN(t.builder_handoff),blockers:Te(t.blockers,"Native blockers",qN),verification:t.verification===null?null:zN(t.verification),history:a,history_overflow:GN(t.history_overflow),verification_result:L(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:L(t.verification_report,["verification.md"],"Native verification_report"),archived:ir(t.archived,"Native archived"),created_at:nr(t.created_at,"Native created_at")};return UN(o),KN(o),o}function oi(e,t){let r=Ee(e),i=If(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 Ee({...r,history:n,history_overflow:a})}function YN(e,t){let r=(0,la.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 ze(e){let t=await _N.readFile(e,"utf8");return Ee(YN(t,"Native portable state"))}async function da(e,t,r={}){let i=Ee(t);await oe(e,(0,la.stringify)(i),r)}async function XN(e,t){let r=sa.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);sa.set(e,a),await r;try{return await t()}finally{i(),sa.get(e)===a&&sa.delete(e)}}async function Tf(e){return XN(e.file,async()=>{let t=j(e.expectedStateVersion,"Native expected state version",1),r=Ee(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await ze(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new ca(t,i.state_version);return await da(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await ze(e.file);if(n.state_version!==t)throw new ca(t,n.state_version)}}),r})}var la,IN,TN,jN,$N,ON,ca,sa,ar=y(()=>{"use strict";la=vr(Kt(),1);O();wr();IN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,TN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jN=/^A[1-9][0-9]*$/u,$N=/^[a-f0-9]{64}$/u,ON=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"]),ca=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"};sa=new Map});function QN(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function It(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(QN(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 fa=y(()=>{"use strict"});var Je,je,$e,ha=y(()=>{"use strict";Je="comet.native.v3",je="comet.native.v2",$e="comet.native.v1"});import ZN from"node:path";function ab(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ob(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 sb(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 cb(e){return e.schema===$e?si(e):e.schema===je?ci(e):li(e)}function lb(e){return ZN.posix.normalize(e.replaceAll("\\","/"))}function ub(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:lb(t.source)})}function db(e){return e==="shape"?"shape":"build"}function fb(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function hb(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 jf(e){let t=cb(e.state);Af(e.acceptance);let r=db(t.phase),i=r==="shape"?0:1,n=ob(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 Ee({schema:Ht,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:ub(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:fb(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:It(hb(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:Ja(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function oc(e){let t=ab(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!eb.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==pa)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!rb.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!tb.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!nb.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!ib.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:pa,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:sb(t.createdAt,"Native portable migration transaction createdAt")}}function $f(e){switch(oc(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 pa,eb,tb,rb,ib,nb,sc=y(()=>{"use strict";G();oa();ar();fa();wr();ha();pa="comet.native.portable-migration.v1",eb=new Set(["schema","id","change","fromSchema","status","createdAt"]),tb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,rb=/^[a-z0-9][a-z0-9-]{7,127}$/u,ib=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),nb=new Set([$e,je,Je])});import cc from"node:path";function Lf(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Bf(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 bb(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Lf(e,r);if(Bf(i,Nb,r),typeof i.capability!="string"||!Df.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 kb(e){let t=Lf(e,"Native portable Archive transaction");if(Bf(t,yb,"Native portable Archive transaction"),t.schema!==Of)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!vb.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Df.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"||!gb.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"||!wb.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(bb);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:Of,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 ma(e){let t=pb.exec(e);if(t)return{kind:"archive",change:t[1]};let r=mb.exec(e);return r?{kind:"migration",change:r[1]}:null}function va(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=ma(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return cc.join(e.transactionsDir,r)}async function lc(e,t){let r=ma(t);if(!r)return null;let i=await M({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=cc.join(e.transactionsDir,t);if(r.kind==="archive"){let s=kb(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=oc(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 uc(e,t){let r=va(e,t);try{return await lc(e,cc.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function Vf(e){return e.kind==="archive"||e.journal.status!=="committed"}var Of,Hf,pb,mb,vb,gb,wb,yb,Nb,Df,ga=y(()=>{"use strict";ge();sc();Of="comet.native.archive-transaction.v4",Hf="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",pb=new RegExp(`^portable-archive-(${Hf})\\.json$`,"u"),mb=new RegExp(`^portable-migration-(${Hf})\\.json$`,"u"),vb=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,gb=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,wb=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),yb=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),Nb=new Set(["capability","operation","source","content"]),Df=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as Sb}from"node:crypto";import{constants as wa,promises as xe}from"node:fs";import Ce from"node:path";function Na(e,t){let r=Ce.relative(e,t);return r===""||!Ce.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ce.sep}`)}function Eb(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function xb(e,t){return _({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Cb(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ya(e,t){return _({...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 dc(e,t){let r=await xe.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await xe.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Pb(e,t,r){let i=Ce.resolve(e),n=Ce.resolve(t);if(!Na(i,n))throw new Error(`${r} is outside its managed root`);let a=[await dc(i,r)],o=i;for(let s of Ce.relative(i,n).split(Ce.sep).filter(Boolean)){await Tt(a,r),o=Ce.join(o,s);let l=await dc(o,r);if(!Na(a[0].realPath,l.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(l)}return await Tt(a,r),a}async function Tt(e,t){for(let r of e){let i=await xe.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!xb(r,i)||await xe.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function Rb(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 or(e){let t=Eb(e.maxBytes),r=Ce.resolve(e.file),i=await Pb(e.root,Ce.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(f=>dc(Ce.resolve(f),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Tt(i,e.label);let a=await xe.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=Cb(a),s=await xe.realpath(r);if(!Na(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(f=>Na(f.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let l=process.platform==="win32"?wa.O_RDONLY:wa.O_RDONLY|wa.O_NOFOLLOW|wa.O_NONBLOCK,c=await xe.open(r,l);try{let f=await c.stat();await e.hooks?.afterOpen?.();let[d,u]=await Promise.all([xe.lstat(r),xe.realpath(r)]);if(await Tt(i,e.label),await Tt(n,e.label),!f.isFile()||!d.isFile()||d.isSymbolicLink()||u!==s||!ya(o,f)||!ya(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await Rb(c,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([c.stat(),xe.lstat(r),xe.realpath(r)]);if(await Tt(i,e.label),await Tt(n,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!ya(o,m)||!ya(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:Sb("sha256").update(p).digest("hex"),size:p.length}}finally{await c.close()}}var Oe=y(()=>{"use strict";O();Pe()});import Ge from"path";import{TextDecoder as _b}from"util";function ka(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Sa(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 Wf(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function fc(e,t){if(typeof e!="string"||e.length===0||Ge.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function ba(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Mf(e,t){if(fc(e,t),e.includes("\\")||e!==Ge.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 Db(e,t){let r=ka(e,`transaction operations[${t}]`);if(Sa(r,Tb,`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`);fc(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&fc(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 zf(e){let t=ka(e,"Native Archive transaction journal");if(Sa(t,jb,"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"||!qf.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(!Wf(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(ba(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,l)=>{let c=ka(s,`Archive transaction operations[${l}]`);if(Sa(c,$b,`Archive transaction operations[${l}]`),typeof c.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(c.id))throw new Error(`Archive transaction operations[${l}].id is invalid`);if(c.type!=="write"&&c.type!=="remove"&&c.type!=="move")throw new Error(`Archive transaction operation ${c.id} has an invalid type`);Mf(c.target,`Archive transaction operation ${c.id} target`);for(let f of["source","staged","backup"])c[f]!==void 0&&Mf(c[f],`Archive transaction operation ${c.id} ${f}`);if(c.expectedTargetHash!==null&&ba(c.expectedTargetHash,`Archive transaction operation ${c.id} expectedTargetHash`),c.type==="write"){if(c.staged===void 0||c.source!==void 0||c.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${c.id} requires staged and forbids source`);if(ba(c.stagedHash,`Archive write operation ${c.id} stagedHash`),c.expectedTargetHash===null!=(c.backup===void 0))throw new Error(`Archive write operation ${c.id} backup must match target existence`)}else if(c.type==="remove"){if(c.source!==void 0||c.staged!==void 0||c.stagedHash!==void 0||c.expectedSourceHash!==void 0||c.backup===void 0||c.expectedTargetHash===null)throw new Error(`Archive remove operation ${c.id} requires a bound target and backup`)}else{if(c.source===void 0||c.staged!==void 0||c.stagedHash!==void 0||c.backup!==void 0||c.expectedTargetHash!==null)throw new Error(`Archive move operation ${c.id} requires source and an absent target`);ba(c.expectedSourceHash,`Archive move operation ${c.id} expectedSourceHash`)}return c}),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 Lb(e){let t=ka(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return zf(t);if(Sa(t,Ib,"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"||!qf.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Ge.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Ge.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(!Wf(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(Db),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 Bb(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Ge.join(e.transactionsDir,t)}function Jf(e,t){let r=Bb(e,t);return{directory:r,journal:Ge.join(r,"transaction.json"),events:Ge.join(r,"events.jsonl"),staged:Ge.join(r,"staged"),backups:Ge.join(r,"backups")}}async function pc(e,t){let r=Jf(e,t);return await Promise.all(Object.values(r).map(i=>T(e.runtimeDir,i))),r}async function mc(e,t,r={}){let i=await pc(e,t),n=await or({root:e.runtimeDir,file:i.journal,maxBytes:Ob,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(Hb.decode(n.bytes)),o=Lb(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var Ib,Tb,jb,$b,qf,Ob,FP,qP,WP,Hb,Ea=y(()=>{"use strict";O();$();Oe();Ib=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Tb=new Set(["id","type","source","target","staged","backup"]),jb=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),$b=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),qf=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),Ob=256*1024,FP=1024*1024,qP=16*1024,WP=64*1024*1024,Hb=new _b("utf-8",{fatal:!0})});import{promises as Vb}from"fs";import Mb from"path";async function Fb(e,t,r){let i;try{i=await Vb.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 mc(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(ma(n.name))try{let a=await lc(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Vf(a))return!0}catch{return!0}return!1}async function qb(e,t){let r=Date.now()+5e3,i=Mb.join(e.locksDir,"root-move.lock");for(;;)try{return await ea(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await bf(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 qb(e,t);try{if(await Xn(e.projectRoot),await Fb(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await ta(n)}}var de=y(()=>{"use strict";ke();ni();ga();Ea()});var Gf=y(()=>{"use strict"});import{createHash as Wb}from"crypto";function fe(e){return Wb("sha256").update(e).digest("hex")}var He=y(()=>{"use strict"});var dR,fR,hR,pR,mR,vR,gR,ui=y(()=>{"use strict";O();ke();He();Pe();$();Oe();br();dR={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},fR=8*1024*1024,hR=64*1024,pR=64*1024,mR={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},vR={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024},gR=(1n<<256n)-1n});var di=y(()=>{"use strict"});var xa=y(()=>{"use strict"});var Uf=y(()=>{"use strict"});var vc=y(()=>{"use strict";xa()});var Kf=y(()=>{"use strict";xa();vc()});var Xb,Yf=y(()=>{"use strict";Xb=vr(Kt(),1);Zt();ut();Rt()});var jR,Xf=y(()=>{"use strict";Zt();Rt();jR=4*1024*1024});function Zb(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Qf(e,t){return(...r)=>{let i=Qb;if(i===null)return t(...r);let n=Zb(`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 Qb,Zf=y(()=>{"use strict";Qb=null});var LR,eh=y(()=>{"use strict";Zf();Qt();LR=Qf("hookWritePolicy",async e=>(await Ms(e))?.hook??{allow_paths:[]})});var th=y(()=>{"use strict";xa();Zt();Uf();Kf();ut();Yf();Rt();Qt();zs();Xf();eh();Fs();vc()});var rh=y(()=>{"use strict";th();yr()});var OA,ih=y(()=>{"use strict";rh();OA=256*1024});var nh=y(()=>{"use strict";ih();di()});var UA,fi=y(()=>{"use strict";di();nh();O();Pe();UA={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 gc=y(()=>{"use strict";di();de();$();fi()});import sr from"node:path";function rk(e,t){let r=sr.relative(e,t);return sr.isAbsolute(r)||r===".."||r.startsWith(`..${sr.sep}`)?null:r.replaceAll("\\","/")||"."}function lh(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function uh(e,t){if(e.length===0||lh(e)||e.includes("\\")||sr.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=sr.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function ik(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 wc(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||lh(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function nk(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(wc(e.changeBranch,"Native workspace change branch"),wc(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 ak(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"||!oh.test(t.baseCommit)||typeof t.targetCommit!="string"||!oh.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");wc(t.targetBranch,"Native workspace Git target branch")}function ok(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"||!hi.test(String(t.projectRootId))||!hi.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");ik(t.capturedAt),uh(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&&!hi.test(String(t.projectRootPathId))||a&&!hi.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!hi.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&ak(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(nk(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 sk(e,t){return sr.join(be(e,t),"workspace.json")}function ck(e,t){let r=sk(e,t),i=ae(e,r),n=rk(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:uh(n,"Native workspace file ref")}}async function lk(e,t){try{let r=ck(e,t),i=await M({root:r.root,ref:r.ref,maxBytes:tk});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function pi(e,t){let r=await lk(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(ok(r),r)}var hi,oh,tk,l_,mi=y(()=>{"use strict";Me();O();ge();de();$();hi=/^[a-f0-9]{64}$/u,oh=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,tk=16*1024,l_=process.platform});import cr from"path";function wi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function mh(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Ec(e){if(!ph.test(e))throw new Error(`Invalid Native change name: ${e}`)}function wk(e){if(!ph.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function vh(e,t){if(e.length===0||cr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function yk(e,t){let r=wi(e,`spec_changes[${t}]`);if(mh(r,hk,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(wk(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"&&vh(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"||!Nc.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"||!Nc.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 Nk(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 xc(e,t){if(mh(e,t,jt),typeof e.name!="string")throw new Error("Native change name is required");if(Ec(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"||!pk.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&&!mk.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(yk),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"||!vk.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"&&vh(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!Nk(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 si(e){let t=wi(e,jt);if(t.schema!==$e)throw new Error(`Expected ${$e}`);return{schema:$e,...xc(t,dk)}}function gi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function yc(e,t,r){if(e===null)return null;let i=typeof e=="string"?gk.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 bk(e){if(e==null)return null;if(typeof e!="string"||!Nc.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function kk(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 ci(e){let t=wi(e,jt);if(t.schema!==je)throw new Error(`Expected ${je}`);if(gi(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${je} minimum_runtime_version must be 2`);return{schema:je,minimum_runtime_version:2,revision:gi(t.revision,"Native v2 revision"),...xc(t,hh)}}function li(e){let t=wi(e,jt);if(t.schema!==Je){if(t.schema===$e||t.schema===je){let o=t.schema===$e?si(t):ci(t);throw new bc(o.name,o.schema)}throw new mt(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=gi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new mt(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=gi(t.revision,"Native revision"),n=xc(t,fk),a=bk(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Je,minimum_runtime_version:3,revision:i,verification_protocol:kk(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:yc(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:yc(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:yc(t.partial_allowance,"Native partial_allowance","allowances")}}function Sk(e){let t=wi(e,jt);if(t.schema===$e){let n=si(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Je}`}}if(t.schema===je){let n=ci(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Je}`}}if(t.schema!==Je){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 mt(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=gi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new mt(t.schema,r).message};let i=li(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function De(e,t){Ec(t);let r=cr.join(e.changesDir,t);if(!J(e.changesDir,r))throw new Error("Native change path escaped");return r}async function Ek(e,t=cr.dirname(e)){let r=cr.relative(t,e).split(cr.sep).join("/"),i=await M({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Sc.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 gh(e,t){let r=cr.join(De(e,t),jt);await T(e.nativeRoot,r);let i=Sk(await Ek(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}var Sc,fh,dk,hh,fk,hk,pk,mk,vk,jt,Nc,ph,gk,bc,mt,Ca,vi,Pa,O_,G=y(()=>{"use strict";Sc=vr(Kt(),1);Me();ge();O();xt();ke();de();$();Oe();Gf();ui();gc();mi();ha();fh=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],dk=new Set(fh),hh=new Set([...fh,"minimum_runtime_version","revision"]),fk=new Set([...hh,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),hk=new Set(["capability","operation","source","base_hash"]),pk=new Set(["shape","build","verify","archive"]),mk=new Set(["implicit","confirmed"]),vk=new Set(["pending","pass","fail"]),jt="comet-state.yaml",Nc=/^[a-f0-9]{64}$/u,ph=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,gk=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,bc=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"},mt=class extends Error{constructor(r,i){super(r!==Je||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"},Ca=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"},vi=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"},Pa=class extends Error{constructor(r,i,n,a,o,s=null,l=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=l;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},O_=Dn("en")});var z_,yi=y(()=>{"use strict";z_=8*1024*1024});var Pc=y(()=>{"use strict";yi();O()});var X_,Ra=y(()=>{"use strict";X_=["$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 Rc=y(()=>{"use strict"});var $t=y(()=>{"use strict"});var Ac=y(()=>{"use strict";Ra();Rc();$t()});var bi=y(()=>{"use strict"});var Aa=y(()=>{"use strict";bi()});var yh=y(()=>{"use strict"});var fI,Nh=y(()=>{"use strict";Ra();fI=8*1024*1024});var bh=y(()=>{"use strict";Nh()});var _a,_c=y(()=>{"use strict";yi();Me();ke();Pc();ni();$();_a=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation}});var Ic=y(()=>{"use strict";Pc();O();te();Ac();Aa();de();$();ke();Me();yh();yi();bh();_c()});import{promises as Ok}from"node:fs";import Hk from"node:path";function Ta(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Ia(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 Eh(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 Fk(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 xh(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(l=>!i.has(l));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 qk(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===Ah&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(c=>!(c in e.acceptance_index)),i.extra=o.filter(c=>!a.includes(c));let s=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of o){let f=s.get(c),d=e.acceptance_index[c];f&&d&&(d.source!==f.source||d.text!==f.text)&&i.mismatched.push(c)}let l=new Set(o);for(let c of e.children)i.unknownCovers.push(...c.covers.filter(f=>!l.has(f)));return i.uncovered=o.filter(c=>!Ch(e.children,c)),Ph(i)?i:null}if(e.schema===ki&&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=>!Ch(e.children,a)),Ph(i)?i:null}return null}function Ch(e,t){return e.some(r=>r.covers.includes(t))}function Ph(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function _h(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 Wk(e){let t=Ta(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=Ta(n,`Native children acceptance_index.${i}`);if(Ia(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 zk(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(c=>!(c in e)),s=a.filter(c=>!n.includes(c));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 l=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of a){let f=l.get(c);if(!f)continue;let d=e[c];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.${c} does not match the acceptance catalog: copy ${u.join(", ")} exactly from the current acceptance catalog`)}}}function Jk(e,t,r={}){let i=(0,Rh.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Ta(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==ki&&a!==Si)throw Ia(n,Sh,"Native children contract"),new Error(`Native children schema must be ${ki} or ${Si}`);let o=a===ki?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Ia(n,o==="indexed-v2"?Lk:Sh,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let l=n.children.map((u,p)=>{let m=Ta(u,`Native child ${p}`);if(Ia(m,o==="indexed-v2"?Mk:o==="summary-v2"?Vk:Bk,`Native ${s} child fields (child ${p})`),typeof m.name!="string"||!Dk.test(m.name))throw new Error(`Native child ${p} name is invalid`);let h=o==="summary-v2";if(h){if(typeof m.summary!="string"||m.summary.trim().length===0)throw new Error(`Native child ${m.name} summary must be a non-empty string`);if(m.summary.length>2e3)throw new Error(`Native child ${m.name} summary exceeds 2000 characters`)}return{name:m.name,summary:h?m.summary:null,depends_on:Eh(m.depends_on,`Native child ${m.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Eh(m.covers,`Native child ${m.name} covers`):[]}}),c=l.map(({name:u})=>u);if(new Set(c).size!==c.length)throw new Error("Native child names must be unique");let f=new Set(c);for(let u of l){let p=u.depends_on.filter(m=>!f.has(m));if(p.length>0)throw new Error(`Native child ${u.name} depends on unknown child: ${p.join(", ")}`)}Fk(l);let d=r.policy==="advisory";if(a===Ah){if(o==="indexed-v2"){let u=Wk(n.acceptance_index);d||zk(u,t,r);let p=Object.keys(u);return d||xh(l,p,p),{schema:Si,acceptance_index:u,children:l}}return{schema:Si,children:l}}return t&&!d&&xh(l,t),{schema:ki,children:l}}async function Ih(e){let t=Hk.join(e.changeDir,kh);try{await Ok.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await M({root:e.changeDir,ref:kh}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=Jk(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?qk(a,e.acceptanceIds,e.validation??{}):null}}function Th(e){return D("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}var Rh,kh,ki,Si,Ah,Dk,Sh,Lk,Bk,Vk,Mk,jh=y(()=>{"use strict";Rh=vr(Kt(),1);Me();yi();ge();te();ke();$();ar();Ic();kh="children.yaml",ki="comet.native.children.v1",Si="comet.native.children.v2",Ah=Si,Dk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Sh=new Set(["schema","children"]),Lk=new Set(["schema","acceptance_index","children"]),Bk=new Set(["name","depends_on","covers"]),Vk=new Set(["name","summary","depends_on"]),Mk=new Set(["name","depends_on","covers"])});var Dh,dr=y(()=>{"use strict";te();ui();Dh=1024*1024});var Da=y(()=>{"use strict";te();$t();br();dr()});var Bh,iS,nS,aS,$T,oS,OT,$c=y(()=>{"use strict";te();Bh="scoped-text-safety",iS=1,nS=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),aS="comet.native.checker-policy.v1",$T=D(aS,{policy:Bh,version:iS,limits:nS,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),oS=["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"],OT=new Set(oS)});var La=y(()=>{"use strict";te();$c();$t()});import{createHash as Fh}from"node:crypto";import{promises as ie}from"node:fs";import Be from"node:path";function Oc(e,t){let r=Be.relative(e,t);return r===""||!Be.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Be.sep}`)}function cS(e,t){return _({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function xi(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return pe(r,i)?_(r,i):_(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Vh(e){let t=await ie.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await ie.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function lS(e,t){let r=Be.resolve(e),i=Be.resolve(t);if(!Oc(r,i))throw new Error("Native evidence path is outside its change");let n=[await Vh(r)],a=r;for(let o of Be.relative(r,i).split(Be.sep).filter(Boolean)){a=Be.join(a,o);let s=await Vh(a);if(!Oc(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function Mh(e){for(let t of e){let r=await ie.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!cS(t,r)||await ie.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function uS(e,t,r={}){let i=await lS(t,Be.dirname(e));await r.afterParentChainCaptured?.();let n=await ie.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await ie.realpath(e);if(!Oc(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await ie.open(e,"r");try{let[s,l,c]=await Promise.all([o.stat(),ie.lstat(e),ie.realpath(e)]);if(await Mh(i),!s.isFile()||!l.isFile()||l.isSymbolicLink()||c!==a||!xi(s,n)||!xi(s,l))throw new Error("Native evidence document changed while opening");if(s.size>Ue)throw new Error(`Native evidence document exceeds ${Ue} bytes`);await r.afterOpen?.();let f=[],d=0,u=Buffer.allocUnsafe(64*1024);for(;;){let v=Ue+1-d,g=await o.read(u,0,Math.min(u.length,v),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>Ue)throw new Error(`Native evidence document exceeds ${Ue} bytes`);f.push(Buffer.from(u.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),ie.lstat(e),ie.realpath(e)]);if(await Mh(i),!m.isFile()||m.isSymbolicLink()||h!==a||!xi(s,p)||!xi(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(f,d).toString("utf8"))}finally{await o.close()}}function Ba(e,t){if(!qh.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function Dc(e){let t=Buffer.from(e.text,"utf8");if(t.byteLength>Ue||Fh("sha256").update(t).digest("hex")!==e.hash)throw new Error("Native verification report snapshot hash or size is invalid");return fS({paths:e.paths,name:e.name,kind:"reports",hash:e.hash,onCreated:e.onCreated,value:{schema:"comet.native.verification-report.v1",reportHash:e.hash,content:e.text}})}async function Wh(e){let t=Lc(e.paths,e.name,"reports",e.hash),r=ae(e.paths,t);await T(r,t);let i=await ie.lstat(t);if(await dS(e.paths,e.name,e.hash),await T(r,t),!xi(i,await ie.lstat(t)))throw new Error("Native report evidence changed before rollback");await ie.unlink(t)}async function dS(e,t,r,i,n){if(!qh.test(r))throw new Error("Native report evidence hash is invalid");let a=await Hc({paths:e,name:t,kind:"reports",hash:r,hooks:i,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==r||typeof o.content!="string"||Fh("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==r)throw new Error("Native report evidence does not match its hash");return o.content}function Lc(e,t,r,i,n){let a=Ba(r,i);return n?Be.join(n,...a.split("/")):Ks(be(e,t),a)}async function Hc(e){let t=Lc(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??ae(e.paths,t);return await T(r,t),uS(t,r,e.hooks)}async function fS(e){hS(e.value);let t=Lc(e.paths,e.name,e.kind,e.hash),r=ae(e.paths,t);await T(r,t);try{let n=await Hc(e);if(JSON.stringify(n)!==JSON.stringify(e.value))throw new Error(`Native evidence hash collision for ${e.hash}`);return Ba(e.kind,e.hash)}catch(n){if(n.code!=="ENOENT")throw n}await U(t,e.value,{containedRoot:r}),e.onCreated?.();let i=await Hc(e);if(JSON.stringify(i)!==JSON.stringify(e.value))throw new Error(`Native evidence changed during commit for ${e.hash}`);return Ba(e.kind,e.hash)}function hS(e){if(pS(e)>Ue)throw new Error(`Native evidence document exceeds ${Ue} bytes`)}function pS(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
152
|
-
`,"utf8")}var qh,Ue,tj,fr=y(()=>{"use strict";O();$();Pe();dr();Da();La();qh=/^[a-f0-9]{64}$/u,Ue=Dh,tj=3*Ue});wr();function Ve(e,t,r){return e.language==="zh-CN"?r:t}function Tp(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:Ve(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:Ve(e,"Reply A or B","回复 A 或 B"),agentInstruction:Ve(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(Ve(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(Ve(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(Ve(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 jp(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 $p(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:Ve(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Ve(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function tl(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function wt(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function Op(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function el(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function Hp(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function Dp(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 Xe(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:tl({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[wt("summary","--summary"),Op(e.name,e.flag)]}}function Ga(e){return[Xe({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Xe({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Ua(e,t,r={}){let i=Hp(t)&&e.coordination_mode===void 0,n=Tp(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:[wt("summary","--summary")],commandAlternatives:[Xe({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:[wt("summary","--summary")],commandAlternatives:[Xe({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Ga({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:[wt("summary","--summary")],commandAlternatives:[Xe({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Xe({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:[wt("summary","--summary")],commandAlternatives:[Xe({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Ga({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:[wt("summary","--summary")],commandAlternatives:Ga({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:l})=>l==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?tl({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:Dp({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?[el("coordination-mode","--coordination-mode",Zc)]:[]],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 l=t.children.some(({status:f})=>f==="blocked"||f==="needs-reverify"),c=t.children.some(({status:f})=>f==="ready"||f==="active");return{...a,disposition:l&&!c?"blocked":"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:l&&!c?["resolve-child-blocker"]:["ready-children"],inputOptions:[wt("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",l=!!e.children_contract_hash,c={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...a,userCommunication:!s&&l?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${Ve(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:[c]}},{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:l?[c]:[]}}],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",c=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")}:c?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[el("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...$p(e)],userCommunication:jp(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Xe({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}import{promises as Sp}from"node:fs";import vE from"node:path";Me();O();ge();G();de();sc();ga();oa();import{randomUUID as kS}from"node:crypto";import{promises as Ai}from"node:fs";import SS from"node:path";Me();O();import{createHash as mS,randomUUID as Oj}from"node:crypto";import{promises as Ci}from"node:fs";import vt from"node:path";xt();G();ge();He();$();var Ck=["outcome","scope","nonGoals","acceptanceExamples"],q_=[...Ck,"constraints","decisions","openQuestions","verificationExpectations"];function wh(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}ge();te();jh();Ic();G();Ac();ar();fa();bi();Aa();function Uk(e){return e.state_version+1}function Kk(e){return e.map(t=>({...t,result:"pending",reason:null}))}function Yk(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:It(e.summary),completed_at:e.completedAt}}function $h(e){let t=Ee(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=oi(t,Yk({state:t,outcome:"recovery",summary:e.reason,completedAt:r})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?Kk(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return Ee({...i,phase:"build",status:"active",state_version:Uk(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"}})}O();wr();import{promises as Xk}from"node:fs";import Ei from"node:path";function ja(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function $a(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 Le(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 Oh(e,t){return e===null?null:Le(e,t)}function Ha(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 Qk(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 Zk(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Oa(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Tc(e,t){if(e===null)return null;let r=Le(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function jc(e,t){let r=Le(e,t);if(!Ei.isAbsolute(r))throw new Error(`${t} must be absolute`);return Ei.resolve(r)}function eS(e,t){let r=`Native local checks[${t}]`,i=ja(e,r);if($a(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((c,f)=>Le(c,`${r}.argv[${f}]`,!0)),a=Oa(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Tc(i.startedAt,`${r}.startedAt`),s=Tc(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 l=Ha(i.timeoutMs,`${r}.timeoutMs`);if(l<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:Le(i.id,`${r}.id`),name:Le(i.name,`${r}.name`),operationId:Le(i.operationId,`${r}.operationId`),status:a,repeatable:Zk(i.repeatable,`${r}.repeatable`),timeoutMs:l,executionCount:Ha(i.executionCount,`${r}.executionCount`),argv:n,cwd:jc(i.cwd,`${r}.cwd`),exitCode:Qk(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Le(i.log,`${r}.log`)}}function Hh(e){let t="Native local execution state",r=ja(e,t);if($a(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==gr)throw new Error(`Native local execution schema must be ${gr}`);let i=ja(r.workspace,"Native local workspace");$a(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=ja(r.execution,"Native local execution");$a(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Tc(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Le(o.operationId,"Native local execution.operationId"),stage:Oa(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Oa(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Oh(o.executionId,"Native local execution.executionId"),status:Oa(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Ha(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(eS);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:gr,change:Le(r.change,"Native local change"),basedOnStateVersion:Ha(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:jc(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:jc(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Oh(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function lr(e){return Hh({schema:gr,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:Ei.resolve(e.projectRoot),worktreeRoot:Ei.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function ur(e,t,r={}){let i=Hh(t);await Xk.mkdir(Ei.dirname(e),{recursive:!0}),await U(e,i,r)}de();oa();ar();ga();fa();bi();Aa();O();xt();bi();$();xt();fr();ke();var Ma=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,vS="comet-state.yaml",gS="state.json",s$=Dn("en");function hr(e,t){if(!Ma.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=vt.join(e.changesDir,t);if(!J(e.changesDir,r))throw new Error("Native change path escaped");return r}function gt(e,t){return vt.join(hr(e,t),vS)}function Pi(e,t){return vt.join(ht(e,t),gS)}async function Ri(e,t){try{let r=await Ci.readFile(gt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Bc(e){return he(e).currentBranch}async function Va(e,t){return ze(gt(e,t))}async function Vc(e){let t=await Tf({file:gt(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=vt.join(hr(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,r),await Ci.rm(r,{force:!0})}return t}async function wS(e){let t=hr(e.paths,e.state.name),r=vt.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await Ci.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,l)=>s.name.localeCompare(l.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!Ma.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`,l=vt.join(t,...s.split("/")),c=await Ci.lstat(l);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let f=vt.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let u=await Ci.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 zh(e){let t=hr(e.paths,e.state.name),r=await M({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(wh(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 M({root:t,ref:a.source,maxBytes:null,includeHash:!1});i.push({capability:a.capability,source:o.ref,markdown:o.text}),n.push({...a,contentHash:D("comet.native.shape-artifact-content.v1",o.text)})}return{acceptance:aa({briefMarkdown:r.text,specs:i}),formalHash:D("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:D("comet.native.shape-artifact-content.v1",r.text)},specs:n})}}function Jh(e){return D("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function yS(e){let t=await wS(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,f)=>{let d=e.state.spec_changes[f];return d!==void 0&&c.capability===d.capability&&c.source===d.source&&(c.operation===d.operation||r?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await zh({...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:c,text:f})=>({source:c,text:f}));if(!rc(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await Ih({changeDir:hr(e.paths,e.state.name),acceptanceIds:a.map(({id:c})=>c),validation:_h({...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&&Jh({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?Th({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 NS(e){let t=await yS(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await bS({paths:e.paths,state:e.state,reason:r}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function Gh(e){return re(e.paths,`sync spec references ${e.name}`,async()=>{let t=await Va(e.paths,e.name);if(t.state_version!==e.expectedStateVersion)throw new Error("Native spec sync state version is stale");if(t.archived||!["build","verify","archive"].includes(t.phase)||t.children_contract_hash)throw new Error("Native spec sync requires a confirmed ordinary active change; revise requirements in Shape otherwise");if(!Ma.test(e.capability)||!e.reason.trim()||!e.actor.trim())throw new Error("Native spec sync requires capability, actor and reason");await NS({paths:e.paths,state:t});let r=t.spec_changes.find(({capability:m,operation:h})=>m===e.capability&&h!=="remove");if(!r?.source)throw new Error("Stage this capability in the current change and confirm Shape before syncing references");let i=new Set(e.affectedAcceptanceIds);if(i.size===0||[...i].some(m=>!t.acceptance.some(h=>h.id===m))||t.acceptance.some(({source:m,id:h})=>m===r.source&&!i.has(h)))throw new Error("Native spec sync must cover the affected spec acceptance IDs");if(e.replacements.length===0||e.replacements.some(({from:m,to:h})=>!/^[A-Za-z0-9_./#%-]+$/u.test(m)||!/^[A-Za-z0-9_./#%-]+$/u.test(h)||m===h)||new Set(e.replacements.map(({from:m})=>m)).size!==e.replacements.length)throw new Error("Native spec sync only accepts unique local Markdown reference replacements");let n=hr(e.paths,t.name),a=await M({root:n,ref:r.source,maxBytes:4*1024*1024,includeHash:!1}),o=new Map(e.replacements.map(({from:m,to:h})=>[m,h])),s=new Set,l=null,c=!1,f=a.text.split(/(?<=\n)/u).map(m=>{let h=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(m.trimEnd());return h?(l?h[1][0]===l.marker&&h[1].length>=l.length&&!h[2].trim()&&(l=null):l={marker:h[1][0],length:h[1].length},m):/^(?:\s|>|[-+*]\s|\d+[.)]\s)/u.test(m)?m:(m.includes("<!--")&&(c=!0),c?(m.includes("-->")&&(c=!1),m):l||/^(?: {4}|\t)/u.test(m)||m.includes("`")?m:m.replace(/(?<!!)\[([^\]\n]+)\]\(([^()\s]+)\)/gu,(v,g,N)=>{let b=o.get(N);return b?(s.add(N),`[${g}](${b})`):v}))}).join("");if(s.size!==o.size)throw new Error("Native spec sync replacement is not an existing prose Markdown reference; use revise-requirements for semantic changes");let d=vt.join(n,r.source);await oe(d,f,{containedRoot:e.paths.nativeRoot});let u=!1,p=null;try{let m=await zh({paths:e.paths,state:t,specChanges:t.spec_changes});if(!rc(t.acceptance,m.acceptance))throw new Error("Reference change affects acceptance; revise requirements in Shape");let h=E=>mS("sha256").update(E).digest("hex"),v=JSON.stringify({schema:"comet.native.spec-sync.v1",change:t.name,actor:e.actor,reason:e.reason,source:r.source,beforeHash:h(a.text),afterHash:h(f),replacements:e.replacements,affectedAcceptanceIds:[...i],requiresConfirmation:!1,at:new Date().toISOString()}),g=h(v),N=await Dc({paths:e.paths,name:t.name,hash:g,text:v,onCreated:()=>{p=g}}),b={...t,loop:{...t.loop,previous_unresolved_ids:[...new Set([...t.loop.previous_unresolved_ids,...i])]}},S=t.phase==="build"?{...b,state_version:t.state_version+1,acceptance:t.acceptance.map(E=>i.has(E.id)?{...E,result:"pending",reason:null}:E)}:$h({state:b,reason:`Spec reference sync: ${e.reason}`});S=oi(S,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[...i],summary:It(`Spec reference sync by ${e.actor}: ${e.reason}; ${N}`),completed_at:new Date().toISOString()}),S.shape_confirmation_hash=Jh({formalHash:m.formalHash,childrenHash:null,coordinationMode:t.coordination_mode});let x=await Vc({paths:e.paths,previous:t,next:S});return u=!0,await ur(Pi(e.paths,t.name),lr({portableState:x,projectRoot:e.paths.projectRoot,branch:Bc(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),x}catch(m){if(!u)try{(await Va(e.paths,t.name)).state_version===t.state_version&&(await oe(d,a.text,{containedRoot:e.paths.nativeRoot}),p&&await Wh({paths:e.paths,name:t.name,hash:p}))}catch{}throw m}})}async function Uh(e){if(!Ma.test(e.capability))throw new Error(`Invalid Native capability: ${e.capability}`);return re(e.paths,`remove portable spec ${e.capability}`,async()=>{let t=await Va(e.paths,e.name);if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r=t.spec_changes.filter(({capability:a})=>a!==e.capability),i={...t,phase:"shape",status:"active",state_version:t.state_version+1,spec_changes:[...r,{capability:e.capability,operation:"remove",source:null}].sort((a,o)=>a.capability.localeCompare(o.capability,"en")),acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,history:[],history_overflow:{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}},loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+(t.phase==="shape"?0:1),iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await Vc({paths:e.paths,previous:t,next:i});return await ur(Pi(e.paths,t.name),lr({portableState:n,projectRoot:e.paths.projectRoot,branch:Bc(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function bS(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...oi(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:It(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 Vc({paths:e.paths,previous:t,next:i});return await ur(Pi(e.paths,t.name),lr({portableState:n,projectRoot:e.paths.projectRoot,branch:Bc(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}ar();$();mi();var Kh=["evidence.md","repair.md","archive.md","checkpoint.md"],ES="verification.md";async function xS(e,t){let r=await uc(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function Yh(e,t){await Ai.mkdir(e.transactionsDir,{recursive:!0}),await U(va(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Xh(e,t,r={}){let i=r.removeVerificationReport===!1?Kh:[...Kh,ES];await Promise.all([Ai.rm(ht(e,t),{recursive:!0,force:!0}),Ai.rm(Us(e,t),{recursive:!0,force:!0}),...i.map(n=>Ai.rm(SS.join(De(e,t),n),{force:!0}))])}async function Qh(e,t){await ur(Pi(e,t.name),lr({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function Zh(e,t){try{let r=await pi(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 ep(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=he(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 CS(e){let t=De(e.paths,e.state.name),r=await M({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 M({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return aa({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function tp(e,t){let r=await gh(e,t);if(r.status==="runtime-incompatible")throw new mt(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function rp(e){return re(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await xS(e.paths,e.name),r=await Ri(e.paths,e.name)?await ze(gt(e.paths,e.name)):null;if(!t&&r)return await Xh(e.paths,e.name,{removeVerificationReport:!1}),await Qh(e.paths,r),r;let i=null,n=null;for(t||(i=await tp(e.paths,e.name),n=await Zh(e.paths,e.name),ep(e.paths,n),t={schema:pa,id:kS(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Yh(e.paths,t));;){let a=$f(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await tp(e.paths,e.name),n??=await Zh(e.paths,e.name),ep(e.paths,n),r=jf({state:i,acceptance:await CS({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await da(gt(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Xh(e.paths,e.name):a.action==="commit-transaction"&&(r??=await ze(gt(e.paths,e.name)),await Qh(e.paths,r)),t={...t,status:a.nextStatus},await Yh(e.paths,t)}return await Ai.rm(va(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??ze(gt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}ti();import Ii from"path";import{realpathSync as hE}from"fs";Me();var Ke={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function ip(e){return e?e.command?`${Ke.next} ${e.command}`:e.ask_user?`${Ke.next} ${e.ask_user}`:null:null}function np(e,t){let r=[e.summary],i=ip(e.next);return i&&r.push(i),e.user_message&&r.push("",Ke.relay,e.user_message),t!==void 0&&r.push("",Ke.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
151
|
+
`),o.context,i)),o=null}};for(let{line:l,body:c}of ra(e)){let f=c?Ef(l):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=ai(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(l);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f)}else o!==null&&c&&o.body.push(l)}return s(),Cf(n,"Specification",i)}var CN,aP,ia,na=y(()=>{"use strict";xt();te();CN="comet.native.acceptance.v1",aP=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),ia=Object.freeze({maxCriteria:1024})});import Pf from"node:path";function Rf(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Pf.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Pf.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function AN(e,t){return e.localeCompare(t,"en")}function aa(e){let t=Rf(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>AN(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=ec(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=Rf(a.source,`Native spec source for ${a.capability}`);i.push(...tc(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=ai(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 Af(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(!RN.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function rc(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var RN,oa=y(()=>{"use strict";na();RN=/^A[1-9]\d*$/u});import{promises as _N}from"node:fs";function Y(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function X(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 W(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 nc(e,t){return e===null?null:W(e,t)}function _f(e,t){let r=W(e,t);if(!$N.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function ir(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function j(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 HN(e,t){return e===null?null:j(e,t,Number.MIN_SAFE_INTEGER)}function L(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function je(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function ua(e,t){return je(e,t,(r,i)=>W(r,`${t}[${i}]`))}function _t(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function nr(e,t){let r=W(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function ac(e,t,r=!1){let i=W(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 de(e,t){let r=Y(e,t);return X(r,new Set(["text","truncated"]),t),{text:W(r.text,`${t}.text`,{empty:!0}),truncated:ir(r.truncated,`${t}.truncated`)}}function DN(e,t){let r=`Native spec_changes[${t}]`,i=Y(e,r);X(i,new Set(["capability","operation","source"]),r);let n=W(i.capability,`${r}.capability`);if(!TN.test(n))throw new Error(`${r}.capability is invalid`);let a=L(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:ac(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 LN(e){let t="Native workspace",r=Y(e,t);X(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=L(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=nc(r.change_branch,`${t}.change_branch`),a=nc(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:L(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 BN(e){let t="Native loop",r=Y(e,t);X(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=ua(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);_t(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:L(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:L(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:j(r.goal_cycle,`${t}.goal_cycle`,1),iteration:j(r.iteration,`${t}.iteration`),attempt:j(r.attempt,`${t}.attempt`),retry_epoch:j(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:j(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:j(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:j(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:nc(r.next_action,`${t}.next_action`)}}function VN(e,t){let r=`Native acceptance[${t}]`,i=Y(e,r);X(i,new Set(["id","source","text","result","reason"]),r);let n=W(i.id,`${r}.id`);if(!jN.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:ac(i.source,`${r}.source`),text:W(i.text,`${r}.text`),result:L(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:de(i.reason,`${r}.reason`)}}function MN(e,t){let r=`Native builder_handoff.checks[${t}]`,i=Y(e,r);return X(i,new Set(["name","result","note"]),r),{name:de(i.name,`${r}.name`),result:L(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:de(i.note,`${r}.note`)}}function FN(e){let t="Native builder_handoff",r=Y(e,t);X(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=ua(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);_t(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:Y(r.review,`${t}.review`);return n&&X(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:W(r.candidate_id,`${t}.candidate_id`),identity_provider:W(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:W(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:j(r.iteration,`${t}.iteration`,1),summary:de(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:je(r.checks,`${t}.checks`,MN),checks_truncated:ir(r.checks_truncated,`${t}.checks_truncated`),known_limits:je(r.known_limits,`${t}.known_limits`,(a,o)=>de(a,`${t}.known_limits[${o}]`)),known_limits_truncated:ir(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:L(n.status,["passed"],`${t}.review.status`),summary:de(n.summary,`${t}.review.summary`),reviewer_execution_ref:W(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:nr(r.submitted_at,`${t}.submitted_at`)}}function qN(e,t){let r=`Native blockers[${t}]`,i=Y(e,r);X(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=ua(i.acceptance_ids,`${r}.acceptance_ids`);return _t(n,`${r}.acceptance_ids`),{owner:L(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:de(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:L(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function WN(e,t){let r=`Native verification.checks[${t}]`,i=Y(e,r);return X(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:W(i.id,`${r}.id`),name:de(i.name,`${r}.name`),argv_display:je(i.argv_display,`${r}.argv_display`,(n,a)=>de(n,`${r}.argv_display[${a}]`)),argv_truncated:ir(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:ac(i.cwd_ref,`${r}.cwd_ref`,!0),status:L(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:HN(i.exit_code,`${r}.exit_code`),duration_ms:j(i.duration_ms,`${r}.duration_ms`)}}function zN(e){let t="Native verification",r=Y(e,t);X(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=je(r.checks,`${t}.checks`,WN);_t(i.map(a=>a.id),`${t}.checks IDs`);let n=W(r.identity_provider,`${t}.identity_provider`);return{candidate_id:W(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:W(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:j(r.iteration,`${t}.iteration`,1),attempt:j(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":L(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:L(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:de(r.summary,`${t}.summary`),risks:je(r.risks,`${t}.risks`,(a,o)=>de(a,`${t}.risks[${o}]`)),risks_truncated:ir(r.risks_truncated,`${t}.risks_truncated`),completed_at:nr(r.completed_at,`${t}.completed_at`)}}function If(e,t){let r=`Native history[${t}]`,i=Y(e,r);X(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=ua(i.unresolved_ids,`${r}.unresolved_ids`);return _t(n,`${r}.unresolved_ids`),{goal_cycle:j(i.goal_cycle,`${r}.goal_cycle`,1),iteration:j(i.iteration,`${r}.iteration`),attempt:j(i.attempt,`${r}.attempt`),outcome:L(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:de(i.summary,`${r}.summary`),completed_at:nr(i.completed_at,`${r}.completed_at`)}}function JN(e){let t="Native history_overflow.outcome_counts",r=Y(e,t),i=["pass","fail","blocked","execution-error","recovery"];return X(r,new Set(i),t),{pass:j(r.pass,`${t}.pass`),fail:j(r.fail,`${t}.fail`),blocked:j(r.blocked,`${t}.blocked`),"execution-error":j(r["execution-error"],`${t}.execution-error`),recovery:j(r.recovery,`${t}.recovery`)}}function GN(e){let t="Native history_overflow",r=Y(e,t);X(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=j(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:nr(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:nr(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=JN(r.outcome_counts);if(Object.values(o).reduce((l,c)=>l+c,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 UN(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 KN(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 xe(e){let t=Y(e,"Native portable state");if(X(t,ON,"Native portable state"),t.schema!==Ht)throw new Error(`Native portable state schema must be ${Ht}`);let r=W(t.name,"Native state name");if(!IN.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=je(t.spec_changes,"Native spec_changes",DN);_t(i.map(s=>s.capability),"Native spec change capabilities");let n=je(t.acceptance,"Native acceptance",VN);_t(n.map(s=>s.id),"Native acceptance IDs");let a=je(t.history,"Native history",If);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Ht,name:r,language:L(t.language,["en","zh-CN"],"Native state language"),phase:L(t.phase,["shape","build","verify","archive"],"Native state phase"),status:L(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:j(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:_f(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:_f(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:L(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:LN(t.workspace),loop:BN(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:FN(t.builder_handoff),blockers:je(t.blockers,"Native blockers",qN),verification:t.verification===null?null:zN(t.verification),history:a,history_overflow:GN(t.history_overflow),verification_result:L(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:L(t.verification_report,["verification.md"],"Native verification_report"),archived:ir(t.archived,"Native archived"),created_at:nr(t.created_at,"Native created_at")};return UN(o),KN(o),o}function oi(e,t){let r=xe(e),i=If(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 xe({...r,history:n,history_overflow:a})}function YN(e,t){let r=(0,la.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 ze(e){let t=await _N.readFile(e,"utf8");return xe(YN(t,"Native portable state"))}async function da(e,t,r={}){let i=xe(t);await se(e,(0,la.stringify)(i),r)}async function XN(e,t){let r=sa.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);sa.set(e,a),await r;try{return await t()}finally{i(),sa.get(e)===a&&sa.delete(e)}}async function Tf(e){return XN(e.file,async()=>{let t=j(e.expectedStateVersion,"Native expected state version",1),r=xe(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await ze(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new ca(t,i.state_version);return await da(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await ze(e.file);if(n.state_version!==t)throw new ca(t,n.state_version)}}),r})}var la,IN,TN,jN,$N,ON,ca,sa,ar=y(()=>{"use strict";la=vr(Kt(),1);O();wr();IN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,TN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,jN=/^A[1-9][0-9]*$/u,$N=/^[a-f0-9]{64}$/u,ON=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"]),ca=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"};sa=new Map});function QN(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function It(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(QN(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 fa=y(()=>{"use strict"});var Je,$e,Oe,ha=y(()=>{"use strict";Je="comet.native.v3",$e="comet.native.v2",Oe="comet.native.v1"});import ZN from"node:path";function ab(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ob(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 sb(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 cb(e){return e.schema===Oe?si(e):e.schema===$e?ci(e):li(e)}function lb(e){return ZN.posix.normalize(e.replaceAll("\\","/"))}function ub(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:lb(t.source)})}function db(e){return e==="shape"?"shape":"build"}function fb(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function hb(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 jf(e){let t=cb(e.state);Af(e.acceptance);let r=db(t.phase),i=r==="shape"?0:1,n=ob(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 xe({schema:Ht,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:ub(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:fb(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:It(hb(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:Ja(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function oc(e){let t=ab(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!eb.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==pa)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!rb.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!tb.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!nb.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!ib.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:pa,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:sb(t.createdAt,"Native portable migration transaction createdAt")}}function $f(e){switch(oc(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 pa,eb,tb,rb,ib,nb,sc=y(()=>{"use strict";G();oa();ar();fa();wr();ha();pa="comet.native.portable-migration.v1",eb=new Set(["schema","id","change","fromSchema","status","createdAt"]),tb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,rb=/^[a-z0-9][a-z0-9-]{7,127}$/u,ib=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),nb=new Set([Oe,$e,Je])});import cc from"node:path";function Lf(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Bf(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 bb(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Lf(e,r);if(Bf(i,Nb,r),typeof i.capability!="string"||!Df.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 kb(e){let t=Lf(e,"Native portable Archive transaction");if(Bf(t,yb,"Native portable Archive transaction"),t.schema!==Of)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!vb.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Df.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"||!gb.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"||!wb.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(bb);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:Of,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 ma(e){let t=pb.exec(e);if(t)return{kind:"archive",change:t[1]};let r=mb.exec(e);return r?{kind:"migration",change:r[1]}:null}function va(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=ma(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return cc.join(e.transactionsDir,r)}async function lc(e,t){let r=ma(t);if(!r)return null;let i=await M({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=cc.join(e.transactionsDir,t);if(r.kind==="archive"){let s=kb(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=oc(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 uc(e,t){let r=va(e,t);try{return await lc(e,cc.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function Vf(e){return e.kind==="archive"||e.journal.status!=="committed"}var Of,Hf,pb,mb,vb,gb,wb,yb,Nb,Df,ga=y(()=>{"use strict";we();sc();Of="comet.native.archive-transaction.v4",Hf="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",pb=new RegExp(`^portable-archive-(${Hf})\\.json$`,"u"),mb=new RegExp(`^portable-migration-(${Hf})\\.json$`,"u"),vb=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,gb=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,wb=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),yb=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),Nb=new Set(["capability","operation","source","content"]),Df=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as Sb}from"node:crypto";import{constants as wa,promises as Ce}from"node:fs";import Pe from"node:path";function Na(e,t){let r=Pe.relative(e,t);return r===""||!Pe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Pe.sep}`)}function Eb(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function xb(e,t){return _({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Cb(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ya(e,t){return _({...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 dc(e,t){let r=await Ce.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Ce.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Pb(e,t,r){let i=Pe.resolve(e),n=Pe.resolve(t);if(!Na(i,n))throw new Error(`${r} is outside its managed root`);let a=[await dc(i,r)],o=i;for(let s of Pe.relative(i,n).split(Pe.sep).filter(Boolean)){await Tt(a,r),o=Pe.join(o,s);let l=await dc(o,r);if(!Na(a[0].realPath,l.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(l)}return await Tt(a,r),a}async function Tt(e,t){for(let r of e){let i=await Ce.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!xb(r,i)||await Ce.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function Rb(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 or(e){let t=Eb(e.maxBytes),r=Pe.resolve(e.file),i=await Pb(e.root,Pe.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(f=>dc(Pe.resolve(f),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Tt(i,e.label);let a=await Ce.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=Cb(a),s=await Ce.realpath(r);if(!Na(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(f=>Na(f.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let l=process.platform==="win32"?wa.O_RDONLY:wa.O_RDONLY|wa.O_NOFOLLOW|wa.O_NONBLOCK,c=await Ce.open(r,l);try{let f=await c.stat();await e.hooks?.afterOpen?.();let[d,u]=await Promise.all([Ce.lstat(r),Ce.realpath(r)]);if(await Tt(i,e.label),await Tt(n,e.label),!f.isFile()||!d.isFile()||d.isSymbolicLink()||u!==s||!ya(o,f)||!ya(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await Rb(c,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([c.stat(),Ce.lstat(r),Ce.realpath(r)]);if(await Tt(i,e.label),await Tt(n,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!ya(o,m)||!ya(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:Sb("sha256").update(p).digest("hex"),size:p.length}}finally{await c.close()}}var He=y(()=>{"use strict";O();Re()});import Ge from"path";import{TextDecoder as _b}from"util";function ka(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Sa(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 Wf(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function fc(e,t){if(typeof e!="string"||e.length===0||Ge.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function ba(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Mf(e,t){if(fc(e,t),e.includes("\\")||e!==Ge.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 Db(e,t){let r=ka(e,`transaction operations[${t}]`);if(Sa(r,Tb,`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`);fc(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&fc(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 zf(e){let t=ka(e,"Native Archive transaction journal");if(Sa(t,jb,"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"||!qf.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(!Wf(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(ba(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,l)=>{let c=ka(s,`Archive transaction operations[${l}]`);if(Sa(c,$b,`Archive transaction operations[${l}]`),typeof c.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(c.id))throw new Error(`Archive transaction operations[${l}].id is invalid`);if(c.type!=="write"&&c.type!=="remove"&&c.type!=="move")throw new Error(`Archive transaction operation ${c.id} has an invalid type`);Mf(c.target,`Archive transaction operation ${c.id} target`);for(let f of["source","staged","backup"])c[f]!==void 0&&Mf(c[f],`Archive transaction operation ${c.id} ${f}`);if(c.expectedTargetHash!==null&&ba(c.expectedTargetHash,`Archive transaction operation ${c.id} expectedTargetHash`),c.type==="write"){if(c.staged===void 0||c.source!==void 0||c.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${c.id} requires staged and forbids source`);if(ba(c.stagedHash,`Archive write operation ${c.id} stagedHash`),c.expectedTargetHash===null!=(c.backup===void 0))throw new Error(`Archive write operation ${c.id} backup must match target existence`)}else if(c.type==="remove"){if(c.source!==void 0||c.staged!==void 0||c.stagedHash!==void 0||c.expectedSourceHash!==void 0||c.backup===void 0||c.expectedTargetHash===null)throw new Error(`Archive remove operation ${c.id} requires a bound target and backup`)}else{if(c.source===void 0||c.staged!==void 0||c.stagedHash!==void 0||c.backup!==void 0||c.expectedTargetHash!==null)throw new Error(`Archive move operation ${c.id} requires source and an absent target`);ba(c.expectedSourceHash,`Archive move operation ${c.id} expectedSourceHash`)}return c}),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 Lb(e){let t=ka(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return zf(t);if(Sa(t,Ib,"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"||!qf.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Ge.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Ge.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(!Wf(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(Db),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 Bb(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Ge.join(e.transactionsDir,t)}function Jf(e,t){let r=Bb(e,t);return{directory:r,journal:Ge.join(r,"transaction.json"),events:Ge.join(r,"events.jsonl"),staged:Ge.join(r,"staged"),backups:Ge.join(r,"backups")}}async function pc(e,t){let r=Jf(e,t);return await Promise.all(Object.values(r).map(i=>T(e.runtimeDir,i))),r}async function mc(e,t,r={}){let i=await pc(e,t),n=await or({root:e.runtimeDir,file:i.journal,maxBytes:Ob,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(Hb.decode(n.bytes)),o=Lb(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var Ib,Tb,jb,$b,qf,Ob,FP,qP,WP,Hb,Ea=y(()=>{"use strict";O();$();He();Ib=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Tb=new Set(["id","type","source","target","staged","backup"]),jb=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),$b=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),qf=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),Ob=256*1024,FP=1024*1024,qP=16*1024,WP=64*1024*1024,Hb=new _b("utf-8",{fatal:!0})});import{promises as Vb}from"fs";import Mb from"path";async function Fb(e,t,r){let i;try{i=await Vb.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 mc(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(ma(n.name))try{let a=await lc(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Vf(a))return!0}catch{return!0}return!1}async function qb(e,t){let r=Date.now()+5e3,i=Mb.join(e.locksDir,"root-move.lock");for(;;)try{return await ea(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await bf(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 qb(e,t);try{if(await Xn(e.projectRoot),await Fb(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await ta(n)}}var fe=y(()=>{"use strict";Se();ni();ga();Ea()});var Gf=y(()=>{"use strict"});import{createHash as Wb}from"crypto";function he(e){return Wb("sha256").update(e).digest("hex")}var De=y(()=>{"use strict"});var dR,fR,hR,pR,mR,vR,gR,ui=y(()=>{"use strict";O();Se();De();Re();$();He();br();dR={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},fR=8*1024*1024,hR=64*1024,pR=64*1024,mR={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},vR={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024},gR=(1n<<256n)-1n});var di=y(()=>{"use strict"});var xa=y(()=>{"use strict"});var Uf=y(()=>{"use strict"});var vc=y(()=>{"use strict";xa()});var Kf=y(()=>{"use strict";xa();vc()});var Xb,Yf=y(()=>{"use strict";Xb=vr(Kt(),1);Zt();ut();Rt()});var jR,Xf=y(()=>{"use strict";Zt();Rt();jR=4*1024*1024});function Zb(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Qf(e,t){return(...r)=>{let i=Qb;if(i===null)return t(...r);let n=Zb(`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 Qb,Zf=y(()=>{"use strict";Qb=null});var LR,eh=y(()=>{"use strict";Zf();Qt();LR=Qf("hookWritePolicy",async e=>(await Ms(e))?.hook??{allow_paths:[]})});var th=y(()=>{"use strict";xa();Zt();Uf();Kf();ut();Yf();Rt();Qt();zs();Xf();eh();Fs();vc()});var rh=y(()=>{"use strict";th();yr()});var OA,ih=y(()=>{"use strict";rh();OA=256*1024});var nh=y(()=>{"use strict";ih();di()});var UA,fi=y(()=>{"use strict";di();nh();O();Re();UA={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 gc=y(()=>{"use strict";di();fe();$();fi()});import sr from"node:path";function rk(e,t){let r=sr.relative(e,t);return sr.isAbsolute(r)||r===".."||r.startsWith(`..${sr.sep}`)?null:r.replaceAll("\\","/")||"."}function lh(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function uh(e,t){if(e.length===0||lh(e)||e.includes("\\")||sr.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=sr.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function ik(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 wc(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||lh(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function nk(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(wc(e.changeBranch,"Native workspace change branch"),wc(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 ak(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"||!oh.test(t.baseCommit)||typeof t.targetCommit!="string"||!oh.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");wc(t.targetBranch,"Native workspace Git target branch")}function ok(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"||!hi.test(String(t.projectRootId))||!hi.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");ik(t.capturedAt),uh(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&&!hi.test(String(t.projectRootPathId))||a&&!hi.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!hi.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&ak(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(nk(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 sk(e,t){return sr.join(ke(e,t),"workspace.json")}function ck(e,t){let r=sk(e,t),i=ae(e,r),n=rk(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:uh(n,"Native workspace file ref")}}async function lk(e,t){try{let r=ck(e,t),i=await M({root:r.root,ref:r.ref,maxBytes:tk});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function pi(e,t){let r=await lk(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(ok(r),r)}var hi,oh,tk,l_,mi=y(()=>{"use strict";Me();O();we();fe();$();hi=/^[a-f0-9]{64}$/u,oh=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,tk=16*1024,l_=process.platform});import cr from"path";function wi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function mh(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Ec(e){if(!ph.test(e))throw new Error(`Invalid Native change name: ${e}`)}function wk(e){if(!ph.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function vh(e,t){if(e.length===0||cr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function yk(e,t){let r=wi(e,`spec_changes[${t}]`);if(mh(r,hk,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(wk(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"&&vh(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"||!Nc.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"||!Nc.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 Nk(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 xc(e,t){if(mh(e,t,jt),typeof e.name!="string")throw new Error("Native change name is required");if(Ec(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"||!pk.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&&!mk.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(yk),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"||!vk.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"&&vh(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!Nk(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 si(e){let t=wi(e,jt);if(t.schema!==Oe)throw new Error(`Expected ${Oe}`);return{schema:Oe,...xc(t,dk)}}function gi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function yc(e,t,r){if(e===null)return null;let i=typeof e=="string"?gk.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 bk(e){if(e==null)return null;if(typeof e!="string"||!Nc.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function kk(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 ci(e){let t=wi(e,jt);if(t.schema!==$e)throw new Error(`Expected ${$e}`);if(gi(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${$e} minimum_runtime_version must be 2`);return{schema:$e,minimum_runtime_version:2,revision:gi(t.revision,"Native v2 revision"),...xc(t,hh)}}function li(e){let t=wi(e,jt);if(t.schema!==Je){if(t.schema===Oe||t.schema===$e){let o=t.schema===Oe?si(t):ci(t);throw new bc(o.name,o.schema)}throw new mt(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=gi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new mt(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=gi(t.revision,"Native revision"),n=xc(t,fk),a=bk(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Je,minimum_runtime_version:3,revision:i,verification_protocol:kk(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:yc(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:yc(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:yc(t.partial_allowance,"Native partial_allowance","allowances")}}function Sk(e){let t=wi(e,jt);if(t.schema===Oe){let n=si(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Je}`}}if(t.schema===$e){let n=ci(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Je}`}}if(t.schema!==Je){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 mt(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=gi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new mt(t.schema,r).message};let i=li(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function Le(e,t){Ec(t);let r=cr.join(e.changesDir,t);if(!J(e.changesDir,r))throw new Error("Native change path escaped");return r}async function Ek(e,t=cr.dirname(e)){let r=cr.relative(t,e).split(cr.sep).join("/"),i=await M({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Sc.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 gh(e,t){let r=cr.join(Le(e,t),jt);await T(e.nativeRoot,r);let i=Sk(await Ek(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}var Sc,fh,dk,hh,fk,hk,pk,mk,vk,jt,Nc,ph,gk,bc,mt,Ca,vi,Pa,O_,G=y(()=>{"use strict";Sc=vr(Kt(),1);Me();we();O();xt();Se();fe();$();He();Gf();ui();gc();mi();ha();fh=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],dk=new Set(fh),hh=new Set([...fh,"minimum_runtime_version","revision"]),fk=new Set([...hh,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),hk=new Set(["capability","operation","source","base_hash"]),pk=new Set(["shape","build","verify","archive"]),mk=new Set(["implicit","confirmed"]),vk=new Set(["pending","pass","fail"]),jt="comet-state.yaml",Nc=/^[a-f0-9]{64}$/u,ph=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,gk=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,bc=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"},mt=class extends Error{constructor(r,i){super(r!==Je||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"},Ca=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"},vi=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"},Pa=class extends Error{constructor(r,i,n,a,o,s=null,l=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=l;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},O_=Dn("en")});var z_,yi=y(()=>{"use strict";z_=8*1024*1024});var Pc=y(()=>{"use strict";yi();O()});var X_,Ra=y(()=>{"use strict";X_=["$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 Rc=y(()=>{"use strict"});var $t=y(()=>{"use strict"});var Ac=y(()=>{"use strict";Ra();Rc();$t()});var bi=y(()=>{"use strict"});var Aa=y(()=>{"use strict";bi()});var yh=y(()=>{"use strict"});var fI,Nh=y(()=>{"use strict";Ra();fI=8*1024*1024});var bh=y(()=>{"use strict";Nh()});var _a,_c=y(()=>{"use strict";yi();Me();Se();Pc();ni();$();_a=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation}});var Ic=y(()=>{"use strict";Pc();O();te();Ac();Aa();fe();$();Se();Me();yh();yi();bh();_c()});import{promises as Ok}from"node:fs";import Hk from"node:path";function Ta(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Ia(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 Eh(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 Fk(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 xh(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(l=>!i.has(l));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 qk(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===Ah&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(c=>!(c in e.acceptance_index)),i.extra=o.filter(c=>!a.includes(c));let s=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of o){let f=s.get(c),d=e.acceptance_index[c];f&&d&&(d.source!==f.source||d.text!==f.text)&&i.mismatched.push(c)}let l=new Set(o);for(let c of e.children)i.unknownCovers.push(...c.covers.filter(f=>!l.has(f)));return i.uncovered=o.filter(c=>!Ch(e.children,c)),Ph(i)?i:null}if(e.schema===ki&&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=>!Ch(e.children,a)),Ph(i)?i:null}return null}function Ch(e,t){return e.some(r=>r.covers.includes(t))}function Ph(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function _h(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 Wk(e){let t=Ta(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=Ta(n,`Native children acceptance_index.${i}`);if(Ia(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 zk(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(c=>!(c in e)),s=a.filter(c=>!n.includes(c));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 l=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of a){let f=l.get(c);if(!f)continue;let d=e[c];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.${c} does not match the acceptance catalog: copy ${u.join(", ")} exactly from the current acceptance catalog`)}}}function Jk(e,t,r={}){let i=(0,Rh.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Ta(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==ki&&a!==Si)throw Ia(n,Sh,"Native children contract"),new Error(`Native children schema must be ${ki} or ${Si}`);let o=a===ki?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Ia(n,o==="indexed-v2"?Lk:Sh,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let l=n.children.map((u,p)=>{let m=Ta(u,`Native child ${p}`);if(Ia(m,o==="indexed-v2"?Mk:o==="summary-v2"?Vk:Bk,`Native ${s} child fields (child ${p})`),typeof m.name!="string"||!Dk.test(m.name))throw new Error(`Native child ${p} name is invalid`);let h=o==="summary-v2";if(h){if(typeof m.summary!="string"||m.summary.trim().length===0)throw new Error(`Native child ${m.name} summary must be a non-empty string`);if(m.summary.length>2e3)throw new Error(`Native child ${m.name} summary exceeds 2000 characters`)}return{name:m.name,summary:h?m.summary:null,depends_on:Eh(m.depends_on,`Native child ${m.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Eh(m.covers,`Native child ${m.name} covers`):[]}}),c=l.map(({name:u})=>u);if(new Set(c).size!==c.length)throw new Error("Native child names must be unique");let f=new Set(c);for(let u of l){let p=u.depends_on.filter(m=>!f.has(m));if(p.length>0)throw new Error(`Native child ${u.name} depends on unknown child: ${p.join(", ")}`)}Fk(l);let d=r.policy==="advisory";if(a===Ah){if(o==="indexed-v2"){let u=Wk(n.acceptance_index);d||zk(u,t,r);let p=Object.keys(u);return d||xh(l,p,p),{schema:Si,acceptance_index:u,children:l}}return{schema:Si,children:l}}return t&&!d&&xh(l,t),{schema:ki,children:l}}async function Ih(e){let t=Hk.join(e.changeDir,kh);try{await Ok.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await M({root:e.changeDir,ref:kh}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=Jk(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?qk(a,e.acceptanceIds,e.validation??{}):null}}function Th(e){return D("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}var Rh,kh,ki,Si,Ah,Dk,Sh,Lk,Bk,Vk,Mk,jh=y(()=>{"use strict";Rh=vr(Kt(),1);Me();yi();we();te();Se();$();ar();Ic();kh="children.yaml",ki="comet.native.children.v1",Si="comet.native.children.v2",Ah=Si,Dk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Sh=new Set(["schema","children"]),Lk=new Set(["schema","acceptance_index","children"]),Bk=new Set(["name","depends_on","covers"]),Vk=new Set(["name","summary","depends_on"]),Mk=new Set(["name","depends_on","covers"])});var Dh,dr=y(()=>{"use strict";te();ui();Dh=1024*1024});var Da=y(()=>{"use strict";te();$t();br();dr()});var Bh,iS,nS,aS,$T,oS,OT,$c=y(()=>{"use strict";te();Bh="scoped-text-safety",iS=1,nS=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),aS="comet.native.checker-policy.v1",$T=D(aS,{policy:Bh,version:iS,limits:nS,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),oS=["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"],OT=new Set(oS)});var La=y(()=>{"use strict";te();$c();$t()});import{createHash as Fh}from"node:crypto";import{promises as ie}from"node:fs";import Ve from"node:path";function Oc(e,t){let r=Ve.relative(e,t);return r===""||!Ve.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ve.sep}`)}function cS(e,t){return _({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function xi(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return me(r,i)?_(r,i):_(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Vh(e){let t=await ie.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await ie.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function lS(e,t){let r=Ve.resolve(e),i=Ve.resolve(t);if(!Oc(r,i))throw new Error("Native evidence path is outside its change");let n=[await Vh(r)],a=r;for(let o of Ve.relative(r,i).split(Ve.sep).filter(Boolean)){a=Ve.join(a,o);let s=await Vh(a);if(!Oc(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function Mh(e){for(let t of e){let r=await ie.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!cS(t,r)||await ie.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function uS(e,t,r={}){let i=await lS(t,Ve.dirname(e));await r.afterParentChainCaptured?.();let n=await ie.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await ie.realpath(e);if(!Oc(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await ie.open(e,"r");try{let[s,l,c]=await Promise.all([o.stat(),ie.lstat(e),ie.realpath(e)]);if(await Mh(i),!s.isFile()||!l.isFile()||l.isSymbolicLink()||c!==a||!xi(s,n)||!xi(s,l))throw new Error("Native evidence document changed while opening");if(s.size>Ue)throw new Error(`Native evidence document exceeds ${Ue} bytes`);await r.afterOpen?.();let f=[],d=0,u=Buffer.allocUnsafe(64*1024);for(;;){let v=Ue+1-d,g=await o.read(u,0,Math.min(u.length,v),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>Ue)throw new Error(`Native evidence document exceeds ${Ue} bytes`);f.push(Buffer.from(u.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[p,m,h]=await Promise.all([o.stat(),ie.lstat(e),ie.realpath(e)]);if(await Mh(i),!m.isFile()||m.isSymbolicLink()||h!==a||!xi(s,p)||!xi(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(f,d).toString("utf8"))}finally{await o.close()}}function Ba(e,t){if(!qh.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}async function Dc(e){let t=Buffer.from(e.text,"utf8");if(t.byteLength>Ue||Fh("sha256").update(t).digest("hex")!==e.hash)throw new Error("Native verification report snapshot hash or size is invalid");return fS({paths:e.paths,name:e.name,kind:"reports",hash:e.hash,onCreated:e.onCreated,value:{schema:"comet.native.verification-report.v1",reportHash:e.hash,content:e.text}})}async function Wh(e){let t=Lc(e.paths,e.name,"reports",e.hash),r=ae(e.paths,t);await T(r,t);let i=await ie.lstat(t);if(await dS(e.paths,e.name,e.hash),await T(r,t),!xi(i,await ie.lstat(t)))throw new Error("Native report evidence changed before rollback");await ie.unlink(t)}async function dS(e,t,r,i,n){if(!qh.test(r))throw new Error("Native report evidence hash is invalid");let a=await Hc({paths:e,name:t,kind:"reports",hash:r,hooks:i,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==r||typeof o.content!="string"||Fh("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==r)throw new Error("Native report evidence does not match its hash");return o.content}function Lc(e,t,r,i,n){let a=Ba(r,i);return n?Ve.join(n,...a.split("/")):Ks(ke(e,t),a)}async function Hc(e){let t=Lc(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??ae(e.paths,t);return await T(r,t),uS(t,r,e.hooks)}async function fS(e){hS(e.value);let t=Lc(e.paths,e.name,e.kind,e.hash),r=ae(e.paths,t);await T(r,t);try{let n=await Hc(e);if(JSON.stringify(n)!==JSON.stringify(e.value))throw new Error(`Native evidence hash collision for ${e.hash}`);return Ba(e.kind,e.hash)}catch(n){if(n.code!=="ENOENT")throw n}await U(t,e.value,{containedRoot:r}),e.onCreated?.();let i=await Hc(e);if(JSON.stringify(i)!==JSON.stringify(e.value))throw new Error(`Native evidence changed during commit for ${e.hash}`);return Ba(e.kind,e.hash)}function hS(e){if(pS(e)>Ue)throw new Error(`Native evidence document exceeds ${Ue} bytes`)}function pS(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
152
|
+
`,"utf8")}var qh,Ue,tj,fr=y(()=>{"use strict";O();$();Re();dr();Da();La();qh=/^[a-f0-9]{64}$/u,Ue=Dh,tj=3*Ue});wr();function oe(e,t,r){return e.language==="zh-CN"?r:t}function Tp(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:oe(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:oe(e,"Reply A or B","回复 A 或 B"),agentInstruction:oe(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(oe(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(oe(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:oe(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:oe(e,"Accept the result","接受结果"),agentInstruction:oe(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(oe(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 jp(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 $p(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:oe(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:oe(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function tl(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function wt(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function Op(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function el(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function Hp(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function Dp(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 Xe(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:tl({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[wt("summary","--summary"),Op(e.name,e.flag)]}}function Ga(e){return[Xe({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Xe({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Ua(e,t,r={}){let i=Hp(t)&&e.coordination_mode===void 0,n=Tp(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:[wt("summary","--summary")],commandAlternatives:[Xe({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:[wt("summary","--summary")],commandAlternatives:[Xe({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Ga({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:[wt("summary","--summary")],commandAlternatives:[Xe({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Xe({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:[wt("summary","--summary")],commandAlternatives:[Xe({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Ga({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:[wt("summary","--summary")],commandAlternatives:Ga({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:l})=>l==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?tl({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:Dp({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?[el("coordination-mode","--coordination-mode",Zc)]:[]],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 l=t.children.some(({status:f})=>f==="blocked"||f==="needs-reverify"),c=t.children.some(({status:f})=>f==="ready"||f==="active");return{...a,disposition:l&&!c?"blocked":"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:l&&!c?["resolve-child-blocker"]:["ready-children"],inputOptions:[wt("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",l=!!e.children_contract_hash,c={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...a,userCommunication:!s&&l?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${oe(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:[c]}},{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:l?[c]:[]}}],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",c=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")}:c?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[el("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...$p(e)],userCommunication:jp(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Xe({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}import{promises as Sp}from"node:fs";import vE from"node:path";Me();O();we();G();fe();sc();ga();oa();import{randomUUID as kS}from"node:crypto";import{promises as Ai}from"node:fs";import SS from"node:path";Me();O();import{createHash as mS,randomUUID as Oj}from"node:crypto";import{promises as Ci}from"node:fs";import vt from"node:path";xt();G();we();De();$();var Ck=["outcome","scope","nonGoals","acceptanceExamples"],q_=[...Ck,"constraints","decisions","openQuestions","verificationExpectations"];function wh(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}we();te();jh();Ic();G();Ac();ar();fa();bi();Aa();function Uk(e){return e.state_version+1}function Kk(e){return e.map(t=>({...t,result:"pending",reason:null}))}function Yk(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:It(e.summary),completed_at:e.completedAt}}function $h(e){let t=xe(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=oi(t,Yk({state:t,outcome:"recovery",summary:e.reason,completedAt:r})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?Kk(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return xe({...i,phase:"build",status:"active",state_version:Uk(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"}})}O();wr();import{promises as Xk}from"node:fs";import Ei from"node:path";function ja(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function $a(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 Be(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 Oh(e,t){return e===null?null:Be(e,t)}function Ha(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 Qk(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 Zk(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Oa(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Tc(e,t){if(e===null)return null;let r=Be(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function jc(e,t){let r=Be(e,t);if(!Ei.isAbsolute(r))throw new Error(`${t} must be absolute`);return Ei.resolve(r)}function eS(e,t){let r=`Native local checks[${t}]`,i=ja(e,r);if($a(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((c,f)=>Be(c,`${r}.argv[${f}]`,!0)),a=Oa(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Tc(i.startedAt,`${r}.startedAt`),s=Tc(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 l=Ha(i.timeoutMs,`${r}.timeoutMs`);if(l<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:Be(i.id,`${r}.id`),name:Be(i.name,`${r}.name`),operationId:Be(i.operationId,`${r}.operationId`),status:a,repeatable:Zk(i.repeatable,`${r}.repeatable`),timeoutMs:l,executionCount:Ha(i.executionCount,`${r}.executionCount`),argv:n,cwd:jc(i.cwd,`${r}.cwd`),exitCode:Qk(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Be(i.log,`${r}.log`)}}function Hh(e){let t="Native local execution state",r=ja(e,t);if($a(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==gr)throw new Error(`Native local execution schema must be ${gr}`);let i=ja(r.workspace,"Native local workspace");$a(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=ja(r.execution,"Native local execution");$a(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Tc(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Be(o.operationId,"Native local execution.operationId"),stage:Oa(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Oa(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Oh(o.executionId,"Native local execution.executionId"),status:Oa(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Ha(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(eS);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:gr,change:Be(r.change,"Native local change"),basedOnStateVersion:Ha(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:jc(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:jc(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Oh(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function lr(e){return Hh({schema:gr,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:Ei.resolve(e.projectRoot),worktreeRoot:Ei.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function ur(e,t,r={}){let i=Hh(t);await Xk.mkdir(Ei.dirname(e),{recursive:!0}),await U(e,i,r)}fe();oa();ar();ga();fa();bi();Aa();O();xt();bi();$();xt();fr();Se();var Ma=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,vS="comet-state.yaml",gS="state.json",s$=Dn("en");function hr(e,t){if(!Ma.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=vt.join(e.changesDir,t);if(!J(e.changesDir,r))throw new Error("Native change path escaped");return r}function gt(e,t){return vt.join(hr(e,t),vS)}function Pi(e,t){return vt.join(ht(e,t),gS)}async function Ri(e,t){try{let r=await Ci.readFile(gt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Bc(e){return pe(e).currentBranch}async function Va(e,t){return ze(gt(e,t))}async function Vc(e){let t=await Tf({file:gt(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=vt.join(hr(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,r),await Ci.rm(r,{force:!0})}return t}async function wS(e){let t=hr(e.paths,e.state.name),r=vt.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await Ci.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,l)=>s.name.localeCompare(l.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!Ma.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`,l=vt.join(t,...s.split("/")),c=await Ci.lstat(l);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let f=vt.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let u=await Ci.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 zh(e){let t=hr(e.paths,e.state.name),r=await M({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(wh(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 M({root:t,ref:a.source,maxBytes:null,includeHash:!1});i.push({capability:a.capability,source:o.ref,markdown:o.text}),n.push({...a,contentHash:D("comet.native.shape-artifact-content.v1",o.text)})}return{acceptance:aa({briefMarkdown:r.text,specs:i}),formalHash:D("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:D("comet.native.shape-artifact-content.v1",r.text)},specs:n})}}function Jh(e){return D("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function yS(e){let t=await wS(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,f)=>{let d=e.state.spec_changes[f];return d!==void 0&&c.capability===d.capability&&c.source===d.source&&(c.operation===d.operation||r?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await zh({...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:c,text:f})=>({source:c,text:f}));if(!rc(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await Ih({changeDir:hr(e.paths,e.state.name),acceptanceIds:a.map(({id:c})=>c),validation:_h({...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&&Jh({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?Th({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 NS(e){let t=await yS(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await bS({paths:e.paths,state:e.state,reason:r}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function Gh(e){return re(e.paths,`sync spec references ${e.name}`,async()=>{let t=await Va(e.paths,e.name);if(t.state_version!==e.expectedStateVersion)throw new Error("Native spec sync state version is stale");if(t.archived||!["build","verify","archive"].includes(t.phase)||t.children_contract_hash)throw new Error("Native spec sync requires a confirmed ordinary active change; revise requirements in Shape otherwise");if(!Ma.test(e.capability)||!e.reason.trim()||!e.actor.trim())throw new Error("Native spec sync requires capability, actor and reason");await NS({paths:e.paths,state:t});let r=t.spec_changes.find(({capability:m,operation:h})=>m===e.capability&&h!=="remove");if(!r?.source)throw new Error("Stage this capability in the current change and confirm Shape before syncing references");let i=new Set(e.affectedAcceptanceIds);if(i.size===0||[...i].some(m=>!t.acceptance.some(h=>h.id===m))||t.acceptance.some(({source:m,id:h})=>m===r.source&&!i.has(h)))throw new Error("Native spec sync must cover the affected spec acceptance IDs");if(e.replacements.length===0||e.replacements.some(({from:m,to:h})=>!/^[A-Za-z0-9_./#%-]+$/u.test(m)||!/^[A-Za-z0-9_./#%-]+$/u.test(h)||m===h)||new Set(e.replacements.map(({from:m})=>m)).size!==e.replacements.length)throw new Error("Native spec sync only accepts unique local Markdown reference replacements");let n=hr(e.paths,t.name),a=await M({root:n,ref:r.source,maxBytes:4*1024*1024,includeHash:!1}),o=new Map(e.replacements.map(({from:m,to:h})=>[m,h])),s=new Set,l=null,c=!1,f=a.text.split(/(?<=\n)/u).map(m=>{let h=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(m.trimEnd());return h?(l?h[1][0]===l.marker&&h[1].length>=l.length&&!h[2].trim()&&(l=null):l={marker:h[1][0],length:h[1].length},m):/^(?:\s|>|[-+*]\s|\d+[.)]\s)/u.test(m)?m:(m.includes("<!--")&&(c=!0),c?(m.includes("-->")&&(c=!1),m):l||/^(?: {4}|\t)/u.test(m)||m.includes("`")?m:m.replace(/(?<!!)\[([^\]\n]+)\]\(([^()\s]+)\)/gu,(v,g,N)=>{let b=o.get(N);return b?(s.add(N),`[${g}](${b})`):v}))}).join("");if(s.size!==o.size)throw new Error("Native spec sync replacement is not an existing prose Markdown reference; use revise-requirements for semantic changes");let d=vt.join(n,r.source);await se(d,f,{containedRoot:e.paths.nativeRoot});let u=!1,p=null;try{let m=await zh({paths:e.paths,state:t,specChanges:t.spec_changes});if(!rc(t.acceptance,m.acceptance))throw new Error("Reference change affects acceptance; revise requirements in Shape");let h=E=>mS("sha256").update(E).digest("hex"),v=JSON.stringify({schema:"comet.native.spec-sync.v1",change:t.name,actor:e.actor,reason:e.reason,source:r.source,beforeHash:h(a.text),afterHash:h(f),replacements:e.replacements,affectedAcceptanceIds:[...i],requiresConfirmation:!1,at:new Date().toISOString()}),g=h(v),N=await Dc({paths:e.paths,name:t.name,hash:g,text:v,onCreated:()=>{p=g}}),b={...t,loop:{...t.loop,previous_unresolved_ids:[...new Set([...t.loop.previous_unresolved_ids,...i])]}},S=t.phase==="build"?{...b,state_version:t.state_version+1,acceptance:t.acceptance.map(E=>i.has(E.id)?{...E,result:"pending",reason:null}:E)}:$h({state:b,reason:`Spec reference sync: ${e.reason}`});S=oi(S,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[...i],summary:It(`Spec reference sync by ${e.actor}: ${e.reason}; ${N}`),completed_at:new Date().toISOString()}),S.shape_confirmation_hash=Jh({formalHash:m.formalHash,childrenHash:null,coordinationMode:t.coordination_mode});let x=await Vc({paths:e.paths,previous:t,next:S});return u=!0,await ur(Pi(e.paths,t.name),lr({portableState:x,projectRoot:e.paths.projectRoot,branch:Bc(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),x}catch(m){if(!u)try{(await Va(e.paths,t.name)).state_version===t.state_version&&(await se(d,a.text,{containedRoot:e.paths.nativeRoot}),p&&await Wh({paths:e.paths,name:t.name,hash:p}))}catch{}throw m}})}async function Uh(e){if(!Ma.test(e.capability))throw new Error(`Invalid Native capability: ${e.capability}`);return re(e.paths,`remove portable spec ${e.capability}`,async()=>{let t=await Va(e.paths,e.name);if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r=t.spec_changes.filter(({capability:a})=>a!==e.capability),i={...t,phase:"shape",status:"active",state_version:t.state_version+1,spec_changes:[...r,{capability:e.capability,operation:"remove",source:null}].sort((a,o)=>a.capability.localeCompare(o.capability,"en")),acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,history:[],history_overflow:{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}},loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+(t.phase==="shape"?0:1),iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await Vc({paths:e.paths,previous:t,next:i});return await ur(Pi(e.paths,t.name),lr({portableState:n,projectRoot:e.paths.projectRoot,branch:Bc(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function bS(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...oi(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:It(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 Vc({paths:e.paths,previous:t,next:i});return await ur(Pi(e.paths,t.name),lr({portableState:n,projectRoot:e.paths.projectRoot,branch:Bc(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}ar();$();mi();var Kh=["evidence.md","repair.md","archive.md","checkpoint.md"],ES="verification.md";async function xS(e,t){let r=await uc(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function Yh(e,t){await Ai.mkdir(e.transactionsDir,{recursive:!0}),await U(va(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Xh(e,t,r={}){let i=r.removeVerificationReport===!1?Kh:[...Kh,ES];await Promise.all([Ai.rm(ht(e,t),{recursive:!0,force:!0}),Ai.rm(Us(e,t),{recursive:!0,force:!0}),...i.map(n=>Ai.rm(SS.join(Le(e,t),n),{force:!0}))])}async function Qh(e,t){await ur(Pi(e,t.name),lr({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function Zh(e,t){try{let r=await pi(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 ep(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=pe(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 CS(e){let t=Le(e.paths,e.state.name),r=await M({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 M({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return aa({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function tp(e,t){let r=await gh(e,t);if(r.status==="runtime-incompatible")throw new mt(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function rp(e){return re(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await xS(e.paths,e.name),r=await Ri(e.paths,e.name)?await ze(gt(e.paths,e.name)):null;if(!t&&r)return await Xh(e.paths,e.name,{removeVerificationReport:!1}),await Qh(e.paths,r),r;let i=null,n=null;for(t||(i=await tp(e.paths,e.name),n=await Zh(e.paths,e.name),ep(e.paths,n),t={schema:pa,id:kS(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Yh(e.paths,t));;){let a=$f(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await tp(e.paths,e.name),n??=await Zh(e.paths,e.name),ep(e.paths,n),r=jf({state:i,acceptance:await CS({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await da(gt(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Xh(e.paths,e.name):a.action==="commit-transaction"&&(r??=await ze(gt(e.paths,e.name)),await Qh(e.paths,r)),t={...t,status:a.nextStatus},await Yh(e.paths,t)}return await Ai.rm(va(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??ze(gt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}ti();import Ii from"path";import{realpathSync as hE}from"fs";Me();var Ke={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function ip(e){return e?e.command?`${Ke.next} ${e.command}`:e.ask_user?`${Ke.next} ${e.ask_user}`:null:null}function np(e,t){let r=[e.summary],i=ip(e.next);return i&&r.push(i),e.user_message&&r.push("",Ke.relay,e.user_message),t!==void 0&&r.push("",Ke.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
153
153
|
`)}
|
|
154
154
|
`}function ap(e,t,r){let i=[e.summary],n=ip(e.next);return n&&i.push(n),e.user_message&&i.push("",Ke.relay,e.user_message),i.push("",`${Ke.detail} ${t}`),r!==void 0&&i.push("",Ke.details,JSON.stringify(r,null,2)),i.join(`
|
|
155
|
-
`)}fi();te();
|
|
156
|
-
`)}}let r=t.continuation;if(hp(r))return tE(r,cE(t),lE(t,qc(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:C(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 cE(e){if(Fc(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Fc(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return ZS(r.acceptance)}return null}function lE(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return C(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?C(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function vp(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:C("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:C("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:C("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:C("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:C("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:C("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:C("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:C("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:C("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}_c();var gp=["--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."],zc=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.","
|
|
157
|
-
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:"
|
|
155
|
+
`)}fi();te();we();G();te();var PS=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});fr();He();mi();G();Se();$();di();O();G();De();ni();fe();$();He();$t();te();te();Da();dr();De();var op={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:[]},AS=he("comet-native-runtime:v3:scope-reopen"),fO=[{skillVersion:"3",skillHash:he("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:he("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:he("comet-native-runtime:v1")}];fi();De();fi();De();gc();ha();var cp=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],JO=new Set(cp),HS=new Set([...cp,"minimum_runtime_version","revision"]),GO=new Set([...HS,"operation"]),UO=512*1024,DS=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),KO=new Set([...DS,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);na();we();G();we();na();te();var e0={maxAcceptanceCriteria:ia.maxCriteria};var a0={maxSpecs:64,maxFileBytes:Di,maxTotalBytes:4*1024*1024};fr();ui();dr();Da();import{execFile as JS}from"node:child_process";Ra();Rc();G();import{promisify as GS}from"node:util";G();O();G();De();$();He();br();$t();var m0={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};fe();O();$c();$();Re();var H0=512*1024;fr();fe();$t();var _i=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};ui();La();dr();var aH=64*1024;var oH=3600*1e3;var sH=GS(JS);La();var Fa=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}};mi();De();He();var WH={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};O();Re();$();He();Ea();var eD=16*1024*1024,tD=256*1024,rD=16*1024;G();O();xt();G();fr();var cD=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});De();ni();fe();$();He();ti();var dD=16*1024;G();Se();fe();var SD=16*1024;Ea();var hL=16*1024*1024,qa=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"},Wa=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"};G();$();Se();function C(e,t,r){return e==="zh-CN"?r:t}var Mc={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function dp(e,t){return typeof e=="string"&&Mc[e]?C(t,Mc[e].en,Mc[e].zh):typeof e=="string"?e:""}function Fc(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 ZS(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 fp(e,t){let r=[];e.failed>0&&r.push(C(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(C(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(C(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=C(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function hp(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 qc(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function eE(e,t,r){return e==="done"?C(r,"complete","已完成"):e==="await-user"?C(r,"waiting for a user decision","等待用户决定"):e==="blocked"?C(r,"paused: needs attention","已暂停,需要处理"):t?C(r,"waiting for a user decision","等待用户决定"):C(r,"ready to continue","可继续推进")}function tE(e,t,r){let i=qc(e),n=[];r&&n.push(r);let a=C(i,`Change ${e.change}`,`需求 ${e.change}`),o=dp(e.phase,i),s=eE(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(fp(t,i));let l=e.userCommunication,c=pp(e,i);return{summary:n.join("; "),...c?{next:c}:{},...l.required&&l.message?{user_message:l.message}:{}}}function pp(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:C(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:C(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:C(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function rE(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function iE(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=dp(e.phase,t),n=e.status==="await-user"?C(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?C(t,"paused","已暂停"):e.status==="done"?C(t,"complete","已完成"):C(t,"in progress","进行中"),a=Fc(e.acceptance)?`${C(t,", ",",")}${fp(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function nE(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 aE(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 oE(e){if(e.healthy){let i=e.repaired?C("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):C("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=sE(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:C("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:C("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function sE(e){return hp(e)?pp(e,qc(e)):void 0}function mp(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(aE(t))return oE(t);if(rE(t)){let i=nE(t.items);return{summary:[t.total===t.items.length?C(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):C(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>iE(a,i))].join(`
|
|
156
|
+
`)}}let r=t.continuation;if(hp(r))return tE(r,cE(t),lE(t,qc(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:C(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 cE(e){if(Fc(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Fc(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return ZS(r.acceptance)}return null}function lE(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return C(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?C(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function vp(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:C("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:C("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:C("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:C("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:C("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:C("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:C("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:C("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:C("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}_c();var gp=["--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."],zc=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:gp,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>
|
|
157
|
+
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>]
|
|
158
158
|
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>]
|
|
159
159
|
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]
|
|
160
160
|
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 Wc(e,t){return`${e}:
|
|
@@ -162,7 +162,7 @@ ${t.map(r=>` ${r}`).join(`
|
|
|
162
162
|
`)}`}function uE(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return zc[r]||t.length>1&&zc[t[0]]?.subcommands?r:t[0]}function dE(e=[]){let t=uE(e),r=zc[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.subcommands&&i.push("",Wc("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...gp];return n&&n.length>0&&i.push("",Wc("Options",n)),i.push("",`Output:
|
|
163
163
|
${r.output}`),r.examples&&i.push("",Wc("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
|
|
164
164
|
`)}
|
|
165
|
-
`}}var fE=dE().usage;var TL=10*1024*1024,Q=class extends Error{};function Gc(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new Q(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function za(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new Q(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new Q(`${t} requires a value`);return e.splice(i,2),n}function Uc(e){if(e.length>0)throw new Q(`Unexpected argument: ${e[0]}`)}function mr(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new Q(`${t} is required`);return r}function Jc(e,t){let r=Ii.normalize(wp(e)),i=Ii.normalize(wp(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function wp(e){let t=Ii.resolve(e);try{return hE.native(t)}catch{return t}}function pE(e){let t=Ii.resolve(e),r=
|
|
165
|
+
`}}var fE=dE().usage;var TL=10*1024*1024,Q=class extends Error{};function Gc(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new Q(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function za(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new Q(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new Q(`${t} requires a value`);return e.splice(i,2),n}function Uc(e){if(e.length>0)throw new Q(`Unexpected argument: ${e[0]}`)}function mr(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new Q(`${t} is required`);return r}function Jc(e,t){let r=Ii.normalize(wp(e)),i=Ii.normalize(wp(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function wp(e){let t=Ii.resolve(e);try{return hE.native(t)}catch{return t}}function pE(e){let t=Ii.resolve(e),r=pe(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=pe(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!Jc(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||Jc(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:Jc(process.cwd(),r.currentWorktreeRoot)?Ii.resolve(process.cwd()):r.currentWorktreeRoot}async function yp(e){return e?pE(e):Kn(process.cwd())}async function Kc(e){let t=await lf({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function Np(e){return JSON.stringify(e,null,2)+`
|
|
166
166
|
`}function Yc(e,t,r){return{command:e,exitCode:0,data:t,text:r??Np(t)}}function mE(e,t){if(t instanceof Q)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof qa)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof Wa)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Ca)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof vi)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof _a)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Pa)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof Fa)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof _i)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function bp(e,t){let r=mE(e,t),i=r.error;if(!i)return r;let n=vp({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function kp(e,t,r=!1){let i=e.envelope??mp(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
|
|
167
167
|
`}:e.error?{exitCode:e.exitCode,stderr:i?ap(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:np(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==Np(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
168
168
|
${Ke.details}
|