@rpamis/comet 0.4.2 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +332 -332
- package/assets/manifest.json +1 -1
- package/assets/skills/comet/scripts/comet-check.mjs +89 -89
- package/assets/skills/comet/scripts/comet-guard.mjs +102 -102
- package/assets/skills/comet/scripts/comet-hook-router.mjs +106 -106
- package/assets/skills/comet/scripts/comet-runtime.mjs +227 -227
- package/assets/skills/comet/scripts/comet-state.mjs +124 -124
- package/assets/skills/comet-classic/SKILL.md +2 -0
- package/assets/skills/comet-classic/reference/scripts.md +8 -0
- package/assets/skills/comet-hotfix/SKILL.md +1 -0
- package/assets/skills/comet-native/SKILL.md +3 -1
- package/assets/skills/comet-native/reference/commands.md +10 -0
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +13 -13
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +31 -31
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +26 -26
- package/assets/skills/comet-tweak/SKILL.md +1 -0
- package/assets/skills-zh/comet-classic/SKILL.md +2 -0
- package/assets/skills-zh/comet-classic/reference/scripts.md +2 -0
- package/assets/skills-zh/comet-hotfix/SKILL.md +1 -0
- package/assets/skills-zh/comet-native/SKILL.md +3 -1
- package/assets/skills-zh/comet-native/reference/commands.md +10 -0
- package/assets/skills-zh/comet-tweak/SKILL.md +1 -0
- package/bin/comet-daemon-router.js +35 -7
- package/dist/app/commands/daemon-server.d.ts.map +1 -1
- package/dist/app/commands/daemon-server.js +1 -0
- package/dist/app/commands/daemon-server.js.map +1 -1
- package/dist/app/commands/project-knowledge.d.ts.map +1 -1
- package/dist/app/commands/project-knowledge.js +0 -1
- package/dist/app/commands/project-knowledge.js.map +1 -1
- package/dist/domains/comet-classic/classic-check-snapshot.d.ts +2 -0
- package/dist/domains/comet-classic/classic-check-snapshot.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-check-snapshot.js +22 -1
- package/dist/domains/comet-classic/classic-check-snapshot.js.map +1 -1
- package/dist/domains/comet-native/native-portable-checks.d.ts +1 -0
- package/dist/domains/comet-native/native-portable-checks.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-checks.js +8 -6
- package/dist/domains/comet-native/native-portable-checks.js.map +1 -1
- package/dist/domains/project-knowledge/corpus.d.ts +5 -0
- package/dist/domains/project-knowledge/corpus.d.ts.map +1 -1
- package/dist/domains/project-knowledge/corpus.js +34 -9
- package/dist/domains/project-knowledge/corpus.js.map +1 -1
- package/dist/domains/project-knowledge/index-store.d.ts +5 -2
- package/dist/domains/project-knowledge/index-store.d.ts.map +1 -1
- package/dist/domains/project-knowledge/index-store.js +95 -52
- package/dist/domains/project-knowledge/index-store.js.map +1 -1
- package/dist/domains/project-knowledge/local-provider.d.ts.map +1 -1
- package/dist/domains/project-knowledge/local-provider.js +14 -3
- package/dist/domains/project-knowledge/local-provider.js.map +1 -1
- package/dist/domains/project-knowledge/local-store.d.ts +2 -2
- package/dist/domains/project-knowledge/local-store.d.ts.map +1 -1
- package/dist/domains/project-knowledge/local-store.js +2 -2
- package/dist/domains/project-knowledge/local-store.js.map +1 -1
- package/dist/domains/project-knowledge/plugin.d.ts.map +1 -1
- package/dist/domains/project-knowledge/plugin.js +5 -4
- package/dist/domains/project-knowledge/plugin.js.map +1 -1
- package/dist/domains/project-knowledge/provider-factory.d.ts.map +1 -1
- package/dist/domains/project-knowledge/provider-factory.js +7 -5
- package/dist/domains/project-knowledge/provider-factory.js.map +1 -1
- package/dist/domains/project-knowledge/types.d.ts +1 -0
- package/dist/domains/project-knowledge/types.d.ts.map +1 -1
- package/dist/domains/skill/platform-install.d.ts.map +1 -1
- package/dist/domains/skill/platform-install.js +31 -3
- package/dist/domains/skill/platform-install.js.map +1 -1
- package/dist/platform/process/comet-daemon.d.ts.map +1 -1
- package/dist/platform/process/comet-daemon.js +1 -0
- package/dist/platform/process/comet-daemon.js.map +1 -1
- package/dist/platform/process/windows-process-broker.d.ts +12 -0
- package/dist/platform/process/windows-process-broker.d.ts.map +1 -0
- package/dist/platform/process/windows-process-broker.js +91 -0
- package/dist/platform/process/windows-process-broker.js.map +1 -0
- package/package.json +1 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
3
|
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
-
var oh=Object.create;var no=Object.defineProperty;var ah=Object.getOwnPropertyDescriptor;var ch=Object.getOwnPropertyNames;var lh=Object.getPrototypeOf,uh=Object.prototype.hasOwnProperty;var oi=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var z=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var E=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},dh=(t,e)=>{for(var n in e)no(t,n,{get:e[n],enumerable:!0})},fh=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ch(e))!uh.call(t,i)&&i!==n&&no(t,i,{get:()=>e[i],enumerable:!(r=ah(e,i))||r.enumerable});return t};var _e=(t,e,n)=>(n=t!=null?oh(lh(t)):{},fh(e||!t||!t.__esModule?no(n,"default",{value:t,enumerable:!0}):n,t));import{promises as io}from"node:fs";async function so(t,e){let n;for(let r=0;r<=ro.length;r+=1)try{return await t()}catch(i){n=i;let s=i.code;if(r===ro.length||!mh.has(s??""))throw i;await new Promise(o=>setTimeout(o,ro[r]))}throw n}async function sl(t,e){await so(()=>io.rename(t,e),`rename ${e}`)}async function ai(t){await so(()=>io.unlink(t),`unlink ${t}`)}async function ol(t,e){await so(()=>io.link(t,e),`link ${e}`)}var mh,ro,oo=z(()=>{"use strict";mh=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),ro=[50,100,200]});function ht(t){return t!==0&&t!==0n&&t!=="0"}function al(t,e){return ht(t.dev)&&ht(e.dev)&&ht(t.ino)&&ht(e.ino)}function gt(t,e){let n=ht(t.dev)&&ht(e.dev);if(n&&t.dev!==e.dev)return!1;let r=ht(t.ino)&&ht(e.ino);return r&&t.ino!==e.ino?!1:n&&r?!0:t.birthtime===e.birthtime}var ci=z(()=>{"use strict"});import{randomUUID as ph}from"crypto";import{constants as hh,promises as ie}from"fs";import ae from"path";async function ao(t,e){try{return await ol(t,e),{linked:!0}}catch(n){let r=n.code;if(r!=="ENOTSUP"&&r!=="EOPNOTSUPP")throw n}return await ie.copyFile(t,e,hh.COPYFILE_EXCL),{linked:!1}}function Qt(t,e){let n=ae.relative(t,e);return n===""||!ae.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${ae.sep}`)}function li(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function gh(t,e){return gt(t,li(e))}function ui(t,e){return gt(li(t),li(e))}function cl(t,e){return ui(t,e)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function di(t){let e=await ie.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await ie.realpath(t),...li(e)}}async function rt(t){for(let e of t){let n=await ie.lstat(e.path);if(!n.isDirectory()||n.isSymbolicLink()||!gh(e,n)||await ie.realpath(e.path)!==e.realPath)throw new Error(`Contained atomic write parent changed before commit: ${e.path}`)}}async function wh(t,e,n){let[r,i]=await Promise.all([ie.lstat(t),ie.realpath(t),rt(n)]);if(!r.isFile()||r.isSymbolicLink()||!ui(r,e)||!Qt(n[0].realPath,i))throw new Error("Contained atomic write temporary file changed after close");return r}async function yh(t,e){let n=ae.resolve(t),r=ae.resolve(e);if(!Qt(n,r))throw new Error(`Contained atomic write parent is outside its managed root: ${e}`);let i=[await di(n)],s=ae.relative(n,r).split(ae.sep).filter(Boolean),o=n;for(let a of s){await rt(i),o=ae.join(o,a);try{await ie.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await di(o);if(!Qt(i[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);i.push(c)}return await rt(i),i}async function vh(t,e){let n=ae.resolve(t),r=ae.resolve(e);if(!Qt(n,r))throw new Error(`Contained file parent is outside its managed root: ${e}`);let i=[await di(n)],s=ae.relative(n,r).split(ae.sep).filter(Boolean),o=n;for(let a of s){o=ae.join(o,a);try{let c=await di(o);if(!Qt(i[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);i.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await rt(i),i}async function ll(t){let e;try{e=await ie.open(t,"r"),await e.sync()}catch(n){let r=n.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw n}finally{await e?.close()}}async function kh(t,e,n){let r=ae.dirname(t),i=await yh(n.containedRoot,r),s=ae.join(r,`.${ae.basename(t)}.${ph()}.tmp`),o,a,c;try{await n.beforeTemporaryOpen?.(),o=await ie.open(s,"wx"),a=await o.stat();let[l,u]=await Promise.all([ie.lstat(s),ie.realpath(s)]);if(await rt(i),!l.isFile()||l.isSymbolicLink()||!ui(a,l)||!Qt(i[0].realPath,u))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),c=await o.stat(),!ui(a,c))throw new Error("Contained atomic write temporary file changed while writing");if(await o.close(),o=void 0,await n.afterTemporaryClose?.(),!c)throw new Error("Contained atomic write temporary file was not written");c=await wh(s,c,i),await n.beforeCommit?.(),await rt(i);let d=await ie.lstat(s);if(!d.isFile()||d.isSymbolicLink()||!c||!cl(d,c))throw new Error("Contained atomic write temporary file changed before commit");n.exclusive?(await ao(s,t),await ie.unlink(s)):await sl(s,t),await ll(r)}catch(l){await o?.close();try{await rt(i),await ie.rm(s,{force:!0})}catch{}throw l}}async function we(t,e,n){await kh(t,e,n)}async function Cn(t,e){let n=ae.dirname(t),r=await vh(e.containedRoot,n);if(!r)return!1;let i,s;try{i=await ie.lstat(t),s=await ie.realpath(t)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!i.isFile()||i.isSymbolicLink()||!Qt(r[0].realPath,s))throw new Error("Contained file removal target must be a regular file inside its managed root");await e.beforeRemove?.(),await rt(r);let[o,a]=await Promise.all([ie.lstat(t),ie.realpath(t)]);if(!o.isFile()||o.isSymbolicLink()||!cl(i,o)||a!==s)throw new Error("Contained file removal target changed before removal");return await ai(t),await rt(r),await ll(n),!0}var it=z(()=>{"use strict";oo();ci()});var D=E(ce=>{"use strict";var co=Symbol.for("yaml.alias"),ul=Symbol.for("yaml.document"),fi=Symbol.for("yaml.map"),dl=Symbol.for("yaml.pair"),lo=Symbol.for("yaml.scalar"),mi=Symbol.for("yaml.seq"),st=Symbol.for("yaml.node.type"),bh=t=>!!t&&typeof t=="object"&&t[st]===co,Ch=t=>!!t&&typeof t=="object"&&t[st]===ul,Sh=t=>!!t&&typeof t=="object"&&t[st]===fi,Eh=t=>!!t&&typeof t=="object"&&t[st]===dl,fl=t=>!!t&&typeof t=="object"&&t[st]===lo,xh=t=>!!t&&typeof t=="object"&&t[st]===mi;function ml(t){if(t&&typeof t=="object")switch(t[st]){case fi:case mi:return!0}return!1}function _h(t){if(t&&typeof t=="object")switch(t[st]){case co:case fi:case lo:case mi:return!0}return!1}var Rh=t=>(fl(t)||ml(t))&&!!t.anchor;ce.ALIAS=co;ce.DOC=ul;ce.MAP=fi;ce.NODE_TYPE=st;ce.PAIR=dl;ce.SCALAR=lo;ce.SEQ=mi;ce.hasAnchor=Rh;ce.isAlias=bh;ce.isCollection=ml;ce.isDocument=Ch;ce.isMap=Sh;ce.isNode=_h;ce.isPair=Eh;ce.isScalar=fl;ce.isSeq=xh});var Jn=E(uo=>{"use strict";var se=D(),be=Symbol("break visit"),pl=Symbol("skip children"),Je=Symbol("remove node");function pi(t,e){let n=hl(e);se.isDocument(t)?Sn(null,t.contents,n,Object.freeze([t]))===Je&&(t.contents=null):Sn(null,t,n,Object.freeze([]))}pi.BREAK=be;pi.SKIP=pl;pi.REMOVE=Je;function Sn(t,e,n,r){let i=gl(t,e,n,r);if(se.isNode(i)||se.isPair(i))return wl(t,r,i),Sn(t,i,n,r);if(typeof i!="symbol"){if(se.isCollection(e)){r=Object.freeze(r.concat(e));for(let s=0;s<e.items.length;++s){let o=Sn(s,e.items[s],n,r);if(typeof o=="number")s=o-1;else{if(o===be)return be;o===Je&&(e.items.splice(s,1),s-=1)}}}else if(se.isPair(e)){r=Object.freeze(r.concat(e));let s=Sn("key",e.key,n,r);if(s===be)return be;s===Je&&(e.key=null);let o=Sn("value",e.value,n,r);if(o===be)return be;o===Je&&(e.value=null)}}return i}async function hi(t,e){let n=hl(e);se.isDocument(t)?await En(null,t.contents,n,Object.freeze([t]))===Je&&(t.contents=null):await En(null,t,n,Object.freeze([]))}hi.BREAK=be;hi.SKIP=pl;hi.REMOVE=Je;async function En(t,e,n,r){let i=await gl(t,e,n,r);if(se.isNode(i)||se.isPair(i))return wl(t,r,i),En(t,i,n,r);if(typeof i!="symbol"){if(se.isCollection(e)){r=Object.freeze(r.concat(e));for(let s=0;s<e.items.length;++s){let o=await En(s,e.items[s],n,r);if(typeof o=="number")s=o-1;else{if(o===be)return be;o===Je&&(e.items.splice(s,1),s-=1)}}}else if(se.isPair(e)){r=Object.freeze(r.concat(e));let s=await En("key",e.key,n,r);if(s===be)return be;s===Je&&(e.key=null);let o=await En("value",e.value,n,r);if(o===be)return be;o===Je&&(e.value=null)}}return i}function hl(t){return typeof t=="object"&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function gl(t,e,n,r){if(typeof n=="function")return n(t,e,r);if(se.isMap(e))return n.Map?.(t,e,r);if(se.isSeq(e))return n.Seq?.(t,e,r);if(se.isPair(e))return n.Pair?.(t,e,r);if(se.isScalar(e))return n.Scalar?.(t,e,r);if(se.isAlias(e))return n.Alias?.(t,e,r)}function wl(t,e,n){let r=e[e.length-1];if(se.isCollection(r))r.items[t]=n;else if(se.isPair(r))t==="key"?r.key=n:r.value=n;else if(se.isDocument(r))r.contents=n;else{let i=se.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}uo.visit=pi;uo.visitAsync=hi});var fo=E(vl=>{"use strict";var yl=D(),Ph=Jn(),Ah={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Oh=t=>t.replace(/[!,[\]{}]/g,e=>Ah[e]),Gn=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let r=e.trim().split(/[ \t]+/),i=r.shift();switch(i){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[s,o]=r;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=r;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,o),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,r,i]=e.match(/^(.*!)([^!]*)$/s);i||n(`The ${e} tag has no suffix`);let s=this.tags[r];if(s)try{return s+decodeURIComponent(i)}catch(o){return n(String(o)),null}return r==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,r]of Object.entries(this.tags))if(e.startsWith(r))return n+Oh(e.substring(r.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),i;if(e&&r.length>0&&yl.isNode(e.contents)){let s={};Ph.visit(e.contents,(o,a)=>{yl.isNode(a)&&a.tag&&(s[a.tag]=!0)}),i=Object.keys(s)}else i=[];for(let[s,o]of r)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&n.push(`%TAG ${s} ${o}`);return n.join(`
|
|
5
|
-
`)}};Gn.defaultYaml={explicit:!1,version:"1.2"};Gn.defaultTags={"!!":"tag:yaml.org,2002:"};vl.Directives=Gn});var gi=E(Yn=>{"use strict";var kl=D(),Nh=Jn();function jh(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function bl(t){let e=new Set;return Nh.visit(t,{Value(n,r){r.anchor&&e.add(r.anchor)}}),e}function Cl(t,e){for(let n=1;;++n){let r=`${t}${n}`;if(!e.has(r))return r}}function Ih(t,e){let n=[],r=new Map,i=null;return{onAnchor:s=>{n.push(s),i??(i=bl(t));let o=Cl(e,i);return i.add(o),o},setAnchors:()=>{for(let s of n){let o=r.get(s);if(typeof o=="object"&&o.anchor&&(kl.isScalar(o.node)||kl.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:r}}Yn.anchorIsValid=jh;Yn.anchorNames=bl;Yn.createNodeAnchors=Ih;Yn.findNewAnchor=Cl});var mo=E(Sl=>{"use strict";function Vn(t,e,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let i=0,s=r.length;i<s;++i){let o=r[i],a=Vn(t,r,String(i),o);a===void 0?delete r[i]:a!==o&&(r[i]=a)}else if(r instanceof Map)for(let i of Array.from(r.keys())){let s=r.get(i),o=Vn(t,r,i,s);o===void 0?r.delete(i):o!==s&&r.set(i,o)}else if(r instanceof Set)for(let i of Array.from(r)){let s=Vn(t,r,i,i);s===void 0?r.delete(i):s!==i&&(r.delete(i),r.add(s))}else for(let[i,s]of Object.entries(r)){let o=Vn(t,r,i,s);o===void 0?delete r[i]:o!==s&&(r[i]=o)}return t.call(e,n,r)}Sl.applyReviver=Vn});var
|
|
4
|
+
var oh=Object.create;var no=Object.defineProperty;var ah=Object.getOwnPropertyDescriptor;var ch=Object.getOwnPropertyNames;var lh=Object.getPrototypeOf,uh=Object.prototype.hasOwnProperty;var oi=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var z=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var E=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},dh=(t,e)=>{for(var n in e)no(t,n,{get:e[n],enumerable:!0})},fh=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ch(e))!uh.call(t,i)&&i!==n&&no(t,i,{get:()=>e[i],enumerable:!(r=ah(e,i))||r.enumerable});return t};var Pe=(t,e,n)=>(n=t!=null?oh(lh(t)):{},fh(e||!t||!t.__esModule?no(n,"default",{value:t,enumerable:!0}):n,t));import{promises as io}from"node:fs";async function so(t,e){let n;for(let r=0;r<=ro.length;r+=1)try{return await t()}catch(i){n=i;let s=i.code;if(r===ro.length||!mh.has(s??""))throw i;await new Promise(o=>setTimeout(o,ro[r]))}throw n}async function sl(t,e){await so(()=>io.rename(t,e),`rename ${e}`)}async function ai(t){await so(()=>io.unlink(t),`unlink ${t}`)}async function ol(t,e){await so(()=>io.link(t,e),`link ${e}`)}var mh,ro,oo=z(()=>{"use strict";mh=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),ro=[50,100,200]});function gt(t){return t!==0&&t!==0n&&t!=="0"}function al(t,e){return gt(t.dev)&>(e.dev)&>(t.ino)&>(e.ino)}function wt(t,e){let n=gt(t.dev)&>(e.dev);if(n&&t.dev!==e.dev)return!1;let r=gt(t.ino)&>(e.ino);return r&&t.ino!==e.ino?!1:n&&r?!0:t.birthtime===e.birthtime}var ci=z(()=>{"use strict"});import{randomUUID as ph}from"crypto";import{constants as hh,promises as ne}from"fs";import ae from"path";async function ao(t,e){try{return await ol(t,e),{linked:!0}}catch(n){let r=n.code;if(r!=="ENOTSUP"&&r!=="EOPNOTSUPP")throw n}return await ne.copyFile(t,e,hh.COPYFILE_EXCL),{linked:!1}}function Qt(t,e){let n=ae.relative(t,e);return n===""||!ae.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${ae.sep}`)}function li(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function gh(t,e){return wt(t,li(e))}function ui(t,e){return wt(li(t),li(e))}function cl(t,e){return ui(t,e)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function di(t){let e=await ne.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await ne.realpath(t),...li(e)}}async function st(t){for(let e of t){let n=await ne.lstat(e.path);if(!n.isDirectory()||n.isSymbolicLink()||!gh(e,n)||await ne.realpath(e.path)!==e.realPath)throw new Error(`Contained atomic write parent changed before commit: ${e.path}`)}}async function wh(t,e,n){let[r,i]=await Promise.all([ne.lstat(t),ne.realpath(t),st(n)]);if(!r.isFile()||r.isSymbolicLink()||!ui(r,e)||!Qt(n[0].realPath,i))throw new Error("Contained atomic write temporary file changed after close");return r}async function yh(t,e){let n=ae.resolve(t),r=ae.resolve(e);if(!Qt(n,r))throw new Error(`Contained atomic write parent is outside its managed root: ${e}`);let i=[await di(n)],s=ae.relative(n,r).split(ae.sep).filter(Boolean),o=n;for(let a of s){await st(i),o=ae.join(o,a);try{await ne.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await di(o);if(!Qt(i[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);i.push(c)}return await st(i),i}async function vh(t,e){let n=ae.resolve(t),r=ae.resolve(e);if(!Qt(n,r))throw new Error(`Contained file parent is outside its managed root: ${e}`);let i=[await di(n)],s=ae.relative(n,r).split(ae.sep).filter(Boolean),o=n;for(let a of s){o=ae.join(o,a);try{let c=await di(o);if(!Qt(i[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);i.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await st(i),i}async function ll(t){let e;try{e=await ne.open(t,"r"),await e.sync()}catch(n){let r=n.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw n}finally{await e?.close()}}async function kh(t,e,n){let r=ae.dirname(t),i=await yh(n.containedRoot,r),s=ae.join(r,`.${ae.basename(t)}.${ph()}.tmp`),o,a,c;try{await n.beforeTemporaryOpen?.(),o=await ne.open(s,"wx"),a=await o.stat();let[l,u]=await Promise.all([ne.lstat(s),ne.realpath(s)]);if(await st(i),!l.isFile()||l.isSymbolicLink()||!ui(a,l)||!Qt(i[0].realPath,u))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),c=await o.stat(),!ui(a,c))throw new Error("Contained atomic write temporary file changed while writing");if(await o.close(),o=void 0,await n.afterTemporaryClose?.(),!c)throw new Error("Contained atomic write temporary file was not written");c=await wh(s,c,i),await n.beforeCommit?.(),await st(i);let d=await ne.lstat(s);if(!d.isFile()||d.isSymbolicLink()||!c||!cl(d,c))throw new Error("Contained atomic write temporary file changed before commit");n.exclusive?(await ao(s,t),await ne.unlink(s)):await sl(s,t),await ll(r)}catch(l){await o?.close();try{await st(i),await ne.rm(s,{force:!0})}catch{}throw l}}async function ye(t,e,n){await kh(t,e,n)}async function Cn(t,e){let n=ae.dirname(t),r=await vh(e.containedRoot,n);if(!r)return!1;let i,s;try{i=await ne.lstat(t),s=await ne.realpath(t)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!i.isFile()||i.isSymbolicLink()||!Qt(r[0].realPath,s))throw new Error("Contained file removal target must be a regular file inside its managed root");await e.beforeRemove?.(),await st(r);let[o,a]=await Promise.all([ne.lstat(t),ne.realpath(t)]);if(!o.isFile()||o.isSymbolicLink()||!cl(i,o)||a!==s)throw new Error("Contained file removal target changed before removal");return await ai(t),await st(r),await ll(n),!0}var ot=z(()=>{"use strict";oo();ci()});var D=E(ce=>{"use strict";var co=Symbol.for("yaml.alias"),ul=Symbol.for("yaml.document"),fi=Symbol.for("yaml.map"),dl=Symbol.for("yaml.pair"),lo=Symbol.for("yaml.scalar"),mi=Symbol.for("yaml.seq"),at=Symbol.for("yaml.node.type"),bh=t=>!!t&&typeof t=="object"&&t[at]===co,Ch=t=>!!t&&typeof t=="object"&&t[at]===ul,Sh=t=>!!t&&typeof t=="object"&&t[at]===fi,Eh=t=>!!t&&typeof t=="object"&&t[at]===dl,fl=t=>!!t&&typeof t=="object"&&t[at]===lo,xh=t=>!!t&&typeof t=="object"&&t[at]===mi;function ml(t){if(t&&typeof t=="object")switch(t[at]){case fi:case mi:return!0}return!1}function _h(t){if(t&&typeof t=="object")switch(t[at]){case co:case fi:case lo:case mi:return!0}return!1}var Rh=t=>(fl(t)||ml(t))&&!!t.anchor;ce.ALIAS=co;ce.DOC=ul;ce.MAP=fi;ce.NODE_TYPE=at;ce.PAIR=dl;ce.SCALAR=lo;ce.SEQ=mi;ce.hasAnchor=Rh;ce.isAlias=bh;ce.isCollection=ml;ce.isDocument=Ch;ce.isMap=Sh;ce.isNode=_h;ce.isPair=Eh;ce.isScalar=fl;ce.isSeq=xh});var Jn=E(uo=>{"use strict";var re=D(),Se=Symbol("break visit"),pl=Symbol("skip children"),Ge=Symbol("remove node");function pi(t,e){let n=hl(e);re.isDocument(t)?Sn(null,t.contents,n,Object.freeze([t]))===Ge&&(t.contents=null):Sn(null,t,n,Object.freeze([]))}pi.BREAK=Se;pi.SKIP=pl;pi.REMOVE=Ge;function Sn(t,e,n,r){let i=gl(t,e,n,r);if(re.isNode(i)||re.isPair(i))return wl(t,r,i),Sn(t,i,n,r);if(typeof i!="symbol"){if(re.isCollection(e)){r=Object.freeze(r.concat(e));for(let s=0;s<e.items.length;++s){let o=Sn(s,e.items[s],n,r);if(typeof o=="number")s=o-1;else{if(o===Se)return Se;o===Ge&&(e.items.splice(s,1),s-=1)}}}else if(re.isPair(e)){r=Object.freeze(r.concat(e));let s=Sn("key",e.key,n,r);if(s===Se)return Se;s===Ge&&(e.key=null);let o=Sn("value",e.value,n,r);if(o===Se)return Se;o===Ge&&(e.value=null)}}return i}async function hi(t,e){let n=hl(e);re.isDocument(t)?await En(null,t.contents,n,Object.freeze([t]))===Ge&&(t.contents=null):await En(null,t,n,Object.freeze([]))}hi.BREAK=Se;hi.SKIP=pl;hi.REMOVE=Ge;async function En(t,e,n,r){let i=await gl(t,e,n,r);if(re.isNode(i)||re.isPair(i))return wl(t,r,i),En(t,i,n,r);if(typeof i!="symbol"){if(re.isCollection(e)){r=Object.freeze(r.concat(e));for(let s=0;s<e.items.length;++s){let o=await En(s,e.items[s],n,r);if(typeof o=="number")s=o-1;else{if(o===Se)return Se;o===Ge&&(e.items.splice(s,1),s-=1)}}}else if(re.isPair(e)){r=Object.freeze(r.concat(e));let s=await En("key",e.key,n,r);if(s===Se)return Se;s===Ge&&(e.key=null);let o=await En("value",e.value,n,r);if(o===Se)return Se;o===Ge&&(e.value=null)}}return i}function hl(t){return typeof t=="object"&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function gl(t,e,n,r){if(typeof n=="function")return n(t,e,r);if(re.isMap(e))return n.Map?.(t,e,r);if(re.isSeq(e))return n.Seq?.(t,e,r);if(re.isPair(e))return n.Pair?.(t,e,r);if(re.isScalar(e))return n.Scalar?.(t,e,r);if(re.isAlias(e))return n.Alias?.(t,e,r)}function wl(t,e,n){let r=e[e.length-1];if(re.isCollection(r))r.items[t]=n;else if(re.isPair(r))t==="key"?r.key=n:r.value=n;else if(re.isDocument(r))r.contents=n;else{let i=re.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}uo.visit=pi;uo.visitAsync=hi});var fo=E(vl=>{"use strict";var yl=D(),Ph=Jn(),Ah={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Oh=t=>t.replace(/[!,[\]{}]/g,e=>Ah[e]),Gn=class t{constructor(e,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,n)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,n){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let r=e.trim().split(/[ \t]+/),i=r.shift();switch(i){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[s,o]=r;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=r;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return n(6,`Unsupported YAML version ${s}`,o),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,n){if(e==="!")return"!";if(e[0]!=="!")return n(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,r,i]=e.match(/^(.*!)([^!]*)$/s);i||n(`The ${e} tag has no suffix`);let s=this.tags[r];if(s)try{return s+decodeURIComponent(i)}catch(o){return n(String(o)),null}return r==="!"?e:(n(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[n,r]of Object.entries(this.tags))if(e.startsWith(r))return n+Oh(e.substring(r.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),i;if(e&&r.length>0&&yl.isNode(e.contents)){let s={};Ph.visit(e.contents,(o,a)=>{yl.isNode(a)&&a.tag&&(s[a.tag]=!0)}),i=Object.keys(s)}else i=[];for(let[s,o]of r)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&n.push(`%TAG ${s} ${o}`);return n.join(`
|
|
5
|
+
`)}};Gn.defaultYaml={explicit:!1,version:"1.2"};Gn.defaultTags={"!!":"tag:yaml.org,2002:"};vl.Directives=Gn});var gi=E(Yn=>{"use strict";var kl=D(),Nh=Jn();function jh(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(n)}return!0}function bl(t){let e=new Set;return Nh.visit(t,{Value(n,r){r.anchor&&e.add(r.anchor)}}),e}function Cl(t,e){for(let n=1;;++n){let r=`${t}${n}`;if(!e.has(r))return r}}function Ih(t,e){let n=[],r=new Map,i=null;return{onAnchor:s=>{n.push(s),i??(i=bl(t));let o=Cl(e,i);return i.add(o),o},setAnchors:()=>{for(let s of n){let o=r.get(s);if(typeof o=="object"&&o.anchor&&(kl.isScalar(o.node)||kl.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:r}}Yn.anchorIsValid=jh;Yn.anchorNames=bl;Yn.createNodeAnchors=Ih;Yn.findNewAnchor=Cl});var mo=E(Sl=>{"use strict";function Vn(t,e,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let i=0,s=r.length;i<s;++i){let o=r[i],a=Vn(t,r,String(i),o);a===void 0?delete r[i]:a!==o&&(r[i]=a)}else if(r instanceof Map)for(let i of Array.from(r.keys())){let s=r.get(i),o=Vn(t,r,i,s);o===void 0?r.delete(i):o!==s&&r.set(i,o)}else if(r instanceof Set)for(let i of Array.from(r)){let s=Vn(t,r,i,i);s===void 0?r.delete(i):s!==i&&(r.delete(i),r.add(s))}else for(let[i,s]of Object.entries(r)){let o=Vn(t,r,i,s);o===void 0?delete r[i]:o!==s&&(r[i]=o)}return t.call(e,n,r)}Sl.applyReviver=Vn});var yt=E(xl=>{"use strict";var $h=D();function El(t,e,n){if(Array.isArray(t))return t.map((r,i)=>El(r,String(i),n));if(t&&typeof t.toJSON=="function"){if(!n||!$h.hasAnchor(t))return t.toJSON(e,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(t,r),n.onCreate=s=>{r.res=s,delete n.onCreate};let i=t.toJSON(e,n);return n.onCreate&&n.onCreate(i),i}return typeof t=="bigint"&&!n?.keep?Number(t):t}xl.toJS=El});var wi=E(Rl=>{"use strict";var Th=mo(),_l=D(),Lh=yt(),po=class{constructor(e){Object.defineProperty(this,_l.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:s}={}){if(!_l.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=Lh.toJS(this,"",o);if(typeof i=="function")for(let{count:c,res:l}of o.anchors.values())i(l,c);return typeof s=="function"?Th.applyReviver(s,{"":a},"",a):a}};Rl.NodeBase=po});var Xn=E(Pl=>{"use strict";var qh=gi(),Mh=Jn(),xn=D(),Fh=wi(),Dh=yt(),ho=class extends Fh.NodeBase{constructor(e){super(xn.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],Mh.visit(e,{Node:(s,o)=>{(xn.isAlias(o)||xn.hasAnchor(o))&&r.push(o)}}),n&&(n.aliasResolveCache=r));let i;for(let s of r){if(s===this)break;s.anchor===this.source&&(i=s)}return i}toJSON(e,n){if(!n)return{source:this.source};let{anchors:r,doc:i,maxAliasCount:s}=n,o=this.resolve(i,n);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=r.get(o);if(a||(Dh.toJS(o,null,n),a=r.get(o)),a?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=yi(i,o,r)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,n,r){let i=`*${this.source}`;if(e){if(qh.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${i} `}return i}};function yi(t,e,n){if(xn.isAlias(e)){let r=e.resolve(t),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}else if(xn.isCollection(e)){let r=0;for(let i of e.items){let s=yi(t,i,n);s>r&&(r=s)}return r}else if(xn.isPair(e)){let r=yi(t,e.key,n),i=yi(t,e.value,n);return Math.max(r,i)}return 1}Pl.Alias=ho});var Z=E(go=>{"use strict";var Wh=D(),Bh=wi(),Uh=yt(),Kh=t=>!t||typeof t!="function"&&typeof t!="object",vt=class extends Bh.NodeBase{constructor(e){super(Wh.SCALAR),this.value=e}toJSON(e,n){return n?.keep?this.value:Uh.toJS(this.value,e,n)}toString(){return String(this.value)}};vt.BLOCK_FOLDED="BLOCK_FOLDED";vt.BLOCK_LITERAL="BLOCK_LITERAL";vt.PLAIN="PLAIN";vt.QUOTE_DOUBLE="QUOTE_DOUBLE";vt.QUOTE_SINGLE="QUOTE_SINGLE";go.Scalar=vt;go.isScalarValue=Kh});var Qn=E(Ol=>{"use strict";var Hh=Xn(),Zt=D(),Al=Z(),zh="tag:yaml.org,2002:";function Jh(t,e,n){if(e){let r=n.filter(s=>s.tag===e),i=r.find(s=>!s.format)??r[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return n.find(r=>r.identify?.(t)&&!r.format)}function Gh(t,e,n){if(Zt.isDocument(t)&&(t=t.contents),Zt.isNode(t))return t;if(Zt.isPair(t)){let d=n.schema[Zt.MAP].createNode?.(n.schema,null,n);return d.items.push(t),d}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=n,c;if(r&&t&&typeof t=="object"){if(c=a.get(t),c)return c.anchor??(c.anchor=i(t)),new Hh.Alias(c.anchor);c={anchor:null,node:null},a.set(t,c)}e?.startsWith("!!")&&(e=zh+e.slice(2));let l=Jh(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let d=new Al.Scalar(t);return c&&(c.node=d),d}l=t instanceof Map?o[Zt.MAP]:Symbol.iterator in Object(t)?o[Zt.SEQ]:o[Zt.MAP]}s&&(s(l),delete n.onTagObj);let u=l?.createNode?l.createNode(n.schema,t,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,t,n):new Al.Scalar(t);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}Ol.createNode=Gh});var ki=E(vi=>{"use strict";var Yh=Qn(),Ye=D(),Vh=wi();function wo(t,e,n){let r=n;for(let i=e.length-1;i>=0;--i){let s=e[i];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=r,r=o}else r=new Map([[s,r]])}return Yh.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Nl=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,yo=class extends Vh.NodeBase{constructor(e,n){super(e),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(e){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(n.schema=e),n.items=n.items.map(r=>Ye.isNode(r)||Ye.isPair(r)?r.clone(e):r),this.range&&(n.range=this.range.slice()),n}addIn(e,n){if(Nl(e))this.add(n);else{let[r,...i]=e,s=this.get(r,!0);if(Ye.isCollection(s))s.addIn(i,n);else if(s===void 0&&this.schema)this.set(r,wo(this.schema,i,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}}deleteIn(e){let[n,...r]=e;if(r.length===0)return this.delete(n);let i=this.get(n,!0);if(Ye.isCollection(i))return i.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(e,n){let[r,...i]=e,s=this.get(r,!0);return i.length===0?!n&&Ye.isScalar(s)?s.value:s:Ye.isCollection(s)?s.getIn(i,n):void 0}hasAllNullValues(e){return this.items.every(n=>{if(!Ye.isPair(n))return!1;let r=n.value;return r==null||e&&Ye.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[n,...r]=e;if(r.length===0)return this.has(n);let i=this.get(n,!0);return Ye.isCollection(i)?i.hasIn(r):!1}setIn(e,n){let[r,...i]=e;if(i.length===0)this.set(r,n);else{let s=this.get(r,!0);if(Ye.isCollection(s))s.setIn(i,n);else if(s===void 0&&this.schema)this.set(r,wo(this.schema,i,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}}};vi.Collection=yo;vi.collectionFromPath=wo;vi.isEmptyPath=Nl});var Zn=E(bi=>{"use strict";var Xh=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function vo(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Qh=(t,e,n)=>t.endsWith(`
|
|
6
6
|
`)?vo(n,e):n.includes(`
|
|
7
7
|
`)?`
|
|
8
8
|
`+vo(n,e):(t.endsWith(" ")?"":" ")+n;bi.indentComment=vo;bi.lineComment=Qh;bi.stringifyComment=Xh});var Il=E(er=>{"use strict";var Zh="flow",ko="block",Ci="quoted";function eg(t,e,n="flow",{indentAtStart:r,lineWidth:i=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return t;i<s&&(s=0);let c=Math.max(1+s,1+i-e.length);if(t.length<=c)return t;let l=[],u={},d=i-e.length;typeof r=="number"&&(r>i-Math.max(2,s)?l.push(0):d=i-r);let f,p,g=!1,m=-1,h=-1,v=-1;n===ko&&(m=jl(t,m,e.length),m!==-1&&(d=m+c));for(let S;S=t[m+=1];){if(n===Ci&&S==="\\"){switch(h=m,t[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}v=m}if(S===`
|
|
@@ -11,65 +11,65 @@ var oh=Object.create;var no=Object.defineProperty;var ah=Object.getOwnPropertyDe
|
|
|
11
11
|
`&&b!==" "&&(f=m)}if(m>=d)if(f)l.push(f),d=f+c,f=void 0;else if(n===Ci){for(;p===" "||p===" ";)p=S,S=t[m+=1],g=!0;let b=m>v+1?m-2:h-1;if(u[b])return t;l.push(b),u[b]=!0,d=b+c,f=void 0}else g=!0}p=S}if(g&&a&&a(),l.length===0)return t;o&&o();let y=t.slice(0,l[0]);for(let S=0;S<l.length;++S){let b=l[S],x=l[S+1]||t.length;b===0?y=`
|
|
12
12
|
${e}${t.slice(0,x)}`:(n===Ci&&u[b]&&(y+=`${t[b]}\\`),y+=`
|
|
13
13
|
${e}${t.slice(b+1,x)}`)}return y}function jl(t,e,n){let r=e,i=e+1,s=t[i];for(;s===" "||s===" ";)if(e<i+n)s=t[++e];else{do s=t[++e];while(s&&s!==`
|
|
14
|
-
`);r=e,i=e+1,s=t[i]}return r}er.FOLD_BLOCK=ko;er.FOLD_FLOW=Zh;er.FOLD_QUOTED=Ci;er.foldFlowLines=eg});var nr=E($l=>{"use strict";var
|
|
14
|
+
`);r=e,i=e+1,s=t[i]}return r}er.FOLD_BLOCK=ko;er.FOLD_FLOW=Zh;er.FOLD_QUOTED=Ci;er.foldFlowLines=eg});var nr=E($l=>{"use strict";var Be=Z(),kt=Il(),Ei=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),xi=t=>/^(%|---|\.\.\.)/m.test(t);function tg(t,e,n){if(!e||e<0)return!1;let r=e-n,i=t.length;if(i<=r)return!1;for(let s=0,o=0;s<i;++s)if(t[s]===`
|
|
15
15
|
`){if(s-o>r)return!0;if(o=s+1,i-o<=r)return!1}return!0}function tr(t,e){let n=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=e,i=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(xi(t)?" ":""),o="",a=0;for(let c=0,l=n[c];l;l=n[++c])if(l===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(o+=n.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(n[c+1]){case"u":{o+=n.slice(a,c);let u=n.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(r||n[c+2]==='"'||n.length<i)c+=1;else{for(o+=n.slice(a,c)+`
|
|
16
16
|
|
|
17
17
|
`;n[c+2]==="\\"&&n[c+3]==="n"&&n[c+4]!=='"';)o+=`
|
|
18
|
-
`,c+=2;o+=s,n[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+n.slice(a):n,r?o:
|
|
18
|
+
`,c+=2;o+=s,n[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+n.slice(a):n,r?o:kt.foldFlowLines(o,s,kt.FOLD_QUOTED,Ei(e,!1))}function bo(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`
|
|
19
19
|
`)||/[ \t]\n|\n[ \t]/.test(t))return tr(t,e);let n=e.indent||(xi(t)?" ":""),r="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
-
${n}`)+"'";return e.implicitKey?r:
|
|
20
|
+
${n}`)+"'";return e.implicitKey?r:kt.foldFlowLines(r,n,kt.FOLD_FLOW,Ei(e,!1))}function _n(t,e){let{singleQuote:n}=e.options,r;if(n===!1)r=tr;else{let i=t.includes('"'),s=t.includes("'");i&&!s?r=bo:s&&!i?r=tr:r=n?bo:tr}return r(t,e)}var Co;try{Co=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{Co=/\n+(?!\n|$)/g}function Si({comment:t,type:e,value:n},r,i,s){let{blockQuote:o,commentString:a,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n))return _n(n,r);let l=r.indent||(r.forceBlockIndent||xi(n)?" ":""),u=o==="literal"?!0:o==="folded"||e===
|
|
23
|
+
|$)`,"g")}catch{Co=/\n+(?!\n|$)/g}function Si({comment:t,type:e,value:n},r,i,s){let{blockQuote:o,commentString:a,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n))return _n(n,r);let l=r.indent||(r.forceBlockIndent||xi(n)?" ":""),u=o==="literal"?!0:o==="folded"||e===Be.Scalar.BLOCK_FOLDED?!1:e===Be.Scalar.BLOCK_LITERAL?!0:!tg(n,c,l.length);if(!n)return u?`|
|
|
24
24
|
`:`>
|
|
25
25
|
`;let d,f;for(f=n.length;f>0;--f){let x=n[f-1];if(x!==`
|
|
26
26
|
`&&x!==" "&&x!==" ")break}let p=n.substring(f),g=p.indexOf(`
|
|
27
27
|
`);g===-1?d="-":n===p||g!==p.length-1?(d="+",s&&s()):d="",p&&(n=n.slice(0,-p.length),p[p.length-1]===`
|
|
28
28
|
`&&(p=p.slice(0,-1)),p=p.replace(Co,`$&${l}`));let m=!1,h,v=-1;for(h=0;h<n.length;++h){let x=n[h];if(x===" ")m=!0;else if(x===`
|
|
29
29
|
`)v=h;else break}let y=n.substring(0,v<h?v+1:h);y&&(n=n.substring(y.length),y=y.replace(/\n+/g,`$&${l}`));let b=(m?l?"2":"1":"")+d;if(t&&(b+=" "+a(t.replace(/ ?[\r\n]+/g," ")),i&&i()),!u){let x=n.replace(/\n+/g,`
|
|
30
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),w=!1,C=Ei(r,!0);o!=="folded"&&e!==
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),w=!1,C=Ei(r,!0);o!=="folded"&&e!==Be.Scalar.BLOCK_FOLDED&&(C.onOverflow=()=>{w=!0});let k=kt.foldFlowLines(`${y}${x}${p}`,l,kt.FOLD_BLOCK,C);if(!w)return`>${b}
|
|
31
31
|
${l}${k}`}return n=n.replace(/\n+/g,`$&${l}`),`|${b}
|
|
32
32
|
${l}${y}${n}${p}`}function ng(t,e,n,r){let{type:i,value:s}=t,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=e;if(a&&s.includes(`
|
|
33
33
|
`)||u&&/[[\]{},]/.test(s))return _n(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||u||!s.includes(`
|
|
34
|
-
`)?_n(s,e):Si(t,e,n,r);if(!a&&!u&&i!==
|
|
34
|
+
`)?_n(s,e):Si(t,e,n,r);if(!a&&!u&&i!==Be.Scalar.PLAIN&&s.includes(`
|
|
35
35
|
`))return Si(t,e,n,r);if(xi(s)){if(c==="")return e.forceBlockIndent=!0,Si(t,e,n,r);if(a&&c===l)return _n(s,e)}let d=s.replace(/\n+/g,`$&
|
|
36
|
-
${c}`);if(o){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(d),{compat:p,tags:g}=e.doc.schema;if(g.some(f)||p?.some(f))return _n(s,e)}return a?d:
|
|
37
|
-
${e.indent}${a}`:a}So.createStringifyContext=ag;So.stringify=ug});var Ml=E(ql=>{"use strict";var
|
|
38
|
-
${a}:`):(h=`${h}:`,f&&(h+=ir.lineComment(h,n.indent,l(f))));let v,y,S;
|
|
36
|
+
${c}`);if(o){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(d),{compat:p,tags:g}=e.doc.schema;if(g.some(f)||p?.some(f))return _n(s,e)}return a?d:kt.foldFlowLines(d,c,kt.FOLD_FLOW,Ei(e,!1))}function rg(t,e,n,r){let{implicitKey:i,inFlow:s}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:a}=t;a!==Be.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Be.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Be.Scalar.BLOCK_FOLDED:case Be.Scalar.BLOCK_LITERAL:return i||s?_n(o.value,e):Si(o,e,n,r);case Be.Scalar.QUOTE_DOUBLE:return tr(o.value,e);case Be.Scalar.QUOTE_SINGLE:return bo(o.value,e);case Be.Scalar.PLAIN:return ng(o,e,n,r);default:return null}},l=c(a);if(l===null){let{defaultKeyType:u,defaultStringType:d}=e.options,f=i&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}$l.stringifyString=rg});var rr=E(So=>{"use strict";var ig=gi(),bt=D(),sg=Zn(),og=nr();function ag(t,e){let n=Object.assign({blockQuote:!0,commentString:sg.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},t.schema.toStringOptions,e),r;switch(n.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:t,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:r,options:n}}function cg(t,e){if(e.tag){let i=t.filter(s=>s.tag===e.tag);if(i.length>0)return i.find(s=>s.format===e.format)??i[0]}let n,r;if(bt.isScalar(e)){r=e.value;let i=t.filter(s=>s.identify?.(r));if(i.length>1){let s=i.filter(o=>o.test);s.length>0&&(i=s)}n=i.find(s=>s.format===e.format)??i.find(s=>!s.format)}else r=e,n=t.find(i=>i.nodeClass&&r instanceof i.nodeClass);if(!n){let i=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${i} value`)}return n}function lg(t,e,{anchors:n,doc:r}){if(!r.directives)return"";let i=[],s=(bt.isScalar(t)||bt.isCollection(t))&&t.anchor;s&&ig.anchorIsValid(s)&&(n.add(s),i.push(`&${s}`));let o=t.tag??(e.default?null:e.tag);return o&&i.push(r.directives.tagString(o)),i.join(" ")}function ug(t,e,n,r){if(bt.isPair(t))return t.toString(e,n,r);if(bt.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let i,s=bt.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>i=c});i??(i=cg(e.doc.schema.tags,s));let o=lg(s,i,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof i.stringify=="function"?i.stringify(s,e,n,r):bt.isScalar(s)?og.stringifyString(s,e,n,r):s.toString(e,n,r);return o?bt.isScalar(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
|
|
37
|
+
${e.indent}${a}`:a}So.createStringifyContext=ag;So.stringify=ug});var Ml=E(ql=>{"use strict";var ct=D(),Tl=Z(),Ll=rr(),ir=Zn();function dg({key:t,value:e},n,r,i){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n,f=ct.isNode(t)&&t.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(ct.isCollection(t)||!ct.isNode(t)&&typeof t=="object"){let C="With simple keys, collection cannot be used as a key value";throw new Error(C)}}let p=!d&&(!t||f&&e==null&&!n.inFlow||ct.isCollection(t)||(ct.isScalar(t)?t.type===Tl.Scalar.BLOCK_FOLDED||t.type===Tl.Scalar.BLOCK_LITERAL:typeof t=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!s),indent:a+c});let g=!1,m=!1,h=Ll.stringify(t,n,()=>g=!0,()=>m=!0);if(!p&&!n.inFlow&&h.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(n.inFlow){if(s||e==null)return g&&r&&r(),h===""?"?":p?`? ${h}`:h}else if(s&&!d||e==null&&p)return h=`? ${h}`,f&&!g?h+=ir.lineComment(h,n.indent,l(f)):m&&i&&i(),h;g&&(f=null),p?(f&&(h+=ir.lineComment(h,n.indent,l(f))),h=`? ${h}
|
|
38
|
+
${a}:`):(h=`${h}:`,f&&(h+=ir.lineComment(h,n.indent,l(f))));let v,y,S;ct.isNode(e)?(v=!!e.spaceBefore,y=e.commentBefore,S=e.comment):(v=!1,y=null,S=null,e&&typeof e=="object"&&(e=o.createNode(e))),n.implicitKey=!1,!p&&!f&&ct.isScalar(e)&&(n.indentAtStart=h.length+1),m=!1,!u&&c.length>=2&&!n.inFlow&&!p&&ct.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(n.indent=n.indent.substring(2));let b=!1,x=Ll.stringify(e,n,()=>b=!0,()=>m=!0),w=" ";if(f||v||y){if(w=v?`
|
|
39
39
|
`:"",y){let C=l(y);w+=`
|
|
40
40
|
${ir.indentComment(C,n.indent)}`}x===""&&!n.inFlow?w===`
|
|
41
41
|
`&&S&&(w=`
|
|
42
42
|
|
|
43
43
|
`):w+=`
|
|
44
|
-
${n.indent}`}else if(!p&&
|
|
44
|
+
${n.indent}`}else if(!p&&ct.isCollection(e)){let C=x[0],k=x.indexOf(`
|
|
45
45
|
`),_=k!==-1,P=n.inFlow??e.flow??e.items.length===0;if(_||!P){let O=!1;if(_&&(C==="&"||C==="!")){let R=x.indexOf(" ");C==="&"&&R!==-1&&R<k&&x[R+1]==="!"&&(R=x.indexOf(" ",R+1)),(R===-1||k<R)&&(O=!0)}O||(w=`
|
|
46
46
|
${n.indent}`)}}else(x===""||x[0]===`
|
|
47
|
-
`)&&(w="");return h+=w+x,n.inFlow?b&&r&&r():S&&!b?h+=ir.lineComment(h,n.indent,l(S)):m&&i&&i(),h}ql.stringifyPair=dg});var xo=E(Eo=>{"use strict";var Fl=oi("process");function fg(t,...e){t==="debug"&&console.log(...e)}function mg(t,e){(t==="debug"||t==="warn")&&(typeof Fl.emitWarning=="function"?Fl.emitWarning(e):console.warn(e))}Eo.debug=fg;Eo.warn=mg});var Oi=E(Ai=>{"use strict";var Pi=D(),Dl=
|
|
47
|
+
`)&&(w="");return h+=w+x,n.inFlow?b&&r&&r():S&&!b?h+=ir.lineComment(h,n.indent,l(S)):m&&i&&i(),h}ql.stringifyPair=dg});var xo=E(Eo=>{"use strict";var Fl=oi("process");function fg(t,...e){t==="debug"&&console.log(...e)}function mg(t,e){(t==="debug"||t==="warn")&&(typeof Fl.emitWarning=="function"?Fl.emitWarning(e):console.warn(e))}Eo.debug=fg;Eo.warn=mg});var Oi=E(Ai=>{"use strict";var Pi=D(),Dl=Z(),_i="<<",Ri={identify:t=>t===_i||typeof t=="symbol"&&t.description===_i,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Dl.Scalar(Symbol(_i)),{addToJSMap:Wl}),stringify:()=>_i},pg=(t,e)=>(Ri.identify(e)||Pi.isScalar(e)&&(!e.type||e.type===Dl.Scalar.PLAIN)&&Ri.identify(e.value))&&t?.doc.schema.tags.some(n=>n.tag===Ri.tag&&n.default);function Wl(t,e,n){let r=Bl(t,n);if(Pi.isSeq(r))for(let i of r.items)_o(t,e,i);else if(Array.isArray(r))for(let i of r)_o(t,e,i);else _o(t,e,r)}function _o(t,e,n){let r=Bl(t,n);if(!Pi.isMap(r))throw new Error("Merge sources must be maps or map aliases");let i=r.toJSON(null,t,Map);for(let[s,o]of i)e instanceof Map?e.has(s)||e.set(s,o):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function Bl(t,e){return t&&Pi.isAlias(e)?e.resolve(t.doc,t):e}Ai.addMergeToJSMap=Wl;Ai.isMergeKey=pg;Ai.merge=Ri});var Po=E(Hl=>{"use strict";var hg=xo(),Ul=Oi(),gg=rr(),Kl=D(),Ro=yt();function wg(t,e,{key:n,value:r}){if(Kl.isNode(n)&&n.addToJSMap)n.addToJSMap(t,e,r);else if(Ul.isMergeKey(t,n))Ul.addMergeToJSMap(t,e,r);else{let i=Ro.toJS(n,"",t);if(e instanceof Map)e.set(i,Ro.toJS(r,i,t));else if(e instanceof Set)e.add(i);else{let s=yg(n,i,t),o=Ro.toJS(r,s,t);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function yg(t,e,n){if(e===null)return"";if(typeof e!="object")return String(e);if(Kl.isNode(t)&&n?.doc){let r=gg.createStringifyContext(n.doc,{});r.anchors=new Set;for(let s of n.anchors.keys())r.anchors.add(s.anchor);r.inFlow=!0,r.inStringifyKey=!0;let i=t.toString(r);if(!n.mapKeyWarned){let s=JSON.stringify(i);s.length>40&&(s=s.substring(0,36)+'..."'),hg.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return i}return JSON.stringify(e)}Hl.addPairToJSMap=wg});var Ct=E(Ao=>{"use strict";var zl=Qn(),vg=Ml(),kg=Po(),Ni=D();function bg(t,e,n){let r=zl.createNode(t,void 0,n),i=zl.createNode(e,void 0,n);return new ji(r,i)}var ji=class t{constructor(e,n=null){Object.defineProperty(this,Ni.NODE_TYPE,{value:Ni.PAIR}),this.key=e,this.value=n}clone(e){let{key:n,value:r}=this;return Ni.isNode(n)&&(n=n.clone(e)),Ni.isNode(r)&&(r=r.clone(e)),new t(n,r)}toJSON(e,n){let r=n?.mapAsMap?new Map:{};return kg.addPairToJSMap(n,r,this)}toString(e,n,r){return e?.doc?vg.stringifyPair(this,e,n,r):JSON.stringify(this)}};Ao.Pair=ji;Ao.createPair=bg});var Oo=E(Gl=>{"use strict";var en=D(),Jl=rr(),Ii=Zn();function Cg(t,e,n){return(e.inFlow??t.flow?Eg:Sg)(t,e,n)}function Sg({comment:t,items:e},n,{blockItemPrefix:r,flowChars:i,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:s,type:null}),d=!1,f=[];for(let g=0;g<e.length;++g){let m=e[g],h=null;if(en.isNode(m))!d&&m.spaceBefore&&f.push(""),$i(n,f,m.commentBefore,d),m.comment&&(h=m.comment);else if(en.isPair(m)){let y=en.isNode(m.key)?m.key:null;y&&(!d&&y.spaceBefore&&f.push(""),$i(n,f,y.commentBefore,d))}d=!1;let v=Jl.stringify(m,u,()=>h=null,()=>d=!0);h&&(v+=Ii.lineComment(v,s,l(h))),d&&h&&(d=!1),f.push(r+v)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let g=1;g<f.length;++g){let m=f[g];p+=m?`
|
|
48
48
|
${c}${m}`:`
|
|
49
49
|
`}}return t?(p+=`
|
|
50
50
|
`+Ii.indentComment(l(t),c),a&&a()):d&&o&&o(),p}function Eg({items:t},e,{flowChars:n,itemIndent:r}){let{indent:i,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=e;r+=s;let c=Object.assign({},e,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let g=0;g<t.length;++g){let m=t[g],h=null;if(en.isNode(m))m.spaceBefore&&d.push(""),$i(e,d,m.commentBefore,!1),m.comment&&(h=m.comment);else if(en.isPair(m)){let y=en.isNode(m.key)?m.key:null;y&&(y.spaceBefore&&d.push(""),$i(e,d,y.commentBefore,!1),y.comment&&(l=!0));let S=en.isNode(m.value)?m.value:null;S?(S.comment&&(h=S.comment),S.commentBefore&&(l=!0)):m.value==null&&y?.comment&&(h=y.comment)}h&&(l=!0);let v=Jl.stringify(m,c,()=>h=null);l||(l=d.length>u||v.includes(`
|
|
51
51
|
`)),g<t.length-1?v+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(l||(l=d.reduce((y,S)=>y+S.length+2,2)+(v.length+2)>e.options.lineWidth)),l&&(v+=",")),h&&(v+=Ii.lineComment(v,r,a(h))),d.push(v),u=d.length}let{start:f,end:p}=n;if(d.length===0)return f+p;if(!l){let g=d.reduce((m,h)=>m+h.length+2,2);l=e.options.lineWidth>0&&g>e.options.lineWidth}if(l){let g=f;for(let m of d)g+=m?`
|
|
52
52
|
${s}${i}${m}`:`
|
|
53
53
|
`;return`${g}
|
|
54
|
-
${i}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function $i({indent:t,options:{commentString:e}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,"")),r){let s=Ii.indentComment(e(r),t);n.push(s.trimStart())}}Gl.stringifyCollection=Cg});var
|
|
55
|
-
`:" ")}return aw.stringifyString({comment:t,type:e,value:a},r,i,s)}};pu.binary=cw});var Hi=E(Ki=>{"use strict";var Ui=D(),Uo=
|
|
54
|
+
${i}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function $i({indent:t,options:{commentString:e}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,"")),r){let s=Ii.indentComment(e(r),t);n.push(s.trimStart())}}Gl.stringifyCollection=Cg});var Et=E(jo=>{"use strict";var xg=Oo(),_g=Po(),Rg=ki(),St=D(),Ti=Ct(),Pg=Z();function sr(t,e){let n=St.isScalar(e)?e.value:e;for(let r of t)if(St.isPair(r)&&(r.key===e||r.key===n||St.isScalar(r.key)&&r.key.value===n))return r}var No=class extends Rg.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(St.MAP,e),this.items=[]}static from(e,n,r){let{keepUndefined:i,replacer:s}=r,o=new this(e),a=(c,l)=>{if(typeof s=="function")l=s.call(n,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||i)&&o.items.push(Ti.createPair(c,l,r))};if(n instanceof Map)for(let[c,l]of n)a(c,l);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,n){let r;St.isPair(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new Ti.Pair(e,e?.value):r=new Ti.Pair(e.key,e.value);let i=sr(this.items,r.key),s=this.schema?.sortMapEntries;if(i){if(!n)throw new Error(`Key ${r.key} already set`);St.isScalar(i.value)&&Pg.isScalarValue(r.value)?i.value.value=r.value:i.value=r.value}else if(s){let o=this.items.findIndex(a=>s(r,a)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(e){let n=sr(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){let i=sr(this.items,e)?.value;return(!n&&St.isScalar(i)?i.value:i)??void 0}has(e){return!!sr(this.items,e)}set(e,n){this.add(new Ti.Pair(e,n),!0)}toJSON(e,n,r){let i=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(i);for(let s of this.items)_g.addPairToJSMap(n,i,s);return i}toString(e,n,r){if(!e)return JSON.stringify(this);for(let i of this.items)if(!St.isPair(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),xg.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:n})}};jo.YAMLMap=No;jo.findPair=sr});var Rn=E(Vl=>{"use strict";var Ag=D(),Yl=Et(),Og={collection:"map",default:!0,nodeClass:Yl.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return Ag.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,n)=>Yl.YAMLMap.from(t,e,n)};Vl.map=Og});var xt=E(Xl=>{"use strict";var Ng=Qn(),jg=Oo(),Ig=ki(),qi=D(),$g=Z(),Tg=yt(),Io=class extends Ig.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(qi.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let n=Li(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){let r=Li(e);if(typeof r!="number")return;let i=this.items[r];return!n&&qi.isScalar(i)?i.value:i}has(e){let n=Li(e);return typeof n=="number"&&n<this.items.length}set(e,n){let r=Li(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);let i=this.items[r];qi.isScalar(i)&&$g.isScalarValue(n)?i.value=n:this.items[r]=n}toJSON(e,n){let r=[];n?.onCreate&&n.onCreate(r);let i=0;for(let s of this.items)r.push(Tg.toJS(s,String(i++),n));return r}toString(e,n,r){return e?jg.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:r,onComment:n}):JSON.stringify(this)}static from(e,n,r){let{replacer:i}=r,s=new this(e);if(n&&Symbol.iterator in Object(n)){let o=0;for(let a of n){if(typeof i=="function"){let c=n instanceof Set?a:String(o++);a=i.call(n,c,a)}s.items.push(Ng.createNode(a,void 0,r))}}return s}};function Li(t){let e=qi.isScalar(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}Xl.YAMLSeq=Io});var Pn=E(Zl=>{"use strict";var Lg=D(),Ql=xt(),qg={collection:"seq",default:!0,nodeClass:Ql.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return Lg.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,n)=>Ql.YAMLSeq.from(t,e,n)};Zl.seq=qg});var or=E(eu=>{"use strict";var Mg=nr(),Fg={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,n,r){return e=Object.assign({actualString:!0},e),Mg.stringifyString(t,e,n,r)}};eu.string=Fg});var Mi=E(ru=>{"use strict";var tu=Z(),nu={identify:t=>t==null,createNode:()=>new tu.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new tu.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&nu.test.test(t)?t:e.options.nullStr};ru.nullTag=nu});var $o=E(su=>{"use strict";var Dg=Z(),iu={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new Dg.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},n){if(t&&iu.test.test(t)){let r=t[0]==="t"||t[0]==="T";if(e===r)return t}return e?n.options.trueStr:n.options.falseStr}};su.boolTag=iu});var An=E(ou=>{"use strict";function Wg({format:t,minFractionDigits:e,tag:n,value:r}){if(typeof r=="bigint")return String(r);let i=typeof r=="number"?r:Number(r);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let s=Object.is(r,-0)?"-0":JSON.stringify(r);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=e-(s.length-o-1);for(;a-- >0;)s+="0"}return s}ou.stringifyNumber=Wg});var Lo=E(Fi=>{"use strict";var Bg=Z(),To=An(),Ug={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:To.stringifyNumber},Kg={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():To.stringifyNumber(t)}},Hg={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new Bg.Scalar(parseFloat(t)),n=t.indexOf(".");return n!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-n-1),e},stringify:To.stringifyNumber};Fi.float=Hg;Fi.floatExp=Kg;Fi.floatNaN=Ug});var Mo=E(Wi=>{"use strict";var au=An(),Di=t=>typeof t=="bigint"||Number.isInteger(t),qo=(t,e,n,{intAsBigInt:r})=>r?BigInt(t):parseInt(t.substring(e),n);function cu(t,e,n){let{value:r}=t;return Di(r)&&r>=0?n+r.toString(e):au.stringifyNumber(t)}var zg={identify:t=>Di(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,n)=>qo(t,2,8,n),stringify:t=>cu(t,8,"0o")},Jg={identify:Di,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,n)=>qo(t,0,10,n),stringify:au.stringifyNumber},Gg={identify:t=>Di(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,n)=>qo(t,2,16,n),stringify:t=>cu(t,16,"0x")};Wi.int=Jg;Wi.intHex=Gg;Wi.intOct=zg});var uu=E(lu=>{"use strict";var Yg=Rn(),Vg=Mi(),Xg=Pn(),Qg=or(),Zg=$o(),Fo=Lo(),Do=Mo(),ew=[Yg.map,Xg.seq,Qg.string,Vg.nullTag,Zg.boolTag,Do.intOct,Do.int,Do.intHex,Fo.floatNaN,Fo.floatExp,Fo.float];lu.schema=ew});var mu=E(fu=>{"use strict";var tw=Z(),nw=Rn(),rw=Pn();function du(t){return typeof t=="bigint"||Number.isInteger(t)}var Bi=({value:t})=>JSON.stringify(t),iw=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:Bi},{identify:t=>t==null,createNode:()=>new tw.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Bi},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:Bi},{identify:du,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:n})=>n?BigInt(t):parseInt(t,10),stringify:({value:t})=>du(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:Bi}],sw={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},ow=[nw.map,rw.seq].concat(iw,sw);fu.schema=ow});var Bo=E(pu=>{"use strict";var ar=oi("buffer"),Wo=Z(),aw=nr(),cw={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof ar.Buffer=="function")return ar.Buffer.from(t,"base64");if(typeof atob=="function"){let n=atob(t.replace(/[\n\r]/g,"")),r=new Uint8Array(n.length);for(let i=0;i<n.length;++i)r[i]=n.charCodeAt(i);return r}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:n},r,i,s){if(!n)return"";let o=n,a;if(typeof ar.Buffer=="function")a=o instanceof ar.Buffer?o.toString("base64"):ar.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=Wo.Scalar.BLOCK_LITERAL),e!==Wo.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(a.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=a.substr(f,c);a=u.join(e===Wo.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return aw.stringifyString({comment:t,type:e,value:a},r,i,s)}};pu.binary=cw});var Hi=E(Ki=>{"use strict";var Ui=D(),Uo=Ct(),lw=Z(),uw=xt();function hu(t,e){if(Ui.isSeq(t))for(let n=0;n<t.items.length;++n){let r=t.items[n];if(!Ui.isPair(r)){if(Ui.isMap(r)){r.items.length>1&&e("Each pair must have its own sequence indicator");let i=r.items[0]||new Uo.Pair(new lw.Scalar(null));if(r.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${r.commentBefore}
|
|
56
56
|
${i.key.commentBefore}`:r.commentBefore),r.comment){let s=i.value??i.key;s.comment=s.comment?`${r.comment}
|
|
57
|
-
${s.comment}`:r.comment}r=i}t.items[n]=Ui.isPair(r)?r:new Uo.Pair(r)}}else e("Expected a sequence for this tag");return t}function gu(t,e,n){let{replacer:r}=n,i=new uw.YAMLSeq(t);i.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof r=="function"&&(o=r.call(e,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;i.items.push(Uo.createPair(a,c,n))}return i}var dw={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:hu,createNode:gu};Ki.createPairs=gu;Ki.pairs=dw;Ki.resolvePairs=hu});var zo=E(Ho=>{"use strict";var wu=D(),Ko=wt(),cr=St(),fw=Et(),yu=Hi(),tn=class t extends fw.YAMLSeq{constructor(){super(),this.add=cr.YAMLMap.prototype.add.bind(this),this.delete=cr.YAMLMap.prototype.delete.bind(this),this.get=cr.YAMLMap.prototype.get.bind(this),this.has=cr.YAMLMap.prototype.has.bind(this),this.set=cr.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let r=new Map;n?.onCreate&&n.onCreate(r);for(let i of this.items){let s,o;if(wu.isPair(i)?(s=Ko.toJS(i.key,"",n),o=Ko.toJS(i.value,s,n)):s=Ko.toJS(i,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,o)}return r}static from(e,n,r){let i=yu.createPairs(e,n,r),s=new this;return s.items=i.items,s}};tn.tag="tag:yaml.org,2002:omap";var mw={collection:"seq",identify:t=>t instanceof Map,nodeClass:tn,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=yu.resolvePairs(t,e),r=[];for(let{key:i}of n.items)wu.isScalar(i)&&(r.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):r.push(i.value));return Object.assign(new tn,n)},createNode:(t,e,n)=>tn.from(t,e,n)};Ho.YAMLOMap=tn;Ho.omap=mw});var Su=E(Jo=>{"use strict";var vu=ee();function ku({value:t,source:e},n){return e&&(t?bu:Cu).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var bu={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new vu.Scalar(!0),stringify:ku},Cu={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new vu.Scalar(!1),stringify:ku};Jo.falseTag=Cu;Jo.trueTag=bu});var Eu=E(zi=>{"use strict";var pw=ee(),Go=An(),hw={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Go.stringifyNumber},gw={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Go.stringifyNumber(t)}},ww={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new pw.Scalar(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let r=t.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(e.minFractionDigits=r.length)}return e},stringify:Go.stringifyNumber};zi.float=ww;zi.floatExp=gw;zi.floatNaN=hw});var _u=E(ur=>{"use strict";var xu=An(),lr=t=>typeof t=="bigint"||Number.isInteger(t);function Ji(t,e,n,{intAsBigInt:r}){let i=t[0];if((i==="-"||i==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),r){switch(n){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return i==="-"?BigInt(-1)*o:o}let s=parseInt(t,n);return i==="-"?-1*s:s}function Yo(t,e,n){let{value:r}=t;if(lr(r)){let i=r.toString(e);return r<0?"-"+n+i.substr(1):n+i}return xu.stringifyNumber(t)}var yw={identify:lr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>Ji(t,2,2,n),stringify:t=>Yo(t,2,"0b")},vw={identify:lr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>Ji(t,1,8,n),stringify:t=>Yo(t,8,"0")},kw={identify:lr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>Ji(t,0,10,n),stringify:xu.stringifyNumber},bw={identify:lr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>Ji(t,2,16,n),stringify:t=>Yo(t,16,"0x")};ur.int=kw;ur.intBin=yw;ur.intHex=bw;ur.intOct=vw});var Xo=E(Vo=>{"use strict";var Vi=D(),Gi=bt(),Yi=St(),nn=class t extends Yi.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let n;Vi.isPair(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new Gi.Pair(e.key,null):n=new Gi.Pair(e,null),Yi.findPair(this.items,n.key)||this.items.push(n)}get(e,n){let r=Yi.findPair(this.items,e);return!n&&Vi.isPair(r)?Vi.isScalar(r.key)?r.key.value:r.key:r}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=Yi.findPair(this.items,e);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new Gi.Pair(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(e,n,r){let{replacer:i}=r,s=new this(e);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof i=="function"&&(o=i.call(n,o,o)),s.items.push(Gi.createPair(o,null,r));return s}};nn.tag="tag:yaml.org,2002:set";var Cw={collection:"map",identify:t=>t instanceof Set,nodeClass:nn,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>nn.from(t,e,n),resolve(t,e){if(Vi.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new nn,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};Vo.YAMLSet=nn;Vo.set=Cw});var Zo=E(Xi=>{"use strict";var Sw=An();function Qo(t,e){let n=t[0],r=n==="-"||n==="+"?t.substring(1):t,i=o=>e?BigInt(o):Number(o),s=r.replace(/_/g,"").split(":").reduce((o,a)=>o*i(60)+i(a),i(0));return n==="-"?i(-1)*s:s}function Ru(t){let{value:e}=t,n=o=>o;if(typeof e=="bigint")n=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Sw.stringifyNumber(t);let r="";e<0&&(r="-",e*=n(-1));let i=n(60),s=[e%i];return e<60?s.unshift(0):(e=(e-s[0])/i,s.unshift(e%i),e>=60&&(e=(e-s[0])/i,s.unshift(e))),r+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Ew={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>Qo(t,n),stringify:Ru},xw={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>Qo(t,!1),stringify:Ru},Pu={identify:t=>t 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(t){let e=t.match(Pu.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,i,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(n,r-1,i,s||0,o||0,a||0,c),u=e[8];if(u&&u!=="Z"){let d=Qo(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Xi.floatTime=xw;Xi.intTime=Ew;Xi.timestamp=Pu});var Nu=E(Ou=>{"use strict";var _w=Rn(),Rw=Mi(),Pw=Pn(),Aw=or(),Ow=Bo(),Au=Su(),ea=Eu(),Qi=_u(),Nw=Oi(),jw=zo(),Iw=Hi(),$w=Xo(),ta=Zo(),Tw=[_w.map,Pw.seq,Aw.string,Rw.nullTag,Au.trueTag,Au.falseTag,Qi.intBin,Qi.intOct,Qi.int,Qi.intHex,ea.floatNaN,ea.floatExp,ea.float,Ow.binary,Nw.merge,jw.omap,Iw.pairs,$w.set,ta.intTime,ta.floatTime,ta.timestamp];Ou.schema=Tw});var Wu=E(ia=>{"use strict";var Tu=Rn(),Lw=Mi(),Lu=Pn(),qw=or(),Mw=$o(),na=Lo(),ra=Mo(),Fw=uu(),Dw=mu(),qu=Bo(),dr=Oi(),Mu=zo(),Fu=Hi(),ju=Nu(),Du=Xo(),Zi=Zo(),Iu=new Map([["core",Fw.schema],["failsafe",[Tu.map,Lu.seq,qw.string]],["json",Dw.schema],["yaml11",ju.schema],["yaml-1.1",ju.schema]]),$u={binary:qu.binary,bool:Mw.boolTag,float:na.float,floatExp:na.floatExp,floatNaN:na.floatNaN,floatTime:Zi.floatTime,int:ra.int,intHex:ra.intHex,intOct:ra.intOct,intTime:Zi.intTime,map:Tu.map,merge:dr.merge,null:Lw.nullTag,omap:Mu.omap,pairs:Fu.pairs,seq:Lu.seq,set:Du.set,timestamp:Zi.timestamp},Ww={"tag:yaml.org,2002:binary":qu.binary,"tag:yaml.org,2002:merge":dr.merge,"tag:yaml.org,2002:omap":Mu.omap,"tag:yaml.org,2002:pairs":Fu.pairs,"tag:yaml.org,2002:set":Du.set,"tag:yaml.org,2002:timestamp":Zi.timestamp};function Bw(t,e,n){let r=Iu.get(e);if(r&&!t)return n&&!r.includes(dr.merge)?r.concat(dr.merge):r.slice();let i=r;if(!i)if(Array.isArray(t))i=[];else{let s=Array.from(Iu.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(t))for(let s of t)i=i.concat(s);else typeof t=="function"&&(i=t(i.slice()));return n&&(i=i.concat(dr.merge)),i.reduce((s,o)=>{let a=typeof o=="string"?$u[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys($u).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}ia.coreKnownTags=Ww;ia.getTags=Bw});var aa=E(Bu=>{"use strict";var sa=D(),Uw=Rn(),Kw=Pn(),Hw=or(),es=Wu(),zw=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,oa=class t{constructor({compat:e,customTags:n,merge:r,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?es.getTags(e,"compat"):e?es.getTags(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?es.coreKnownTags:{},this.tags=es.getTags(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,sa.MAP,{value:Uw.map}),Object.defineProperty(this,sa.SCALAR,{value:Hw.string}),Object.defineProperty(this,sa.SEQ,{value:Kw.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?zw:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Bu.Schema=oa});var Ku=E(Uu=>{"use strict";var Jw=D(),ca=rr(),fr=Zn();function Gw(t,e){let n=[],r=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(n.push(c),r=!0):t.directives.docStart&&(r=!0)}r&&n.push("---");let i=ca.createStringifyContext(t,e),{commentString:s}=i.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(fr.indentComment(c,""))}let o=!1,a=null;if(t.contents){if(Jw.isNode(t.contents)){if(t.contents.spaceBefore&&r&&n.push(""),t.contents.commentBefore){let u=s(t.contents.commentBefore);n.push(fr.indentComment(u,""))}i.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>o=!0,l=ca.stringify(t.contents,i,()=>a=null,c);a&&(l+=fr.lineComment(l,"",s(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(ca.stringify(t.contents,i));if(t.directives?.docEnd)if(t.comment){let c=s(t.comment);c.includes(`
|
|
57
|
+
${s.comment}`:r.comment}r=i}t.items[n]=Ui.isPair(r)?r:new Uo.Pair(r)}}else e("Expected a sequence for this tag");return t}function gu(t,e,n){let{replacer:r}=n,i=new uw.YAMLSeq(t);i.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof r=="function"&&(o=r.call(e,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;i.items.push(Uo.createPair(a,c,n))}return i}var dw={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:hu,createNode:gu};Ki.createPairs=gu;Ki.pairs=dw;Ki.resolvePairs=hu});var zo=E(Ho=>{"use strict";var wu=D(),Ko=yt(),cr=Et(),fw=xt(),yu=Hi(),tn=class t extends fw.YAMLSeq{constructor(){super(),this.add=cr.YAMLMap.prototype.add.bind(this),this.delete=cr.YAMLMap.prototype.delete.bind(this),this.get=cr.YAMLMap.prototype.get.bind(this),this.has=cr.YAMLMap.prototype.has.bind(this),this.set=cr.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,n){if(!n)return super.toJSON(e);let r=new Map;n?.onCreate&&n.onCreate(r);for(let i of this.items){let s,o;if(wu.isPair(i)?(s=Ko.toJS(i.key,"",n),o=Ko.toJS(i.value,s,n)):s=Ko.toJS(i,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,o)}return r}static from(e,n,r){let i=yu.createPairs(e,n,r),s=new this;return s.items=i.items,s}};tn.tag="tag:yaml.org,2002:omap";var mw={collection:"seq",identify:t=>t instanceof Map,nodeClass:tn,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let n=yu.resolvePairs(t,e),r=[];for(let{key:i}of n.items)wu.isScalar(i)&&(r.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):r.push(i.value));return Object.assign(new tn,n)},createNode:(t,e,n)=>tn.from(t,e,n)};Ho.YAMLOMap=tn;Ho.omap=mw});var Su=E(Jo=>{"use strict";var vu=Z();function ku({value:t,source:e},n){return e&&(t?bu:Cu).test.test(e)?e:t?n.options.trueStr:n.options.falseStr}var bu={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new vu.Scalar(!0),stringify:ku},Cu={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new vu.Scalar(!1),stringify:ku};Jo.falseTag=Cu;Jo.trueTag=bu});var Eu=E(zi=>{"use strict";var pw=Z(),Go=An(),hw={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Go.stringifyNumber},gw={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Go.stringifyNumber(t)}},ww={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new pw.Scalar(parseFloat(t.replace(/_/g,""))),n=t.indexOf(".");if(n!==-1){let r=t.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(e.minFractionDigits=r.length)}return e},stringify:Go.stringifyNumber};zi.float=ww;zi.floatExp=gw;zi.floatNaN=hw});var _u=E(ur=>{"use strict";var xu=An(),lr=t=>typeof t=="bigint"||Number.isInteger(t);function Ji(t,e,n,{intAsBigInt:r}){let i=t[0];if((i==="-"||i==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),r){switch(n){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return i==="-"?BigInt(-1)*o:o}let s=parseInt(t,n);return i==="-"?-1*s:s}function Yo(t,e,n){let{value:r}=t;if(lr(r)){let i=r.toString(e);return r<0?"-"+n+i.substr(1):n+i}return xu.stringifyNumber(t)}var yw={identify:lr,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,n)=>Ji(t,2,2,n),stringify:t=>Yo(t,2,"0b")},vw={identify:lr,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,n)=>Ji(t,1,8,n),stringify:t=>Yo(t,8,"0")},kw={identify:lr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,n)=>Ji(t,0,10,n),stringify:xu.stringifyNumber},bw={identify:lr,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,n)=>Ji(t,2,16,n),stringify:t=>Yo(t,16,"0x")};ur.int=kw;ur.intBin=yw;ur.intHex=bw;ur.intOct=vw});var Xo=E(Vo=>{"use strict";var Vi=D(),Gi=Ct(),Yi=Et(),nn=class t extends Yi.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let n;Vi.isPair(e)?n=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?n=new Gi.Pair(e.key,null):n=new Gi.Pair(e,null),Yi.findPair(this.items,n.key)||this.items.push(n)}get(e,n){let r=Yi.findPair(this.items,e);return!n&&Vi.isPair(r)?Vi.isScalar(r.key)?r.key.value:r.key:r}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=Yi.findPair(this.items,e);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new Gi.Pair(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(e,n,r){let{replacer:i}=r,s=new this(e);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof i=="function"&&(o=i.call(n,o,o)),s.items.push(Gi.createPair(o,null,r));return s}};nn.tag="tag:yaml.org,2002:set";var Cw={collection:"map",identify:t=>t instanceof Set,nodeClass:nn,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,n)=>nn.from(t,e,n),resolve(t,e){if(Vi.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new nn,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};Vo.YAMLSet=nn;Vo.set=Cw});var Zo=E(Xi=>{"use strict";var Sw=An();function Qo(t,e){let n=t[0],r=n==="-"||n==="+"?t.substring(1):t,i=o=>e?BigInt(o):Number(o),s=r.replace(/_/g,"").split(":").reduce((o,a)=>o*i(60)+i(a),i(0));return n==="-"?i(-1)*s:s}function Ru(t){let{value:e}=t,n=o=>o;if(typeof e=="bigint")n=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Sw.stringifyNumber(t);let r="";e<0&&(r="-",e*=n(-1));let i=n(60),s=[e%i];return e<60?s.unshift(0):(e=(e-s[0])/i,s.unshift(e%i),e>=60&&(e=(e-s[0])/i,s.unshift(e))),r+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Ew={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:n})=>Qo(t,n),stringify:Ru},xw={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>Qo(t,!1),stringify:Ru},Pu={identify:t=>t 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(t){let e=t.match(Pu.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,i,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(n,r-1,i,s||0,o||0,a||0,c),u=e[8];if(u&&u!=="Z"){let d=Qo(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Xi.floatTime=xw;Xi.intTime=Ew;Xi.timestamp=Pu});var Nu=E(Ou=>{"use strict";var _w=Rn(),Rw=Mi(),Pw=Pn(),Aw=or(),Ow=Bo(),Au=Su(),ea=Eu(),Qi=_u(),Nw=Oi(),jw=zo(),Iw=Hi(),$w=Xo(),ta=Zo(),Tw=[_w.map,Pw.seq,Aw.string,Rw.nullTag,Au.trueTag,Au.falseTag,Qi.intBin,Qi.intOct,Qi.int,Qi.intHex,ea.floatNaN,ea.floatExp,ea.float,Ow.binary,Nw.merge,jw.omap,Iw.pairs,$w.set,ta.intTime,ta.floatTime,ta.timestamp];Ou.schema=Tw});var Wu=E(ia=>{"use strict";var Tu=Rn(),Lw=Mi(),Lu=Pn(),qw=or(),Mw=$o(),na=Lo(),ra=Mo(),Fw=uu(),Dw=mu(),qu=Bo(),dr=Oi(),Mu=zo(),Fu=Hi(),ju=Nu(),Du=Xo(),Zi=Zo(),Iu=new Map([["core",Fw.schema],["failsafe",[Tu.map,Lu.seq,qw.string]],["json",Dw.schema],["yaml11",ju.schema],["yaml-1.1",ju.schema]]),$u={binary:qu.binary,bool:Mw.boolTag,float:na.float,floatExp:na.floatExp,floatNaN:na.floatNaN,floatTime:Zi.floatTime,int:ra.int,intHex:ra.intHex,intOct:ra.intOct,intTime:Zi.intTime,map:Tu.map,merge:dr.merge,null:Lw.nullTag,omap:Mu.omap,pairs:Fu.pairs,seq:Lu.seq,set:Du.set,timestamp:Zi.timestamp},Ww={"tag:yaml.org,2002:binary":qu.binary,"tag:yaml.org,2002:merge":dr.merge,"tag:yaml.org,2002:omap":Mu.omap,"tag:yaml.org,2002:pairs":Fu.pairs,"tag:yaml.org,2002:set":Du.set,"tag:yaml.org,2002:timestamp":Zi.timestamp};function Bw(t,e,n){let r=Iu.get(e);if(r&&!t)return n&&!r.includes(dr.merge)?r.concat(dr.merge):r.slice();let i=r;if(!i)if(Array.isArray(t))i=[];else{let s=Array.from(Iu.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(t))for(let s of t)i=i.concat(s);else typeof t=="function"&&(i=t(i.slice()));return n&&(i=i.concat(dr.merge)),i.reduce((s,o)=>{let a=typeof o=="string"?$u[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys($u).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}ia.coreKnownTags=Ww;ia.getTags=Bw});var aa=E(Bu=>{"use strict";var sa=D(),Uw=Rn(),Kw=Pn(),Hw=or(),es=Wu(),zw=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,oa=class t{constructor({compat:e,customTags:n,merge:r,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?es.getTags(e,"compat"):e?es.getTags(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?es.coreKnownTags:{},this.tags=es.getTags(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,sa.MAP,{value:Uw.map}),Object.defineProperty(this,sa.SCALAR,{value:Hw.string}),Object.defineProperty(this,sa.SEQ,{value:Kw.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?zw:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Bu.Schema=oa});var Ku=E(Uu=>{"use strict";var Jw=D(),ca=rr(),fr=Zn();function Gw(t,e){let n=[],r=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(n.push(c),r=!0):t.directives.docStart&&(r=!0)}r&&n.push("---");let i=ca.createStringifyContext(t,e),{commentString:s}=i.options;if(t.commentBefore){n.length!==1&&n.unshift("");let c=s(t.commentBefore);n.unshift(fr.indentComment(c,""))}let o=!1,a=null;if(t.contents){if(Jw.isNode(t.contents)){if(t.contents.spaceBefore&&r&&n.push(""),t.contents.commentBefore){let u=s(t.contents.commentBefore);n.push(fr.indentComment(u,""))}i.forceBlockIndent=!!t.comment,a=t.contents.comment}let c=a?void 0:()=>o=!0,l=ca.stringify(t.contents,i,()=>a=null,c);a&&(l+=fr.lineComment(l,"",s(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(ca.stringify(t.contents,i));if(t.directives?.docEnd)if(t.comment){let c=s(t.comment);c.includes(`
|
|
58
58
|
`)?(n.push("..."),n.push(fr.indentComment(c,""))):n.push(`... ${c}`)}else n.push("...");else{let c=t.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&n[n.length-1]!==""&&n.push(""),n.push(fr.indentComment(s(c),"")))}return n.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}Uu.stringifyDocument=Gw});var mr=E(Hu=>{"use strict";var Yw=Xn(),On=ki()
|
|
60
|
+
`}Uu.stringifyDocument=Gw});var mr=E(Hu=>{"use strict";var Yw=Xn(),On=ki(),Le=D(),Vw=Ct(),Xw=yt(),Qw=aa(),Zw=Ku(),la=gi(),ey=mo(),ty=Qn(),ua=fo(),da=class t{constructor(e,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Le.NODE_TYPE,{value:Le.DOC});let i=null;typeof n=="function"||Array.isArray(n)?i=n:r===void 0&&n&&(r=n,n=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=s;let{version:o}=s;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new ua.Directives({version:o}),this.setSchema(o,r),this.contents=e===void 0?null:this.createNode(e,i,r)}clone(){let e=Object.create(t.prototype,{[Le.NODE_TYPE]:{value:Le.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=Le.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Nn(this.contents)&&this.contents.add(e)}addIn(e,n){Nn(this.contents)&&this.contents.addIn(e,n)}createAlias(e,n){if(!e.anchor){let r=la.anchorNames(this);e.anchor=!n||r.has(n)?la.findNewAnchor(n||"a",r):n}return new Yw.Alias(e.anchor)}createNode(e,n,r){let i;if(typeof n=="function")e=n.call({"":e},"",e),i=n;else if(Array.isArray(n)){let h=y=>typeof y=="number"||y instanceof String||y instanceof Number,v=n.filter(h).map(String);v.length>0&&(n=n.concat(v)),i=n}else r===void 0&&n&&(r=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:u}=r??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=la.createNodeAnchors(this,o||"a"),g={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:p},m=ty.createNode(e,u,g);return a&&Le.isCollection(m)&&(m.flow=!0),f(),m}createPair(e,n,r={}){let i=this.createNode(e,null,r),s=this.createNode(n,null,r);return new Vw.Pair(i,s)}delete(e){return Nn(this.contents)?this.contents.delete(e):!1}deleteIn(e){return On.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Nn(this.contents)?this.contents.deleteIn(e):!1}get(e,n){return Le.isCollection(this.contents)?this.contents.get(e,n):void 0}getIn(e,n){return On.isEmptyPath(e)?!n&&Le.isScalar(this.contents)?this.contents.value:this.contents:Le.isCollection(this.contents)?this.contents.getIn(e,n):void 0}has(e){return Le.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return On.isEmptyPath(e)?this.contents!==void 0:Le.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,n){this.contents==null?this.contents=On.collectionFromPath(this.schema,[e],n):Nn(this.contents)&&this.contents.set(e,n)}setIn(e,n){On.isEmptyPath(e)?this.contents=n:this.contents==null?this.contents=On.collectionFromPath(this.schema,Array.from(e),n):Nn(this.contents)&&this.contents.setIn(e,n)}setSchema(e,n={}){typeof e=="number"&&(e=String(e));let r;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new ua.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new ua.Directives({version:e}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let i=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(r)this.schema=new Qw.Schema(Object.assign(r,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:n,mapAsMap:r,maxAliasCount:i,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=Xw.toJS(this.contents,n??"",a);if(typeof s=="function")for(let{count:l,res:u}of a.anchors.values())s(u,l);return typeof o=="function"?ey.applyReviver(o,{"":c},"",c):c}toJSON(e,n){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:n})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let n=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return Zw.stringifyDocument(this,e)}};function Nn(t){if(Le.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}Hu.Document=da});var gr=E(hr=>{"use strict";var pr=class extends Error{constructor(e,n,r,i){super(),this.name=e,this.code=r,this.message=i,this.pos=n}},fa=class extends pr{constructor(e,n,r){super("YAMLParseError",e,n,r)}},ma=class extends pr{constructor(e,n,r){super("YAMLWarning",e,n,r)}},ny=(t,e)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>e.linePos(a));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let s=i-1,o=t.substring(e.lineStarts[r-1],e.lineStarts[r]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="…"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,s))){let a=t.substring(e.lineStarts[r-2],e.lineStarts[r-1]);a.length>80&&(a=a.substring(0,79)+`…
|
|
61
61
|
`),o=a+o}if(/[^ ]/.test(o)){let a=1,c=n.linePos[1];c?.line===r&&c.col>i&&(a=Math.max(1,Math.min(c.col-i,80-s)));let l=" ".repeat(s)+"^".repeat(a);n.message+=`:
|
|
62
62
|
|
|
63
63
|
${o}
|
|
64
64
|
${l}
|
|
65
65
|
`}};hr.YAMLError=pr;hr.YAMLParseError=fa;hr.YAMLWarning=ma;hr.prettifyError=ny});var wr=E(zu=>{"use strict";function ry(t,{flow:e,indicator:n,next:r,offset:i,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,u=a,d="",f="",p=!1,g=!1,m=null,h=null,v=null,y=null,S=null,b=null,x=null;for(let k of t)switch(g&&(k.type!=="space"&&k.type!=="newline"&&k.type!=="comma"&&s(k.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g=!1),m&&(l&&k.type!=="comment"&&k.type!=="newline"&&s(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),k.type){case"space":!e&&(n!=="doc-start"||r?.type!=="flow-collection")&&k.source.includes(" ")&&(m=k),u=!0;break;case"comment":{u||s(k,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let _=k.source.substring(1)||" ";d?d+=f+_:d=_,f="",l=!1;break}case"newline":l?d?d+=k.source:(!b||n!=="seq-item-ind")&&(c=!0):f+=k.source,l=!0,p=!0,(h||v)&&(y=k),u=!0;break;case"anchor":h&&s(k,"MULTIPLE_ANCHORS","A node can have at most one anchor"),k.source.endsWith(":")&&s(k.offset+k.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),h=k,x??(x=k.offset),l=!1,u=!1,g=!0;break;case"tag":{v&&s(k,"MULTIPLE_TAGS","A node can have at most one tag"),v=k,x??(x=k.offset),l=!1,u=!1,g=!0;break}case n:(h||v)&&s(k,"BAD_PROP_ORDER",`Anchors and tags must be after the ${k.source} indicator`),b&&s(k,"UNEXPECTED_TOKEN",`Unexpected ${k.source} in ${e??"collection"}`),b=k,l=n==="seq-item-ind"||n==="explicit-key-ind",u=!1;break;case"comma":if(e){S&&s(k,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),S=k,l=!1,u=!1;break}default:s(k,"UNEXPECTED_TOKEN",`Unexpected ${k.type} token`),l=!1,u=!1}let w=t[t.length-1],C=w?w.offset+w.source.length:i;return g&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&s(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(l&&m.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&s(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:S,found:b,spaceBefore:c,comment:d,hasNewline:p,anchor:h,tag:v,newlineAfterProp:y,end:C,start:x??C}}zu.resolveProps=ry});var ts=E(Ju=>{"use strict";function pa(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(`
|
|
66
|
-
`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(pa(e.key)||pa(e.value))return!0}return!1;default:return!0}}Ju.containsNewline=pa});var ha=E(Gu=>{"use strict";var iy=ts();function sy(t,e,n){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&&iy.containsNewline(e)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Gu.flowIndentCheck=sy});var ga=E(Vu=>{"use strict";var Yu=D();function oy(t,e,n){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let i=typeof r=="function"?r:(s,o)=>s===o||Yu.isScalar(s)&&Yu.isScalar(o)&&s.value===o.value;return e.some(s=>i(s.key,n))}Vu.mapIncludes=oy});var nd=E(td=>{"use strict";var Xu=
|
|
66
|
+
`))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let n of e.start)if(n.type==="newline")return!0;if(e.sep){for(let n of e.sep)if(n.type==="newline")return!0}if(pa(e.key)||pa(e.value))return!0}return!1;default:return!0}}Ju.containsNewline=pa});var ha=E(Gu=>{"use strict";var iy=ts();function sy(t,e,n){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===t&&(r.source==="]"||r.source==="}")&&iy.containsNewline(e)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Gu.flowIndentCheck=sy});var ga=E(Vu=>{"use strict";var Yu=D();function oy(t,e,n){let{uniqueKeys:r}=t.options;if(r===!1)return!1;let i=typeof r=="function"?r:(s,o)=>s===o||Yu.isScalar(s)&&Yu.isScalar(o)&&s.value===o.value;return e.some(s=>i(s.key,n))}Vu.mapIncludes=oy});var nd=E(td=>{"use strict";var Xu=Ct(),ay=Et(),Qu=wr(),cy=ts(),Zu=ha(),ly=ga(),ed="All mapping items must start at the same column";function uy({composeNode:t,composeEmptyNode:e},n,r,i,s){let o=s?.nodeClass??ay.YAMLMap,a=new o(n.schema);n.atRoot&&(n.atRoot=!1);let c=r.offset,l=null;for(let u of r.items){let{start:d,key:f,sep:p,value:g}=u,m=Qu.resolveProps(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:i,parentIndent:r.indent,startOnNewline:!0}),h=!m.found;if(h){if(f&&(f.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&i(c,"BAD_INDENT",ed)),!m.anchor&&!m.tag&&!p){l=m.end,m.comment&&(a.comment?a.comment+=`
|
|
67
67
|
`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||cy.containsNewline(f))&&i(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==r.indent&&i(c,"BAD_INDENT",ed);n.atKey=!0;let v=m.end,y=f?t(n,f,m,i):e(n,v,d,null,m,i);n.schema.compat&&Zu.flowIndentCheck(r.indent,f,i),n.atKey=!1,ly.mapIncludes(n,a.items,y)&&i(v,"DUPLICATE_KEY","Map keys must be unique");let S=Qu.resolveProps(p??[],{indicator:"map-value-ind",next:g,offset:y.range[2],onError:i,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=S.end,S.found){h&&(g?.type==="block-map"&&!S.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&m.start<S.found.offset-1024&&i(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let b=g?t(n,g,S,i):e(n,c,p,null,S,i);n.schema.compat&&Zu.flowIndentCheck(r.indent,g,i),c=b.range[2];let x=new Xu.Pair(y,b);n.options.keepSourceTokens&&(x.srcToken=u),a.items.push(x)}else{h&&i(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),S.comment&&(y.comment?y.comment+=`
|
|
68
|
-
`+S.comment:y.comment=S.comment);let b=new Xu.Pair(y);n.options.keepSourceTokens&&(b.srcToken=u),a.items.push(b)}}return l&&l<c&&i(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,c,l??c],a}td.resolveBlockMap=uy});var id=E(rd=>{"use strict";var dy=
|
|
68
|
+
`+S.comment:y.comment=S.comment);let b=new Xu.Pair(y);n.options.keepSourceTokens&&(b.srcToken=u),a.items.push(b)}}return l&&l<c&&i(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,c,l??c],a}td.resolveBlockMap=uy});var id=E(rd=>{"use strict";var dy=xt(),fy=wr(),my=ha();function py({composeNode:t,composeEmptyNode:e},n,r,i,s){let o=s?.nodeClass??dy.YAMLSeq,a=new o(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=r.offset,l=null;for(let{start:u,value:d}of r.items){let f=fy.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?i(f.end,"BAD_INDENT","All sequence items must start at the same column"):i(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(a.comment=f.comment);continue}let p=d?t(n,d,f,i):e(n,f.end,u,null,f,i);n.schema.compat&&my.flowIndentCheck(r.indent,d,i),c=p.range[2],a.items.push(p)}return a.range=[r.offset,c,l??c],a}rd.resolveBlockSeq=py});var jn=E(sd=>{"use strict";function hy(t,e,n,r){let i="";if(t){let s=!1,o="";for(let a of t){let{source:c,type:l}=a;switch(l){case"space":s=!0;break;case"comment":{n&&!s&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";i?i+=o+u:i=u,o="";break}case"newline":i&&(o+=c),s=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:i,offset:e}}sd.resolveEnd=hy});var ld=E(cd=>{"use strict";var gy=D(),wy=Ct(),od=Et(),yy=xt(),vy=jn(),ad=wr(),ky=ts(),by=ga(),wa="Block collections are not allowed within flow collections",ya=t=>t&&(t.type==="block-map"||t.type==="block-seq");function Cy({composeNode:t,composeEmptyNode:e},n,r,i,s){let o=r.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?od.YAMLMap:yy.YAMLSeq),l=new c(n.schema);l.flow=!0;let u=n.atRoot;u&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let d=r.offset+r.start.source.length;for(let h=0;h<r.items.length;++h){let v=r.items[h],{start:y,key:S,sep:b,value:x}=v,w=ad.resolveProps(y,{flow:a,indicator:"explicit-key-ind",next:S??b?.[0],offset:d,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!w.found){if(!w.anchor&&!w.tag&&!b&&!x){h===0&&w.comma?i(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):h<r.items.length-1&&i(w.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),w.comment&&(l.comment?l.comment+=`
|
|
69
69
|
`+w.comment:l.comment=w.comment),d=w.end;continue}!o&&n.options.strict&&ky.containsNewline(S)&&i(S,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(h===0)w.comma&&i(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(w.comma||i(w.start,"MISSING_CHAR",`Missing , between ${a} items`),w.comment){let C="";e:for(let k of y)switch(k.type){case"comma":case"space":break;case"comment":C=k.source.substring(1);break e;default:break e}if(C){let k=l.items[l.items.length-1];gy.isPair(k)&&(k=k.value??k.key),k.comment?k.comment+=`
|
|
70
70
|
`+C:k.comment=C,w.comment=w.comment.substring(C.length+1)}}if(!o&&!b&&!w.found){let C=x?t(n,x,w,i):e(n,w.end,b,null,w,i);l.items.push(C),d=C.range[2],ya(x)&&i(C.range,"BLOCK_IN_FLOW",wa)}else{n.atKey=!0;let C=w.end,k=S?t(n,S,w,i):e(n,C,y,null,w,i);ya(S)&&i(k.range,"BLOCK_IN_FLOW",wa),n.atKey=!1;let _=ad.resolveProps(b??[],{flow:a,indicator:"map-value-ind",next:x,offset:k.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(_.found){if(!o&&!w.found&&n.options.strict){if(b)for(let R of b){if(R===_.found)break;if(R.type==="newline"){i(R,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}w.start<_.found.offset-1024&&i(_.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else x&&("source"in x&&x.source?.[0]===":"?i(x,"MISSING_CHAR",`Missing space after : in ${a}`):i(_.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let P=x?t(n,x,_,i):_.found?e(n,_.end,b,null,_,i):null;P?ya(x)&&i(P.range,"BLOCK_IN_FLOW",wa):_.comment&&(k.comment?k.comment+=`
|
|
71
71
|
`+_.comment:k.comment=_.comment);let O=new wy.Pair(k,P);if(n.options.keepSourceTokens&&(O.srcToken=v),o){let R=l;by.mapIncludes(n,R.items,k)&&i(C,"DUPLICATE_KEY","Map keys must be unique"),R.items.push(O)}else{let R=new od.YAMLMap(n.schema);R.flow=!0,R.items.push(O);let $=(P??k).range;R.range=[k.range[0],$[1],$[2]],l.items.push(R)}d=P?P.range[2]:_.end}}let f=o?"}":"]",[p,...g]=r.end,m=d;if(p?.source===f)m=p.offset+p.source.length;else{let h=a[0].toUpperCase()+a.substring(1),v=u?`${h} must end with a ${f}`:`${h} in block collection must be sufficiently indented and end with a ${f}`;i(d,u?"MISSING_CHAR":"BAD_INDENT",v),p&&p.source.length!==1&&g.unshift(p)}if(g.length>0){let h=vy.resolveEnd(g,m,n.options.strict,i);h.comment&&(l.comment?l.comment+=`
|
|
72
|
-
`+h.comment:l.comment=h.comment),l.range=[r.offset,m,h.offset]}else l.range=[r.offset,m,m];return l}cd.resolveFlowCollection=Cy});var dd=E(ud=>{"use strict";var Sy=D(),Ey=
|
|
72
|
+
`+h.comment:l.comment=h.comment),l.range=[r.offset,m,h.offset]}else l.range=[r.offset,m,m];return l}cd.resolveFlowCollection=Cy});var dd=E(ud=>{"use strict";var Sy=D(),Ey=Z(),xy=Et(),_y=xt(),Ry=nd(),Py=id(),Ay=ld();function va(t,e,n,r,i,s){let o=n.type==="block-map"?Ry.resolveBlockMap(t,e,n,r,s):n.type==="block-seq"?Py.resolveBlockSeq(t,e,n,r,s):Ay.resolveFlowCollection(t,e,n,r,s),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function Oy(t,e,n,r,i){let s=r.tag,o=s?e.directives.tagName(s.source,f=>i(s,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=r,g=f&&s?f.offset>s.offset?f:s:f??s;g&&(!p||p.offset<g.offset)&&i(g,"MISSING_CHAR","Missing newline after block sequence props")}let a=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!s||!o||o==="!"||o===xy.YAMLMap.tagName&&a==="map"||o===_y.YAMLSeq.tagName&&a==="seq")return va(t,e,n,i,o);let c=e.schema.tags.find(f=>f.tag===o&&f.collection===a);if(!c){let f=e.schema.knownTags[o];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?i(s,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),va(t,e,n,i,o)}let l=va(t,e,n,i,o,c),u=c.resolve?.(l,f=>i(s,"TAG_RESOLVE_FAILED",f),e.options)??l,d=Sy.isNode(u)?u:new Ey.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}ud.composeCollection=Oy});var ba=E(fd=>{"use strict";var ka=Z();function Ny(t,e,n){let r=e.offset,i=jy(e,t.options.strict,n);if(!i)return{value:"",type:null,comment:"",range:[r,r,r]};let s=i.mode===">"?ka.Scalar.BLOCK_FOLDED:ka.Scalar.BLOCK_LITERAL,o=e.source?Iy(e.source):[],a=o.length;for(let m=o.length-1;m>=0;--m){let h=o[m][1];if(h===""||h==="\r")a=m;else break}if(a===0){let m=i.chomp==="+"&&o.length>0?`
|
|
73
73
|
`.repeat(Math.max(1,o.length-1)):"",h=r+i.length;return e.source&&(h+=e.source.length),{value:m,type:s,comment:i.comment,range:[r,h,h]}}let c=e.indent+i.indent,l=e.offset+i.length,u=0;for(let m=0;m<a;++m){let[h,v]=o[m];if(v===""||v==="\r")i.indent===0&&h.length>c&&(c=h.length);else{h.length<c&&n(l+h.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(c=h.length),u=m,c===0&&!t.atRoot&&n(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=h.length+v.length+1}for(let m=o.length-1;m>=a;--m)o[m][0].length>c&&(a=m+1);let d="",f="",p=!1;for(let m=0;m<u;++m)d+=o[m][0].slice(c)+`
|
|
74
74
|
`;for(let m=u;m<a;++m){let[h,v]=o[m];l+=h.length+v.length+1;let y=v[v.length-1]==="\r";if(y&&(v=v.slice(0,-1)),v&&h.length<c){let b=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;n(l-v.length-(y?2:1),"BAD_INDENT",b),h=""}s===ka.Scalar.BLOCK_LITERAL?(d+=f+h.slice(c)+v,f=`
|
|
75
75
|
`):h.length>c||v[0]===" "?(f===" "?f=`
|
|
@@ -84,7 +84,7 @@ ${l}
|
|
|
84
84
|
`+o[m][0].slice(c);d[d.length-1]!==`
|
|
85
85
|
`&&(d+=`
|
|
86
86
|
`);break;default:d+=`
|
|
87
|
-
`}let g=r+i.length+e.source.length;return{value:d,type:s,comment:i.comment,range:[r,g,g]}}function jy({offset:t,props:e},n,r){if(e[0].type!=="block-scalar-header")return r(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:i}=e[0],s=i[0],o=0,a="",c=-1;for(let f=1;f<i.length;++f){let p=i[f];if(!a&&(p==="-"||p==="+"))a=p;else{let g=Number(p);!o&&g?o=g:c===-1&&(c=t+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let l=!1,u="",d=i.length;for(let f=1;f<e.length;++f){let p=e[f];switch(p.type){case"space":l=!0;case"newline":d+=p.source.length;break;case"comment":n&&!l&&r(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=p.source.length,u=p.source.substring(1);break;case"error":r(p,"UNEXPECTED_TOKEN",p.message),d+=p.source.length;break;default:{let g=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",g);let m=p.source;m&&typeof m=="string"&&(d+=m.length)}}}return{mode:s,indent:o,chomp:a,comment:u,length:d}}function Iy(t){let e=t.split(/\n( *)/),n=e[0],r=n.match(/^( *)/),s=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let o=1;o<e.length;o+=2)s.push([e[o],e[o+1]]);return s}fd.resolveBlockScalar=Ny});var Sa=E(pd=>{"use strict";var Ca=
|
|
87
|
+
`}let g=r+i.length+e.source.length;return{value:d,type:s,comment:i.comment,range:[r,g,g]}}function jy({offset:t,props:e},n,r){if(e[0].type!=="block-scalar-header")return r(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:i}=e[0],s=i[0],o=0,a="",c=-1;for(let f=1;f<i.length;++f){let p=i[f];if(!a&&(p==="-"||p==="+"))a=p;else{let g=Number(p);!o&&g?o=g:c===-1&&(c=t+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let l=!1,u="",d=i.length;for(let f=1;f<e.length;++f){let p=e[f];switch(p.type){case"space":l=!0;case"newline":d+=p.source.length;break;case"comment":n&&!l&&r(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=p.source.length,u=p.source.substring(1);break;case"error":r(p,"UNEXPECTED_TOKEN",p.message),d+=p.source.length;break;default:{let g=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",g);let m=p.source;m&&typeof m=="string"&&(d+=m.length)}}}return{mode:s,indent:o,chomp:a,comment:u,length:d}}function Iy(t){let e=t.split(/\n( *)/),n=e[0],r=n.match(/^( *)/),s=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let o=1;o<e.length;o+=2)s.push([e[o],e[o+1]]);return s}fd.resolveBlockScalar=Ny});var Sa=E(pd=>{"use strict";var Ca=Z(),$y=jn();function Ty(t,e,n){let{offset:r,type:i,source:s,end:o}=t,a,c,l=(f,p,g)=>n(r+f,p,g);switch(i){case"scalar":a=Ca.Scalar.PLAIN,c=Ly(s,l);break;case"single-quoted-scalar":a=Ca.Scalar.QUOTE_SINGLE,c=qy(s,l);break;case"double-quoted-scalar":a=Ca.Scalar.QUOTE_DOUBLE,c=My(s,l);break;default:return n(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[r,r+s.length,r+s.length]}}let u=r+s.length,d=$y.resolveEnd(o,u,e,n);return{value:c,type:a,comment:d.comment,range:[r,u,d.offset]}}function Ly(t,e){let n="";switch(t[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${t[0]}`;break}case"@":case"`":{n=`reserved character ${t[0]}`;break}}return n&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),md(t)}function qy(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),md(t.slice(1,-1)).replace(/''/g,"'")}function md(t){let e,n;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
88
|
`,"sy"),n=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
89
|
`,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=e.exec(t);if(!r)return t;let i=r[1],s=" ",o=e.lastIndex;for(n.lastIndex=o;r=n.exec(t);)r[1]===""?s===`
|
|
90
90
|
`?i+=s:s=`
|
|
@@ -99,7 +99,7 @@ ${l}
|
|
|
99
99
|
`);)r===`
|
|
100
100
|
`&&(n+=`
|
|
101
101
|
`),e+=1,r=t[e+1];return n||(n=" "),{fold:n,offset:e}}var Dy={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Wy(t,e,n,r){let i=t.substr(e,n),o=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(o)}catch{let a=t.substr(e-2,n+2);return r(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}pd.resolveFlowScalar=Ty});var wd=E(gd=>{"use strict";var rn=D(),hd=
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Wy(t,e,n,r){let i=t.substr(e,n),o=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(o)}catch{let a=t.substr(e-2,n+2);return r(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}pd.resolveFlowScalar=Ty});var wd=E(gd=>{"use strict";var rn=D(),hd=Z(),By=ba(),Uy=Sa();function Ky(t,e,n,r){let{value:i,type:s,comment:o,range:a}=e.type==="block-scalar"?By.resolveBlockScalar(t,e,r):Uy.resolveFlowScalar(e,t.options.strict,r),c=n?t.directives.tagName(n.source,d=>r(n,"TAG_RESOLVE_FAILED",d)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[rn.SCALAR]:c?l=Hy(t.schema,i,c,n,r):e.type==="scalar"?l=zy(t,i,e,r):l=t.schema[rn.SCALAR];let u;try{let d=l.resolve(i,f=>r(n??e,"TAG_RESOLVE_FAILED",f),t.options);u=rn.isScalar(d)?d:new hd.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(n??e,"TAG_RESOLVE_FAILED",f),u=new hd.Scalar(i)}return u.range=a,u.source=i,s&&(u.type=s),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function Hy(t,e,n,r,i){if(n==="!")return t[rn.SCALAR];let s=[];for(let a of t.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;let o=t.knownTags[n];return o&&!o.collection?(t.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),t[rn.SCALAR])}function zy({atKey:t,directives:e,schema:n},r,i,s){let o=n.tags.find(a=>(a.default===!0||t&&a.default==="key")&&a.test?.test(r))||n[rn.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(r))??n[rn.SCALAR];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),u=`Value may be parsed as either ${c} or ${l}`;s(i,"TAG_RESOLVE_FAILED",u,!0)}}return o}gd.composeScalar=Ky});var vd=E(yd=>{"use strict";function Jy(t,e,n){if(e){n??(n=e.length);for(let r=n-1;r>=0;--r){let i=e[r];switch(i.type){case"space":case"comment":case"newline":t-=i.source.length;continue}for(i=e[++r];i?.type==="space";)t+=i.source.length,i=e[++r];break}}return t}yd.emptyScalarPosition=Jy});var Cd=E(xa=>{"use strict";var Gy=Xn(),Yy=D(),Vy=dd(),kd=wd(),Xy=jn(),Qy=vd(),Zy={composeNode:bd,composeEmptyNode:Ea};function bd(t,e,n,r){let i=t.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=n,l,u=!0;switch(e.type){case"alias":l=ev(t,e,r),(a||c)&&r(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=kd.composeScalar(t,e,c,r),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Vy.composeCollection(Zy,t,e,n,r),a&&(l.anchor=a.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(e,"RESOURCE_EXHAUSTION",f)}break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;r(e,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=Ea(t,e.offset,void 0,null,n,r)),a&&l.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&t.options.stringKeys&&(!Yy.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&u&&(l.srcToken=e),l}function Ea(t,e,n,r,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){let u={type:"scalar",offset:Qy.emptyScalarPosition(e,n,r),indent:-1,source:""},d=kd.composeScalar(t,u,a,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(d.spaceBefore=!0),s&&(d.comment=s,d.range[2]=c),d}function ev({options:t},{offset:e,source:n,end:r},i){let s=new Gy.Alias(n.substring(1));s.source===""&&i(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&i(e+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+n.length,a=Xy.resolveEnd(r,o,t.strict,i);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}xa.composeEmptyNode=Ea;xa.composeNode=bd});var xd=E(Ed=>{"use strict";var tv=mr(),Sd=Cd(),nv=jn(),rv=wr();function iv(t,e,{offset:n,start:r,value:i,end:s},o){let a=Object.assign({_directives:e},t),c=new tv.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=rv.resolveProps(r,{indicator:"doc-start",next:i??s?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?Sd.composeNode(l,i,u,o):Sd.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=nv.resolveEnd(s,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[n,d,f.offset],c}Ed.composeDoc=iv});var Ra=E(Pd=>{"use strict";var sv=oi("process"),ov=fo(),av=mr(),yr=gr(),_d=D(),cv=xd(),lv=jn();function vr(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:n}=t;return[e,e+(typeof n=="string"?n.length:1)]}function Rd(t){let e="",n=!1,r=!1;for(let i=0;i<t.length;++i){let s=t[i];switch(s[0]){case"#":e+=(e===""?"":r?`
|
|
103
103
|
|
|
104
104
|
`:`
|
|
105
105
|
`)+(s.substring(1)||" "),n=!0,r=!1;break;case"%":t[i+1]?.[0]!=="#"&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:e,afterEmptyLine:r}}var _a=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,i,s)=>{let o=vr(n);s?this.warnings.push(new yr.YAMLWarning(o,r,i)):this.errors.push(new yr.YAMLParseError(o,r,i))},this.directives=new ov.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,n){let{comment:r,afterEmptyLine:i}=Rd(this.prelude);if(r){let s=e.contents;if(n)e.comment=e.comment?`${e.comment}
|
|
@@ -114,136 +114,136 @@ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.pus
|
|
|
114
114
|
`),r=e.substring(0,n),i=e.substring(n+1)+`
|
|
115
115
|
`;if(t.type==="block-scalar"){let s=t.props[0];if(s.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s.source=r,t.source=i}else{let{offset:s}=t,o="indent"in t?t.indent:-1,a=[{type:"block-scalar-header",offset:s,indent:o,source:r}];Od(a,"end"in t?t.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
|
|
116
116
|
`});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:a,source:i})}}function Od(t,e){if(e)for(let n of e)switch(n.type){case"space":case"comment":t.push(n);break;case"newline":return t.push(n),!0}return!1}function Pa(t,e,n){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=n,t.source=e;break;case"block-scalar":{let r=t.props.slice(1),i=e.length;t.props[0].type==="block-scalar-header"&&(i-=t.props[0].source.length);for(let s of r)s.offset+=i;delete t.props,Object.assign(t,{type:n,source:e,end:r});break}case"block-map":case"block-seq":{let i={type:"newline",offset:t.offset+e.length,indent:t.indent,source:`
|
|
117
|
-
`};delete t.items,Object.assign(t,{type:n,source:e,end:[i]});break}default:{let r="indent"in t?t.indent:-1,i="end"in t&&Array.isArray(t.end)?t.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(t))s!=="type"&&s!=="offset"&&delete t[s];Object.assign(t,{type:n,indent:r,source:e,end:i})}}}ns.createScalarToken=pv;ns.resolveAsScalar=mv;ns.setScalarValue=hv});var Id=E(jd=>{"use strict";var wv=t=>"type"in t?is(t):rs(t);function is(t){switch(t.type){case"block-scalar":{let e="";for(let n of t.props)e+=is(n);return e+t.source}case"block-map":case"block-seq":{let e="";for(let n of t.items)e+=rs(n);return e}case"flow-collection":{let e=t.start.source;for(let n of t.items)e+=rs(n);for(let n of t.end)e+=n.source;return e}case"document":{let e=rs(t);if(t.end)for(let n of t.end)e+=n.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let n of t.end)e+=n.source;return e}}}function rs({start:t,key:e,sep:n,value:r}){let i="";for(let s of t)i+=s.source;if(e&&(i+=is(e)),n)for(let s of n)i+=s.source;return r&&(i+=is(r)),i}jd.stringify=wv});var qd=E(Ld=>{"use strict";var Aa=Symbol("break visit"),yv=Symbol("skip children"),$d=Symbol("remove item");function sn(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Td(Object.freeze([]),t,e)}sn.BREAK=Aa;sn.SKIP=yv;sn.REMOVE=$d;sn.itemAtPath=(t,e)=>{let n=t;for(let[r,i]of e){let s=n?.[r];if(s&&"items"in s)n=s.items[i];else return}return n};sn.parentCollection=(t,e)=>{let n=sn.itemAtPath(t,e.slice(0,-1)),r=e[e.length-1][0],i=n?.[r];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function Td(t,e,n){let r=n(e,t);if(typeof r=="symbol")return r;for(let i of["key","value"]){let s=e[i];if(s&&"items"in s){for(let o=0;o<s.items.length;++o){let a=Td(Object.freeze(t.concat([[i,o]])),s.items[o],n);if(typeof a=="number")o=a-1;else{if(a===Aa)return Aa;a===$d&&(s.items.splice(o,1),o-=1)}}typeof r=="function"&&i==="key"&&(r=r(e,t))}}return typeof r=="function"?r(e,t):r}Ld.visit=sn});var ss=E(
|
|
117
|
+
`};delete t.items,Object.assign(t,{type:n,source:e,end:[i]});break}default:{let r="indent"in t?t.indent:-1,i="end"in t&&Array.isArray(t.end)?t.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(t))s!=="type"&&s!=="offset"&&delete t[s];Object.assign(t,{type:n,indent:r,source:e,end:i})}}}ns.createScalarToken=pv;ns.resolveAsScalar=mv;ns.setScalarValue=hv});var Id=E(jd=>{"use strict";var wv=t=>"type"in t?is(t):rs(t);function is(t){switch(t.type){case"block-scalar":{let e="";for(let n of t.props)e+=is(n);return e+t.source}case"block-map":case"block-seq":{let e="";for(let n of t.items)e+=rs(n);return e}case"flow-collection":{let e=t.start.source;for(let n of t.items)e+=rs(n);for(let n of t.end)e+=n.source;return e}case"document":{let e=rs(t);if(t.end)for(let n of t.end)e+=n.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let n of t.end)e+=n.source;return e}}}function rs({start:t,key:e,sep:n,value:r}){let i="";for(let s of t)i+=s.source;if(e&&(i+=is(e)),n)for(let s of n)i+=s.source;return r&&(i+=is(r)),i}jd.stringify=wv});var qd=E(Ld=>{"use strict";var Aa=Symbol("break visit"),yv=Symbol("skip children"),$d=Symbol("remove item");function sn(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Td(Object.freeze([]),t,e)}sn.BREAK=Aa;sn.SKIP=yv;sn.REMOVE=$d;sn.itemAtPath=(t,e)=>{let n=t;for(let[r,i]of e){let s=n?.[r];if(s&&"items"in s)n=s.items[i];else return}return n};sn.parentCollection=(t,e)=>{let n=sn.itemAtPath(t,e.slice(0,-1)),r=e[e.length-1][0],i=n?.[r];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function Td(t,e,n){let r=n(e,t);if(typeof r=="symbol")return r;for(let i of["key","value"]){let s=e[i];if(s&&"items"in s){for(let o=0;o<s.items.length;++o){let a=Td(Object.freeze(t.concat([[i,o]])),s.items[o],n);if(typeof a=="number")o=a-1;else{if(a===Aa)return Aa;a===$d&&(s.items.splice(o,1),o-=1)}}typeof r=="function"&&i==="key"&&(r=r(e,t))}}return typeof r=="function"?r(e,t):r}Ld.visit=sn});var ss=E(Ee=>{"use strict";var Oa=Nd(),vv=Id(),kv=qd(),Na="\uFEFF",ja="",Ia="",$a="",bv=t=>!!t&&"items"in t,Cv=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function Sv(t){switch(t){case Na:return"<BOM>";case ja:return"<DOC>";case Ia:return"<FLOW_END>";case $a:return"<SCALAR>";default:return JSON.stringify(t)}}function Ev(t){switch(t){case Na:return"byte-order-mark";case ja:return"doc-mode";case Ia:return"flow-error-end";case $a:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
118
118
|
`:case`\r
|
|
119
|
-
`: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(t[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}
|
|
119
|
+
`: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(t[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=Oa.createScalarToken;Ee.resolveAsScalar=Oa.resolveAsScalar;Ee.setScalarValue=Oa.setScalarValue;Ee.stringify=vv.stringify;Ee.visit=kv.visit;Ee.BOM=Na;Ee.DOCUMENT=ja;Ee.FLOW_END=Ia;Ee.SCALAR=$a;Ee.isCollection=bv;Ee.isScalar=Cv;Ee.prettyToken=Sv;Ee.tokenType=Ev});var qa=E(Fd=>{"use strict";var kr=ss();function Ue(t){switch(t){case void 0:case" ":case`
|
|
120
120
|
`:case"\r":case" ":return!0;default:return!1}}var Md=new Set("0123456789ABCDEFabcdef"),xv=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),os=new Set(",[]{}"),_v=new Set(` ,[]{}
|
|
121
121
|
\r `),Ta=t=>!t||_v.has(t),La=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(e,n=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!n;let r=this.next??"stream";for(;r&&(n||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,n=this.buffer[e];for(;n===" "||n===" ";)n=this.buffer[++e];return!n||n==="#"||n===`
|
|
122
122
|
`?!0:n==="\r"?this.buffer[e+1]===`
|
|
123
123
|
`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let n=this.buffer[e];if(this.indentNext>0){let r=0;for(;n===" ";)n=this.buffer[++r+e];if(n==="\r"){let i=this.buffer[r+e+1];if(i===`
|
|
124
124
|
`||!i&&!this.atEnd)return e+r+1}return n===`
|
|
125
|
-
`||r>=this.indentNext||!n&&!this.atEnd?e+r:-1}if(n==="-"||n==="."){let r=this.buffer.substr(e,3);if((r==="---"||r==="...")&&
|
|
126
|
-
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){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 e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===kr.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let n=e.length,r=e.indexOf("#");for(;r!==-1;){let s=e[r-1];if(s===" "||s===" "){n=r-1;break}else r=e.indexOf("#",r+1)}for(;;){let s=e[n-1];if(s===" "||s===" ")n-=1;else break}let i=(yield*this.pushCount(n))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-i),this.pushNewline(),"stream"}if(this.atLineEnd()){let n=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-n),yield*this.pushNewline(),"stream"}return yield kr.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let n=this.peek(3);if((n==="---"||n==="...")&&
|
|
125
|
+
`||r>=this.indentNext||!n&&!this.atEnd?e+r:-1}if(n==="-"||n==="."){let r=this.buffer.substr(e,3);if((r==="---"||r==="...")&&Ue(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
|
|
126
|
+
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){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 e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===kr.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let n=e.length,r=e.indexOf("#");for(;r!==-1;){let s=e[r-1];if(s===" "||s===" "){n=r-1;break}else r=e.indexOf("#",r+1)}for(;;){let s=e[n-1];if(s===" "||s===" ")n-=1;else break}let i=(yield*this.pushCount(n))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-i),this.pushNewline(),"stream"}if(this.atLineEnd()){let n=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-n),yield*this.pushNewline(),"stream"}return yield kr.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let n=this.peek(3);if((n==="---"||n==="...")&&Ue(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,n==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Ue(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Ue(n)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(e[n]){case"#":yield*this.pushCount(e.length-n);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(Ta),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,n,r=-1;do e=yield*this.pushNewline(),e>0?(n=yield*this.pushSpaces(!1),this.indentValue=r=n):n=0,n+=yield*this.pushSpaces(!0);while(e+n>0);let i=this.getLine();if(i===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&i[0]!=="#"||r===0&&(i.startsWith("---")||i.startsWith("..."))&&Ue(i[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield kr.FLOW_END,yield*this.parseLineStart();let s=0;for(;i[s]===",";)s+=yield*this.pushCount(1),s+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(s+=yield*this.pushIndicators(),i[s]){case void 0:return"flow";case"#":return yield*this.pushCount(i.length-s),"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(Ta),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ue(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 e=this.charAt(0),n=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;n!==-1&&this.buffer[n+1]==="'";)n=this.buffer.indexOf("'",n+2);else for(;n!==-1;){let s=0;for(;this.buffer[n-1-s]==="\\";)s+=1;if(s%2===0)break;n=this.buffer.indexOf('"',n+1)}let r=this.buffer.substring(0,n),i=r.indexOf(`
|
|
127
127
|
`,this.pos);if(i!==-1){for(;i!==-1;){let s=this.continueScalar(i+1);if(s===-1)break;i=r.indexOf(`
|
|
128
|
-
`,s)}i!==-1&&(n=i-(r[i-1]==="\r"?2:1))}if(n===-1){if(!this.atEnd)return this.setNext("quoted-scalar");n=this.buffer.length}return yield*this.pushToIndex(n+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let n=this.buffer[++e];if(n==="+")this.blockScalarKeep=!0;else if(n>"0"&&n<="9")this.blockScalarIndent=Number(n)-1;else if(n!=="-")break}return yield*this.pushUntil(n=>
|
|
128
|
+
`,s)}i!==-1&&(n=i-(r[i-1]==="\r"?2:1))}if(n===-1){if(!this.atEnd)return this.setNext("quoted-scalar");n=this.buffer.length}return yield*this.pushToIndex(n+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let n=this.buffer[++e];if(n==="+")this.blockScalarKeep=!0;else if(n>"0"&&n<="9")this.blockScalarIndent=Number(n)-1;else if(n!=="-")break}return yield*this.pushUntil(n=>Ue(n)||n==="#")}*parseBlockScalar(){let e=this.pos-1,n=0,r;e:for(let s=this.pos;r=this.buffer[s];++s)switch(r){case" ":n+=1;break;case`
|
|
129
129
|
`:e=s,n=0;break;case"\r":{let o=this.buffer[s+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
130
130
|
`)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=n:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let s=this.continueScalar(e+1);if(s===-1)break;e=this.buffer.indexOf(`
|
|
131
131
|
`,s)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let i=e+1;for(r=this.buffer[i];r===" ";)r=this.buffer[++i];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
|
|
132
132
|
`;)r=this.buffer[++i];e=i-1}else if(!this.blockScalarKeep)do{let s=e-1,o=this.buffer[s];o==="\r"&&(o=this.buffer[--s]);let a=s;for(;o===" ";)o=this.buffer[--s];if(o===`
|
|
133
|
-
`&&s>=this.pos&&s+1+n>a)e=s;else break}while(!0);return yield kr.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,n=this.pos-1,r=this.pos-1,i;for(;i=this.buffer[++r];)if(i===":"){let s=this.buffer[r+1];if(
|
|
133
|
+
`&&s>=this.pos&&s+1+n>a)e=s;else break}while(!0);return yield kr.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,n=this.pos-1,r=this.pos-1,i;for(;i=this.buffer[++r];)if(i===":"){let s=this.buffer[r+1];if(Ue(s)||e&&os.has(s))break;n=r}else if(Ue(i)){let s=this.buffer[r+1];if(i==="\r"&&(s===`
|
|
134
134
|
`?(r+=1,i=`
|
|
135
135
|
`,s=this.buffer[r+1]):n=r),s==="#"||e&&os.has(s))break;if(i===`
|
|
136
|
-
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(e&&os.has(i))break;n=r}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield kr.SCALAR,yield*this.pushToIndex(n+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,n){let r=this.buffer.slice(this.pos,e);return r?(yield r,this.pos+=r.length,r.length):(n&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Ta),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(
|
|
136
|
+
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(e&&os.has(i))break;n=r}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield kr.SCALAR,yield*this.pushToIndex(n+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,n){let r=this.buffer.slice(this.pos,e);return r?(yield r,this.pos+=r.length,r.length):(n&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Ta),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(Ue(r)||n&&os.has(r)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,n=this.buffer[e];for(;!Ue(n)&&n!==">";)n=this.buffer[++e];return yield*this.pushToIndex(n===">"?e+1:e,!1)}else{let e=this.pos+1,n=this.buffer[e];for(;n;)if(xv.has(n))n=this.buffer[++e];else if(n==="%"&&Md.has(this.buffer[e+1])&&Md.has(this.buffer[e+2]))n=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
|
|
137
137
|
`?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
|
|
138
|
-
`?yield*this.pushCount(2):0}*pushSpaces(e){let n=this.pos-1,r;do r=this.buffer[++n];while(r===" "||e&&r===" ");let i=n-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=n),i}*pushUntil(e){let n=this.pos,r=this.buffer[n];for(;!e(r);)r=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};Fd.Lexer=La});var Fa=E(Dd=>{"use strict";var Ma=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,r=this.lineStarts.length;for(;n<r;){let s=n+r>>1;this.lineStarts[s]<e?n=s+1:r=s}if(this.lineStarts[n]===e)return{line:n+1,col:1};if(n===0)return{line:0,col:e};let i=this.lineStarts[n-1];return{line:n,col:e-i+1}}}};Dd.LineCounter=Ma});var Wa=E(Hd=>{"use strict";var Rv=oi("process"),Wd=ss(),Pv=qa();function
|
|
138
|
+
`?yield*this.pushCount(2):0}*pushSpaces(e){let n=this.pos-1,r;do r=this.buffer[++n];while(r===" "||e&&r===" ");let i=n-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=n),i}*pushUntil(e){let n=this.pos,r=this.buffer[n];for(;!e(r);)r=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};Fd.Lexer=La});var Fa=E(Dd=>{"use strict";var Ma=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let n=0,r=this.lineStarts.length;for(;n<r;){let s=n+r>>1;this.lineStarts[s]<e?n=s+1:r=s}if(this.lineStarts[n]===e)return{line:n+1,col:1};if(n===0)return{line:0,col:e};let i=this.lineStarts[n-1];return{line:n,col:e-i+1}}}};Dd.LineCounter=Ma});var Wa=E(Hd=>{"use strict";var Rv=oi("process"),Wd=ss(),Pv=qa();function _t(t,e){for(let n=0;n<t.length;++n)if(t[n].type===e)return!0;return!1}function Bd(t){for(let e=0;e<t.length;++e)switch(t[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function Kd(t){switch(t?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function as(t){switch(t.type){case"document":return t.start;case"block-map":{let e=t.items[t.items.length-1];return e.sep??e.start}case"block-seq":return t.items[t.items.length-1].start;default:return[]}}function In(t){if(t.length===0)return[];let e=t.length;e:for(;--e>=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function cs(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let n=0;n<e.length;++n)t.push(e[n])}function Ud(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!_t(e.start,"explicit-key-ind")&&!_t(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Kd(e.value)?e.value.end?cs(e.value.end,e.sep):e.value.end=e.sep:cs(e.start,e.sep),delete e.sep)}var Da=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Pv.Lexer,this.onNewLine=e}*parse(e,n=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(e,n))yield*this.next(r);n||(yield*this.end())}*next(e){if(this.source=e,Rv.env.LOG_TOKENS&&console.log("|",Wd.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let n=Wd.tokenType(e);if(n)if(n==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=n,yield*this.step(),n){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let r=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:e}),this.offset+=e.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 e=this.peek(1);if(this.type==="doc-end"&&e?.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(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let n=e??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let r=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in r?r.indent:0:n.type==="flow-collection"&&r.type==="document"&&(n.indent=0),n.type==="flow-collection"&&Ud(n),r.type){case"document":r.value=n;break;case"block-scalar":r.props.push(n);break;case"block-map":{let i=r.items[r.items.length-1];if(i.value){r.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=n;else{Object.assign(i,{key:n,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{let i=r.items[r.items.length-1];i.value?r.items.push({start:[],value:n}):i.value=n;break}case"flow-collection":{let i=r.items[r.items.length-1];!i||i.value?r.items.push({start:[],key:n,sep:[]}):i.sep?i.value=n:Object.assign(i,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let i=n.items[n.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&Bd(i.start)===-1&&(n.indent===0||i.start.every(s=>s.type!=="comment"||s.indent<n.indent))&&(r.type==="document"?r.end=i.start:r.items.push({start:i.start}),n.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 e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{Bd(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let n=as(this.peek(2)),r=In(n),i;e.end?(i=e.end,i.push(this.sourceToken),delete e.end):i=[this.sourceToken];let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let n=this.source.indexOf(`
|
|
139
139
|
`)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
|
|
140
|
-
`,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,e.indent)){let i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){cs(i,n.start),i.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,i=r&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(i&&n.sep&&!n.value){let o=[];for(let a=0;a<n.sep.length;++a){let c=n.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=n.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||n.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):i||n.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(
|
|
140
|
+
`,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,e.indent)){let i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){cs(i,n.start),i.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,i=r&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(i&&n.sep&&!n.value){let o=[];for(let a=0;a<n.sep.length;++a){let c=n.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=n.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||n.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):i||n.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(_t(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(Kd(n.key)&&!_t(n.sep,"newline")){let o=In(n.start),a=n.key,c=n.sep;c.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else s.length>0?n.sep=n.sep.concat(s,this.sourceToken):n.sep.push(this.sourceToken);else if(_t(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let o=In(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||i?e.items.push({start:s,key:null,sep:[this.sourceToken]}):_t(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);i||n.value?(e.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(o):(Object.assign(n,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!n.explicitKey&&n.sep&&!_t(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&e.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,e.indent)){let i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){cs(i,n.start),i.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=e.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;n.value||_t(n.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let n=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?e.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);!n||n.value?e.items.push({start:[],key:i,sep:[]}):n.sep?this.stack.push(i):Object.assign(n,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let i=as(r),s=In(i);Ud(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let n=this.source.indexOf(`
|
|
141
141
|
`)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
|
|
142
|
-
`,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){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 n=as(e),r=In(n);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=as(e),r=In(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){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:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Hd.Parser=Da});var Vd=E(Cr=>{"use strict";var zd=Ra(),Av=mr(),br=gr(),Ov=xo(),Nv=D(),jv=Fa(),Jd=Wa();function Gd(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new jv.LineCounter||null,prettyErrors:e}}function Iv(t,e={}){let{lineCounter:n,prettyErrors:r}=Gd(e),i=new Jd.Parser(n?.addNewLine),s=new zd.Composer(e),o=Array.from(s.compose(i.parse(t)));if(r&&n)for(let a of o)a.errors.forEach(br.prettifyError(t,n)),a.warnings.forEach(br.prettifyError(t,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function Yd(t,e={}){let{lineCounter:n,prettyErrors:r}=Gd(e),i=new Jd.Parser(n?.addNewLine),s=new zd.Composer(e),o=null;for(let a of s.compose(i.parse(t),!0,t.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new br.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(o.errors.forEach(br.prettifyError(t,n)),o.warnings.forEach(br.prettifyError(t,n))),o}function $v(t,e,n){let r;typeof e=="function"?r=e:n===void 0&&e&&typeof e=="object"&&(n=e);let i=Yd(t,n);if(!i)return null;if(i.warnings.forEach(s=>Ov.warn(i.options.logLevel,s)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:r},n))}function Tv(t,e,n){let r=null;if(typeof e=="function"||Array.isArray(e)?r=e:n===void 0&&e&&(n=e),typeof n=="string"&&(n=n.length),typeof n=="number"){let i=Math.round(n);n=i<1?void 0:i>8?{indent:8}:{indent:i}}if(t===void 0){let{keepUndefined:i}=n??e??{};if(!i)return}return Nv.isDocument(t)&&!r?t.toString(n):new Av.Document(t,r,n).toString(n)}Cr.parse=$v;Cr.parseAllDocuments=Iv;Cr.parseDocument=Yd;Cr.stringify=Tv});var Se=E(W=>{"use strict";var Lv=Ra(),qv=mr(),Mv=aa(),Ba=gr(),Fv=Xn(),_t=D(),Dv=bt(),Wv=ee(),Bv=St(),Uv=Et(),Kv=ss(),Hv=qa(),zv=Fa(),Jv=Wa(),ls=Vd(),Xd=Jn();W.Composer=Lv.Composer;W.Document=qv.Document;W.Schema=Mv.Schema;W.YAMLError=Ba.YAMLError;W.YAMLParseError=Ba.YAMLParseError;W.YAMLWarning=Ba.YAMLWarning;W.Alias=Fv.Alias;W.isAlias=_t.isAlias;W.isCollection=_t.isCollection;W.isDocument=_t.isDocument;W.isMap=_t.isMap;W.isNode=_t.isNode;W.isPair=_t.isPair;W.isScalar=_t.isScalar;W.isSeq=_t.isSeq;W.Pair=Dv.Pair;W.Scalar=Wv.Scalar;W.YAMLMap=Bv.YAMLMap;W.YAMLSeq=Uv.YAMLSeq;W.CST=Kv;W.Lexer=Hv.Lexer;W.LineCounter=zv.LineCounter;W.Parser=Jv.Parser;W.parse=ls.parse;W.parseAllDocuments=ls.parseAllDocuments;W.parseDocument=ls.parseDocument;W.stringify=ls.stringify;W.visit=Xd.visit;W.visitAsync=Xd.visitAsync});import Rt from"path";function Qv(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim();if(n.length===0||Rt.posix.isAbsolute(n)||Rt.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be a project-relative path`);if(n===".")return[];let r=n.replaceAll("\\","/").split("/");if(r.some(i=>i===".."))throw new Error(`${e} must stay inside the project root`);if(r.some(i=>i===""||i==="."))throw new Error(`${e} must not contain empty or dot path segments`);return r}function Er(t){let e=Qv(t,"native.artifact_root");return e.length===0?".":e.join("/")}function af(t,e="docs"){let n=t??e;if(n!=="legacy"&&n!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return n}function de(t,e,n=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim().replaceAll("\\","/");if(r.length===0||Rt.posix.isAbsolute(r)||Rt.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${e} must be relative to its declared path base`);let i=r.split("/");if(i.some(s=>s===".."))throw new Error(`${e} must stay inside its declared path base`);if(i.some(s=>s===""||s==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!n&&/[*?]/u.test(r))throw new Error(`${e} cannot contain wildcards`);return i.join("/")}function at(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function cf(t,e,n){let r=t??e;if(r!=="en"&&r!=="zh-CN")throw new Error(`${n} must be en or zh-CN`);return r}function xr(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>Ua)throw new Error(`${e} exceeds ${Ua} characters`);let n=0;for(let r=0;r<t.length;r+=1)t[r]==="?"?n+=1:t[r]==="*"&&(n+=1,t[r+1]==="*"&&(r+=1));if(n>Ka)throw new Error(`${e} contains more than ${Ka} wildcard tokens`);return t}function nf(t,e,n){if(t===void 0)return[...n];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(r=>xr(r,e)))].sort((r,i)=>r.localeCompare(i,"en"))}function Sr(t,e,n){let r=t??e;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${n} must be a positive integer`);return r}function rf(t,e,n){let r=Sr(t,e,n);if(r>Math.floor(Number.MAX_SAFE_INTEGER/(1024*1024)))throw new Error(`${n} is too large to convert to bytes safely`);return r}function Zv(t){if(t===void 0)return{...Re,include:[...Re.include],exclude:[...Re.exclude]};let e=at(t,"native.snapshot");return{include:nf(e.include,"native.snapshot.include",Re.include),exclude:nf(e.exclude,"native.snapshot.exclude",Re.exclude),max_files:Sr(e.max_files,Re.max_files,"native.snapshot.max_files"),max_total_bytes:Sr(e.max_total_bytes,Re.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Sr(e.max_duration_ms,Re.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:Sr(e.max_selection_records,Re.max_selection_records,"native.snapshot.max_selection_records")}}function ek(t){if(t===void 0)return;let e=at(t,"native.pending_root_move"),n=e.id,r=e.from_artifact_root,i=e.to_artifact_root,s=e.stage;if(typeof n!="string"||!/^[a-f0-9-]{8,}$/u.test(n))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof i!="string")throw new Error("native.pending_root_move roots must be strings");if(s!=="copying"&&s!=="ready"&&s!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let a=at(e.cleanup,"native.pending_root_move.cleanup"),c=a.kind,l=a.state,u=a.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:n,fromArtifactRoot:Er(r),toArtifactRoot:Er(i),stage:s,...o?{cleanup:o}:{}}}function tk(t){if(t===void 0)return;let e=at(t,"native.finish");if(e.pull_request===void 0)return{};let n=at(e.pull_request,"native.finish.pull_request");if(n.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(n.command)||n.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(n.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let r=n.command.map((s,o)=>{if(typeof s!="string"||s.trim().length===0||s.length>4096||/[\0\r\n]/u.test(s))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return s});if(Rt.posix.isAbsolute(r[0])||Rt.win32.isAbsolute(r[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let i=n.timeout_ms??Gv;if(!Number.isSafeInteger(i)||i<1||i>tf)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${tf}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:i}}}function nk(t,e={}){let n=at(t,"native"),r=n.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let i=n.clarification_mode??"batch";if(i!=="sequential"&&i!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let s=n.archive_confirmation??"automatic";if(s!=="automatic"&&s!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=n.max_verify_failures??sf;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let a=n.document_writes??"allow";if(a!=="allow"&&a!=="revert")throw new Error("native.document_writes must be allow or revert");let c=ek(n.pending_root_move),l=tk(n.finish);return{artifact_root:Er(r),language:cf(n.language,"en","native.language"),clarification_mode:i,archive_confirmation:s,max_verify_failures:o,...a==="revert"?{document_writes:a}:{},snapshot:Zv(n.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function rk(t){let e=at(t,"classic"),n=e.context_compression??"off";if(n!=="off"&&n!=="beta")throw new Error("classic.context_compression must be off or beta");let r=e.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let i=e.auto_transition??!0;if(typeof i!="boolean")throw new Error("classic.auto_transition must be true or false");let s=e.document_evidence??"neutral";if(s!=="neutral"&&s!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:af(e.artifact_layout),language:cf(e.language,"zh-CN","classic.language"),context_compression:n,review_mode:r,auto_transition:i,...s==="strict"?{document_evidence:s}:{}}}function ik(t){let n=at(t,"hook").allow_paths??[];if(!Array.isArray(n))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(n.map((r,i)=>de(r,`hook.allow_paths[${i}]`)))]}}function sk(t){if(t===void 0)return{...us};let e=at(t,"memory"),n=e.learning??us.learning,r=e.retrieval??us.retrieval;if(typeof n!="boolean")throw new Error("memory.learning must be true or false");if(typeof r!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:n,retrieval:r}}function za(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function ok(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim();if(n.length===0||n.includes("\\")||n.includes("\0")||Rt.posix.isAbsolute(n)||Rt.win32.isAbsolute(n)||n.startsWith("~")||n.split("/").some(i=>i===""||i==="."||i===".."))throw new Error(`${e} must be a safe project-relative glob`);if(!n.toLowerCase().endsWith(".md"))throw new Error(`${e} must target a Markdown file ending in .md`);if(n.length>Qd)throw new Error(`${e} exceeds ${Qd} characters`);let r=0;for(let i=0;i<n.length;i+=1)n[i]==="?"?r+=1:n[i]==="*"&&(r+=1,n[i+1]==="*"&&(i+=1));if(r>Zd)throw new Error(`${e} contains more than ${Zd} wildcard tokens`);return n}function ak(t){let e=za(t,"knowledge.local"),n=e.include??[];if(!Array.isArray(n))throw new Error("knowledge.local.include must be an array");let r={include:[...new Set(n.map((i,s)=>ok(i,`knowledge.local.include[${s}]`)))],max_file_mb:rf(e.max_file_mb,ef.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:rf(e.max_total_mb,ef.max_total_mb,"knowledge.local.max_total_mb")};if(r.max_file_mb>r.max_total_mb)throw new Error("knowledge.local.max_file_mb must not exceed max_total_mb");return r}function ck(t){if(typeof t!="string"||t.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let e;try{e=new URL(t)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let n=e.hostname.toLowerCase().replace(/^\[|\]$/gu,""),r=n==="localhost"||n==="127.0.0.1"||n==="::1";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&r))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return e.toString()}function lk(t){let e=za(t,"knowledge.remote"),n=ck(e.endpoint),r=e.token_env;if(r!==void 0&&(typeof r!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(r)))throw new Error("knowledge.remote.token_env must be an environment variable name");let i=e.scope;if(i!==void 0&&(typeof i!="string"||i.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let s=e.timeout_ms??5e3;if(typeof s!="number"||!Number.isSafeInteger(s)||s<100||s>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:n,...r===void 0?{}:{token_env:r},...i===void 0?{}:{scope:i},timeout_ms:s}}function uk(t){if(t===void 0)return{...of};let e=za(t,"knowledge"),n=e.provider??"local";if(n!=="local"&&n!=="remote")throw new Error("knowledge.provider must be local or remote");let r=e.local===void 0?void 0:ak(e.local);if(n==="local")return{provider:n,...r?{local:r}:{}};let i=e.remote===void 0?void 0:lk(e.remote);if(i===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:n,...r?{local:r}:{},remote:i}}function dk(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function fk(t,e,n,r,i,s,o,a){let c=t.schema!==void 0;if(!(c||t.default_workflow!==void 0||t.workflows!==void 0||!a.allowPartialProject&&t.native!==void 0)||a.allowPartialProject&&!c)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=t.workflows??[t.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!i)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:d,ambient_resume:o,...e?{hook:e}:{},memory:n,knowledge:r,...i?{native:i}:{},...s?{classic:s}:{}}}function Pt(t,e={}){let n=(0,Ha.parseDocument)(t,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${n.errors[0].message}`);let r=n.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let i=r,s=dk(i.ambient_resume),o=i.hook===void 0?void 0:ik(i.hook),a=sk(i.memory),c=uk(i.knowledge),l=i.native===void 0?void 0:nk(i.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),u=i.classic===void 0?void 0:rk(i.classic),d=fk(i,o,a,c,l,u,s,{allowPartialProject:e.allowPartialProject??!1});return{value:i,config:d,ambient_resume:s,memory:a,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function Ja(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...us},knowledge:{...of},native:{artifact_root:Er(t),language:e,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:sf,snapshot:{...Re,include:[...Re.include],exclude:[...Re.exclude]}}}}var Ha,$n,Ua,Ka,Qd,Zd,sf,us,ef,of,Gv,tf,Yv,Vv,Xv,Re,Ye=z(()=>{"use strict";Ha=_e(Se(),1),$n=Number.MAX_SAFE_INTEGER,Ua=1024,Ka=64,Qd=1024,Zd=64,sf=5,us={learning:!0,retrieval:!0},ef={include:[],max_file_mb:1,max_total_mb:32},of={provider:"local"},Gv=12e4,tf=6e5,Yv=[".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/**"],Vv=["**/.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"],Xv=[...Yv,...Vv].sort((t,e)=>t.localeCompare(e,"en")),Re={include:["**/*"],exclude:[...Xv],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4}});import{constants as At,promises as Ee}from"fs";import{createHash as mk}from"node:crypto";function Ga(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function lf(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function Nt(t){return{dev:t.dev,ino:t.ino,birthtime:Ga(t)}}function Ot(t,e){let n=Nt(t),r=Nt(e);return al(n,r)?gt(n,r):gt(n,r)&&Ga(t)===Ga(e)&&lf(t)===lf(e)&&t.size===e.size}async function Ya(t,e,n={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let r=n.label??"file",i=n.bigint===!0,s=await Ee.lstat(t,{bigint:i});if(!s.isFile()||s.isSymbolicLink())throw new Te("not-regular-file",`${r} must be a regular file`);if(BigInt(s.size)>BigInt(e))throw new Te("too-large",`${r} exceeds ${e} bytes`);let o=await Ee.realpath(t);await n.verify?.("pre-open",{realPath:o,identity:Nt(s)});let a=process.platform==="win32"?At.O_RDONLY:At.O_RDONLY|At.O_NOFOLLOW|At.O_NONBLOCK,c;try{c=await Ee.open(t,a)}catch(l){throw l.code==="ELOOP"?new Te("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:i}),Ee.lstat(t,{bigint:i}),Ee.realpath(t)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Ot(s,l)||!Ot(s,u))throw new Te("changed",`${r} changed while opening`);await n.verify?.("post-open",{realPath:d,identity:Nt(l)}),await n.hooks?.afterOpen?.();let f=[],p=0,g=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let y=e+1-p,{bytesRead:S}=await c.read(g,0,Math.min(g.length,y),null);if(S===0)break;if(p+=S,p>e)throw new Te("too-large",`${r} exceeds ${e} bytes`);f.push(Buffer.from(g.subarray(0,S)))}await n.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([c.stat({bigint:i}),Ee.lstat(t,{bigint:i}),Ee.realpath(t)]);if(!h.isFile()||h.isSymbolicLink()||v!==o||!Ot(s,m)||!Ot(s,h))throw new Te("changed",`${r} changed while reading`);return await n.verify?.("post-read",{realPath:v,identity:Nt(m)}),{bytes:Buffer.concat(f,p),stat:m,realPath:v}}finally{await c.close()}}async function uf(t,e={}){let n=e.label??"file",r=e.bigint===!0,i=await Ee.lstat(t,{bigint:r});if(!i.isFile()||i.isSymbolicLink())throw new Te("not-regular-file",`${n} must be a regular file`);let s=await Ee.realpath(t);await e.verify?.("pre-open",{realPath:s,identity:Nt(i)});let o=process.platform==="win32"?At.O_RDONLY:At.O_RDONLY|At.O_NOFOLLOW|At.O_NONBLOCK,a;try{a=await Ee.open(t,o)}catch(c){throw c.code==="ELOOP"?new Te("not-regular-file",`${n} must be a regular file`,{cause:c}):c}try{let[c,l,u]=await Promise.all([a.stat({bigint:r}),Ee.lstat(t,{bigint:r}),Ee.realpath(t)]);if(!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==s||!Ot(i,c)||!Ot(i,l))throw new Te("changed",`${n} changed while opening`);await e.verify?.("post-open",{realPath:u,identity:Nt(c)}),await e.hooks?.afterOpen?.();let d=mk(e.algorithm??"sha256"),f=Buffer.allocUnsafe(64*1024);for(;;){let{bytesRead:h}=await a.read(f,0,f.length,null);if(h===0)break;d.update(f.subarray(0,h))}await e.hooks?.beforeFinalCheck?.();let[p,g,m]=await Promise.all([a.stat({bigint:r}),Ee.lstat(t,{bigint:r}),Ee.realpath(t)]);if(!g.isFile()||g.isSymbolicLink()||m!==s||!Ot(i,p)||!Ot(i,g))throw new Te("changed",`${n} changed while reading`);return await e.verify?.("post-read",{realPath:m,identity:Nt(p)}),{digest:d.digest("hex"),stat:p,realPath:m}}finally{await a.close()}}var Te,Va=z(()=>{"use strict";ci();Te=class extends Error{reason;constructor(e,n,r){super(n,r),this.name="RaceSafeReadError",this.reason=e}}});import{promises as jt}from"fs";import Ue from"path";async function df(t,e,n){let r=await J(t,e,{label:n.label,expected:"file"});if(!r.exists){let s=new Error(`${n.label} does not exist`);throw s.code="ENOENT",s}let i=await ds(r.projectRoot,n.label);return uf(r.target,{...n,verify:async(s,o)=>{if(!_r(i,o.realPath))throw new Error(`${n.label} resolves outside the project root`);await fs(r.projectRoot,i,r.relative.split("/"),{label:n.label,expected:"file"})}})}function ff(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function _r(t,e){let n=Ue.relative(t,e);return n===""||!Ue.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${Ue.sep}`)}async function ds(t,e){let n=Ue.resolve(t),r=await jt.lstat(n);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return jt.realpath(n)}async function fs(t,e,n,r){let i=t;for(let s=0;s<n.length;s++){i=Ue.join(i,n[s]);let o;try{o=await jt.lstat(i)}catch(u){if(ff(u))return{exists:!1,kind:"missing"};throw u}let a=Ue.relative(t,i).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${a}`);let c=s===n.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${a} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await jt.realpath(i);if(!_r(e,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function J(t,e,n){let r=de(e,n.label),i=Ue.resolve(t),s=await ds(i,n.label),o=r.split("/"),a=Ue.resolve(i,...o);if(!_r(i,a))throw new Error(`${n.label} must stay inside the project root`);let c=await fs(i,s,o,n);return{projectRoot:i,target:a,relative:r,exists:c.exists,kind:c.kind}}async function Xa(t,e,n){let r=de(e,n.label),i=Ue.resolve(t),s=await ds(i,n.label),o=r.split("/"),a=i;for(let c of o){a=Ue.join(a,c);let l;try{l=await jt.lstat(a)}catch(f){if(!ff(f))throw f;try{await jt.mkdir(a)}catch(p){if(p.code!=="EEXIST")throw p}l=await jt.lstat(a)}let u=Ue.relative(i,a).replaceAll("\\","/");if(l.isSymbolicLink())throw new Error(`${n.label} crosses a symbolic link or junction at ${u}`);if(!l.isDirectory())throw new Error(`${n.label} directory ${u} must be a real directory`);let d=await jt.realpath(a);if(!_r(s,d))throw new Error(`${n.label} resolves outside the project root`)}return await fs(i,s,o,{label:n.label,expected:"directory"}),a}async function Qa(t,e,n){return(await J(t,e,{...n,expected:"file"})).exists}async function Y(t,e,n,r){let i=await J(t,e,{label:r.label,expected:"file"});if(!i.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let s=await ds(i.projectRoot,r.label);return Ya(i.target,n,{...r,verify:async(o,a)=>{if(!_r(s,a.realPath))throw new Error(`${r.label} resolves outside the project root`);await fs(i.projectRoot,s,i.relative.split("/"),{label:r.label,expected:"file"})}})}var le=z(()=>{"use strict";Va();Ye()});import{createHash as gk}from"crypto";function wk(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function ct(t,e={}){return(await hs(t,e)).document}async function yk(t){try{return(await Y(t,Nr,$n,{label:Nr})).bytes}catch(e){if(wk(e))return null;throw e}}function vk(t){return t?{exists:!0,sha256:gk("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function hs(t,e={}){let n=await yk(t);return{document:n?Pt(n.toString("utf8"),e):null,identity:vk(n)}}async function ec(t){return(await ct(t))?.config??null}var Nr,$t=z(()=>{"use strict";Ye();le();Nr=".comet/config.yaml"});var gR,tc=z(()=>{"use strict";it();$t();le();gR=16*1024});var rc=z(()=>{"use strict";it();Ye();$t();le();tc()});import{spawn as sc}from"node:child_process";import{existsSync as Sf}from"node:fs";import cn from"node:path";function oc(t,e){let n=e.toLowerCase();return Object.entries(t).find(([r,i])=>r.toLowerCase()===n&&i!==void 0)?.[1]}function Lk(t){let e=(oc(t,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(n=>n.trim().toLowerCase()).filter(Boolean);return[...new Set([...e,".ps1"])]}function qk(t,e,n){let i=cn.win32.isAbsolute(t)||/[\\/]/u.test(t)?[""]:(oc(e,"PATH")??"").split(cn.delimiter).map(a=>a.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=cn.win32.extname(t)?[t]:Lk(e).map(a=>`${t}${a}`);return i.flatMap(a=>o.map(c=>a?cn.join(a,c):cn.resolve(n,c)))}function ln(t,e,n){return qk(t,e,n).find(r=>Sf(r))??t}function Mk(t){let e=oc(t,"SystemRoot");if(e){let n=cn.join(e,"System32","WindowsPowerShell","v1.0","powershell.exe");if(Sf(n))return n}return"powershell.exe"}function ac(t){if(t.some(e=>$k.test(e)))throw new Error("Windows batch check arguments must not contain shell syntax")}function Fk(t,e,n){let r=Buffer.from(JSON.stringify({command:t,arguments:[...e]}),"utf8").toString("base64"),i=Buffer.from(Tk,"utf16le").toString("base64");return sc(Mk(n.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",i],{cwd:n.cwd,env:{...n.env,COMET_COMMAND_PAYLOAD:r},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function Ef(t,e,n){let r=n.env??process.env;if(process.platform!=="win32")return sc(t,[...e],{cwd:n.cwd,env:r,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let i=ln(t,r,n.cwd),s=cn.win32.extname(i).toLowerCase();return Ik.has(s)&&ac(e),jk.has(s)?Fk(i,e,{cwd:n.cwd,env:r}):sc(i,[...e],{cwd:n.cwd,env:r,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}var jk,Ik,$k,Tk,Tr=z(()=>{"use strict";jk=new Set([".bat",".cmd",".ps1"]),Ik=new Set([".bat",".cmd"]),$k=/[&|<>()^%"!\r\n]/u,Tk=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ")});import{execFileSync as Dk}from"node:child_process";import xf from"node:path";function Uk(t){return t instanceof Error&&(t.code==="ETIMEDOUT"||t.killed===!0&&t.signal==="SIGTERM")}function Ln(t,e,n={}){let r=n.timeoutMs??Wk,i=n.maxBufferBytes??Bk;if(!Number.isSafeInteger(r)||r<1)throw new Error("External command timeout must be a positive integer");if(!Number.isSafeInteger(i)||i<1)throw new Error("External command max buffer must be a positive integer");let s=xf.resolve(n.cwd??process.cwd()),o=n.env??process.env,a=process.platform==="win32"?ln(t,o,s):t,c=xf.win32.extname(a).toLowerCase(),l=c===".bat"||c===".cmd";process.platform==="win32"&&l&&ac(e);try{return Dk(a,[...e],{cwd:s,env:o,...n.input!==void 0?{input:n.input}:{},encoding:"utf8",stdio:[n.input===void 0?"ignore":"pipe","pipe","pipe"],timeout:r,maxBuffer:i,windowsHide:!0,shell:process.platform==="win32"&&l})}catch(u){let d=typeof u.stderr=="string"?u.stderr.trim():Buffer.isBuffer(u.stderr)?u.stderr.toString("utf8").trim():"";throw new Tn(t,e,d,{cause:u,timedOut:Uk(u)})}}var Wk,Bk,Tn,cc=z(()=>{"use strict";Tr();Wk=6e4,Bk=8*1024*1024,Tn=class extends Error{constructor(n,r,i,s){super(`${n} ${r.join(" ")} failed${i?`: ${i}`:""}`,s);this.command=n;this.args=r;this.stderr=i;this.name="ExternalCommandError",this.timedOut=s?.timedOut===!0}command;args;stderr;timedOut}});import{promises as Gf}from"node:fs";import Yf from"node:path";function Ob(t){let e=gc.get(t);if(!e)return;let n=e.value===null?Ab:Pb;if(Date.now()-e.at>n){gc.delete(t);return}return e.value}async function wc(t){if(t===process.pid&&hc!==null)return hc;let e=Ob(t);if(e!==void 0)return e;let n=await Nb(t);return t===process.pid&&n!==null&&(hc=n),t!==process.pid&&gc.set(t,{value:n,at:Date.now()}),n}async function Nb(t){if(!Number.isSafeInteger(t)||t<=0)return null;try{if(process.platform==="linux"){let[e,n]=await Promise.all([Gf.readFile(`/proc/${t}/stat`,"utf8"),Gf.readFile("/proc/sys/kernel/random/boot_id","utf8")]),r=e.slice(e.lastIndexOf(")")+2).trim().split(/\s+/u)[19];return/^\d+$/u.test(r??"")?`linux:${n.trim()}:${r}`:null}if(process.platform==="win32")return await Ib(t);if(process.platform==="darwin"){let e=Ln("/bin/ps",["-p",String(t),"-o","lstart="],{timeoutMs:5e3,maxBufferBytes:4096,env:{...process.env,LC_ALL:"C",TZ:"UTC0"}}).trim();return e?`darwin:${e}`:null}}catch{}return null}function jb(t){let e=t.trim();return/^\d+$/u.test(e)?`win32-ps:${e}`:null}async function Ib(t){try{let i=Ln(Yf.win32.join(process.env.SystemRoot??"C:\\Windows","System32","wbem","WMIC.exe"),["process","where",`processid=${t}`,"get","creationdate","/value"],{timeoutMs:5e3,maxBufferBytes:4096}),s=/^CreationDate=(\S+)/mu.exec(i);if(s)return`win32-wmic:${s[1]}`}catch{}let e=process.env.SystemRoot??"C:\\Windows",n=Yf.win32.join(e,"System32","WindowsPowerShell","v1.0","powershell.exe"),r=Ln(n,["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${t} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:8e3,maxBufferBytes:4096}).trim();return jb(r)}function Rs(t){let e=t.indexOf(":");return e===-1?"":t.slice(0,e)}async function Xf(t,e){if(!Number.isSafeInteger(t)||t<=0)return"alive";try{process.kill(t,0)}catch(r){if(r.code==="ESRCH")return"dead"}if(!e)return"unknown";let n=await wc(t);return n===e?"alive":n===null||Rs(n)!==Rs(e)&&Vf.has(Rs(n))&&Vf.has(Rs(e))?"unknown":"dead"}var hc,Pb,Ab,gc,Vf,Qf=z(()=>{"use strict";cc();hc=null,Pb=6e4,Ab=1e4,gc=new Map;Vf=new Set(["win32-wmic","win32-ps"])});import{randomUUID as $b}from"node:crypto";import{promises as fn}from"node:fs";import em from"node:os";import Zf from"node:path";async function tm(t,e,n={}){let r=Zf.resolve(t);await fn.mkdir(Zf.dirname(r),{recursive:!0});let i=Date.now(),s=n.timeoutMs??Tb,o=n.retryMs??Lb,a=n.malformedLockStaleMs??qb,c=await wc(process.pid),l={pid:process.pid,nonce:$b(),createdAt:Date.now(),hostname:em.hostname(),...c===null?{}:{processIdentity:c}},u=!1;for(;!u;){let d;try{d=await fn.open(r,"wx"),await d.writeFile(JSON.stringify(l),"utf8"),u=!0}catch(f){if(f.code!=="EEXIST")throw f;if(await Fb(r,a))continue;if(Date.now()-i>=s)throw new Error(`Timed out waiting for file lock: ${r}`,{cause:f});await new Promise(p=>setTimeout(p,o))}finally{await d?.close()}}try{return await e()}finally{await Db(r,l.nonce)}}async function Fb(t,e){let n,r;try{[n,r]=await Promise.all([fn.readFile(t,"utf8"),fn.stat(t)])}catch(s){return s.code==="ENOENT"}let i=nm(n);if(i!==null&&(i.hostname!==void 0&&i.hostname!==em.hostname()||await Xf(i.pid,i.processIdentity)!=="dead"))return!1;if(i===null){let s=n.trim().length===0?Mb:e;if(Date.now()-Number(r.mtimeMs)<s)return!1}try{return await fn.readFile(t,"utf8")!==n?!1:(await fn.rm(t),!0)}catch(s){return s.code==="ENOENT"}}async function Db(t,e){try{if(nm(await fn.readFile(t,"utf8"))?.nonce!==e)return;await ai(t)}catch(n){let r=n.code;if(r==="ENOENT")return;process.stderr.write(`[comet] warning: could not remove lock file ${t} (${r??n}); it will be recovered automatically
|
|
143
|
-
`)}}function nm(t){try{let e=JSON.parse(t);return Number.isSafeInteger(e.pid)&&Number(e.pid)>0&&typeof e.nonce=="string"&&e.nonce.length>0&&typeof e.createdAt=="number"&&Number.isFinite(e.createdAt)&&(e.hostname===void 0||typeof e.hostname=="string"&&e.hostname.length>0)&&(e.processIdentity===void 0||typeof e.processIdentity=="string"&&e.processIdentity.length>0)?{pid:Number(e.pid),nonce:e.nonce,createdAt:e.createdAt,...e.hostname===void 0?{}:{hostname:e.hostname},...e.processIdentity===void 0?{}:{processIdentity:e.processIdentity}}:null}catch{return null}}var Tb,Lb,qb,Mb,rm=z(()=>{"use strict";oo();Qf();Tb=3e4,Lb=20,qb=5*6e4,Mb=1e4});var Ps=z(()=>{"use strict"});var im=z(()=>{"use strict"});var yc=z(()=>{"use strict";Ps()});var sm=z(()=>{"use strict";Ps();yc()});function zb(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function Jb(t){let e=(0,om.parseDocument)(t,{uniqueKeys:!0});if(e.errors.length>0)throw new Error(`Invalid global Comet config: ${e.errors[0].message}`);let n=e.toJS();if(n==null)return{};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid global Comet config: root must be a mapping");return n}function cm(t){if(t.native?.pending_root_move)throw new Error("Global Comet config cannot contain native.pending_root_move");let e=t.native?(({pending_root_move:n,...r})=>r)(t.native):void 0;return{...t,schema:"comet.global.v1",...e?{native:e}:{}}}function Gb(t){let e=Pt(JSON.stringify({...t,schema:"comet.project.v1"})).config;if(!e)throw new Error("Invalid global Comet config: workflow template is incomplete");return cm(e)}function Yb(t){let e=Pt(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e.native&&!e.classic)return null;let n=e.native?"native":"classic",r=e.native?.language??e.classic?.language??"en",i=Ja(e.native?.artifact_root??"docs",r);return{schema:"comet.global.v1",default_workflow:n,workflows:[n],ambient_resume:e.ambient_resume,...e.native?{native:{...i.native,...e.native}}:{},...e.classic?{classic:e.classic}:{}}}function lm(t){let e=Jb(t);if(Object.keys(e).length===0)return null;if(e.schema===void 0)return Yb(t);if(e.schema!=="comet.global.v1")throw new Error("Unsupported Comet global schema");return Gb(e)}async function vc(t){try{let e=await Y(t,am,$n,{label:"global Comet config"});return lm(e.bytes.toString("utf8"))}catch(e){if(zb(e))return null;throw e}}var om,am,kc=z(()=>{"use strict";om=_e(Se(),1);it();Ye();le();am=".comet/config.yaml"});var NA,um=z(()=>{"use strict";it();le();NA=4*1024*1024});function fm(t,e){let n=t;for(let r of e)n+="\0"+(typeof r=="string"?r:JSON.stringify(r));return n}function mm(t,e){return(...n)=>{let r=dm;if(r===null)return e(...n);let i=fm(`async:${t}`,n),s=r.entries.get(i);if(s)return s.value;let o=e(...n).catch(a=>{throw r.entries.delete(i),a});return r.entries.set(i,{value:o}),o}}function bc(t,e){return(...n)=>{let r=dm;if(r===null)return e(...n);let i=fm(`sync:${t}`,n),s=r.entries.get(i);if(s)return s.value;let o=e(...n);return r.entries.set(i,{value:o}),o}}var dm,Cc=z(()=>{"use strict";dm=null});var LA,pm=z(()=>{"use strict";Cc();$t();LA=mm("hookWritePolicy",async t=>(await ec(t))?.hook??{allow_paths:[]})});var Vb,hm=z(()=>{"use strict";Va();Vb=16*1024});var gm=z(()=>{"use strict";Ps();it();im();sm();Ye();kc();le();$t();rc();um();pm();hm();tc();yc()});import{TextDecoder as Xb}from"util";function wm(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function Qb(t,e){try{return new Xb("utf-8",{fatal:!0}).decode(t.bytes)}catch(n){throw new Error(`${e} is not valid UTF-8`,{cause:n})}}async function Sc(t,e,n,r,i={}){try{let s=await Y(t,e,n,{label:r,hooks:i.hooks});return{result:s,text:Qb(s,r)}}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw s}}async function dt(t,e,n,r,i={}){return(await Sc(t,e,n,r,i))?.text??null}async function Dt(t,e,n,r,i,s={}){if(Buffer.byteLength(n,"utf8")>r)throw new Error(`${i} exceeds ${r} bytes`);let o=await Sc(t,e,r,i),a=await J(t,e,{label:i,expected:"file"});await we(a.target,n,{containedRoot:a.projectRoot,beforeCommit:async()=>{await s.beforeCommit?.();let c=await Sc(t,e,r,i);if(!(!o&&!c)){if(!o||!c)throw new Error(`${i} changed before commit`);if(o.result.realPath!==c.result.realPath||!gt(wm(o.result.stat),wm(c.result.stat))||o.text!==c.text)throw new Error(`${i} changed before commit`)}}})}async function As(t,e,n,r,i,s={}){let o=await dt(t,e,r,i);await Dt(t,e,`${o??""}${n}`,r,i,s)}async function Os(t,e,n,r={}){let i=await J(t,e,{label:n,expected:"file"});return i.exists?Cn(i.target,{containedRoot:i.projectRoot,beforeRemove:r.beforeRemove}):!1}var Ns=z(()=>{"use strict";gm();ci()});var km={};dh(km,{RUN_STATE_FILE:()=>js,applyRunStateToDocument:()=>Ec,readRunState:()=>Is,removeRunState:()=>Jr,runStateFromDocument:()=>Dn,writeRunState:()=>Wn});import Zb from"path";function zr(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return n}function Hr(t,e){let n=zr(t,e);if(Zb.isAbsolute(n)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return n}function eC(t){let e=t.run_retries??"{}",n;try{n=typeof e=="string"?JSON.parse(e):e}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(n))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return n}function Dn(t){if(!t.run_id)return null;let e=zr(t,"run_id"),n=zr(t,"skill"),r=zr(t,"skill_version"),i=zr(t,"skill_hash"),s=Hr(t,"pending_ref"),o=Hr(t,"trajectory_ref"),a=Hr(t,"context_ref"),c=Hr(t,"artifacts_ref"),l=Hr(t,"checkpoint_ref"),u=Number(t.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:n,skillVersion:r,skillHash:i,orchestration:t.orchestration,currentStep:ym(t,"current_step"),iteration:u,pending:ym(t,"pending"),pendingRef:s,trajectoryRef:o,contextRef:a,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:eC(t)}}function Ec(t,e){e?t.run_id=e.runId:delete t.run_id}function tC(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,currentStep:t.currentStep,iteration:t.iteration,pending:t.pending,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,status:t.status,retries:t.retries}}function nC(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)};return Dn(e)}async function Is(t,e={}){let n=await dt(t,js,vm,"Run state",e);if(n===null)return null;let r=JSON.parse(n);return nC(r)}async function Wn(t,e,n={}){await Dt(t,js,JSON.stringify(tC(e),null,2),vm,"Run state",n)}async function Jr(t,e={}){await Os(t,js,"Run state",e)}var ym,js,vm,$s=z(()=>{"use strict";Ns();ym=(t,e)=>{let n=t[e];return n==null?null:String(n)};js=".comet/run-state.json",vm=Number.MAX_SAFE_INTEGER});import{spawn as ES}from"node:child_process";import Bc from"node:path";async function hp(t){let e=t.pid;if(e===void 0){t.kill("SIGKILL");return}if(process.platform==="win32"){let n=process.env.SystemRoot??process.env.WINDIR,r=n&&Bc.win32.isAbsolute(n)?Bc.win32.resolve(n):"C:\\Windows",i=Bc.win32.join(r,"System32","taskkill.exe"),s=()=>new Promise(o=>{let a=!1,c=null,l=null,u=(d,f=!1)=>{a||(a=!0,l&&clearTimeout(l),f&&c?.kill("SIGKILL"),o(d))};try{c=ES(i,["/pid",String(e),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>u(!1)),c.once("close",d=>u(d===0)),l=setTimeout(()=>u(!1,!0),xS)}catch{u(!1)}});for(let o=0;o<_S;o+=1)if(await s()){t.kill("SIGKILL");return}t.kill("SIGKILL"),t.stdin?.destroy(),t.stdout?.destroy(),t.stderr?.destroy();return}try{process.kill(-e,"SIGKILL")}catch(n){if(n.code!=="ESRCH")throw n}t.kill("SIGKILL")}var xS,_S,gp=z(()=>{"use strict";xS=1e3,_S=2});import{createHash as pE}from"crypto";import{promises as hE}from"fs";it();Ye();le();import Rr from"path";var Za=Number.MAX_SAFE_INTEGER;function ms(t,e,n){let r=Rr.resolve(t),i=Rr.isAbsolute(e)?Rr.resolve(e):Rr.resolve(r,e),s=Rr.relative(r,i).replaceAll("\\","/");return{root:r,relative:de(s,n),target:i}}async function fe(t,e,n){let r=ms(t,e,n.label);return J(r.root,r.relative,n)}async function G(t,e,n){return(await fe(t,e,{label:n.label,expected:n.expected??"any"})).exists}async function Pe(t,e,n,r){return await G(t,e,{label:n,expected:"file"})?(await ps(t,e,{label:n,hooks:r})).byteLength>0:!1}async function I(t,e,n){return(await ps(t,e,n)).toString("utf8")}async function ps(t,e,n){let r=ms(t,e,n.label);return(await Y(r.root,r.relative,n.maxBytes??Za,{label:n.label,hooks:n.hooks})).bytes}async function Pr(t,e,n){let r=ms(t,e,n);return Xa(r.root,r.relative,{label:n})}async function It(t,e,n,r){let i=ms(t,e,r.label);await J(i.root,i.relative,{label:r.label,expected:"file"}),await we(i.target,n,{containedRoot:i.root,beforeTemporaryOpen:r.beforeTemporaryOpen,beforeCommit:r.beforeCommit,exclusive:r.exclusive})}function Ar(t){if(t.workflow!=="full")return{missingFields:[],invalidFields:[]};let e=[],n=[];return t.buildMode||e.push("build_mode"),t.tddMode||e.push("tdd_mode"),t.reviewMode||e.push("review_mode"),t.buildMode==="subagent-driven-development"&&t.subagentDispatch!=="confirmed"&&e.push("subagent_dispatch"),t.buildMode==="autonomous"&&t.reviewMode==="off"&&n.push({field:"review_mode",reason:"autonomous full build requires review_mode=standard or thorough"}),t.buildMode==="direct"&&t.directOverride!==!0&&n.push({field:"direct_override",reason:"full workflow direct execution requires direct_override=true"}),{missingFields:e,invalidFields:n}}function mf(t){let e=Ar(t);return e.missingFields.length===0&&e.invalidFields.length===0}var kf=_e(Se(),1);import{promises as wf}from"fs";import X from"path";import{promises as pk}from"fs";async function Or(t){try{return await pk.access(t),!0}catch(e){if(hk(e))return!1;throw e}}function hk(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}Ye();$t();rc();le();var jr=class extends Error{code="classic-layout-unavailable";constructor(e="Classic artifact layout is unavailable from .comet/config.yaml"){super(e),this.name="ClassicLayoutUnavailableError"}},gf=".comet/config.yaml";function yf(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function vf(t){await J(t,gf,{label:gf,expected:"file"})}function gs(t,e){let n=X.resolve(t),r=e==="docs"?X.join(n,"docs"):n,i=X.join(r,"openspec"),s=X.join(n,"docs","superpowers");return{projectRoot:n,artifactLayout:e,openSpecBase:r,openSpecRoot:i,changesDir:X.join(i,"changes"),archiveDir:X.join(i,"changes","archive"),specsDir:X.join(i,"specs"),superpowersRoot:s,superpowersSpecsDir:X.join(s,"specs"),superpowersPlansDir:X.join(s,"plans"),superpowersReportsDir:X.join(s,"reports")}}async function Ek(t){await vf(t);let e=await ct(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e?.config)throw new jr;if(!(e.config.workflows??[e.config.default_workflow]).includes("classic"))throw new jr("Classic artifact layout is unavailable because Classic is not enabled");return e.classic?.artifact_layout??"legacy"}async function ic(t,e){return gs(t,e??await Ek(t))}async function xk(t){try{return await wf.lstat(t),!0}catch(e){if(yf(e))return!1;throw e}}async function _k(t,e){let n=await ic(t,e),r=n.artifactLayout==="legacy"?"docs":"legacy",i=gs(t,r).openSpecRoot,[s,o]=await Promise.all([J(n.projectRoot,K(n.projectRoot,n.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),xk(i)]),a=s.exists;return{paths:n,configuredRootExists:a,alternateRoot:i,alternateRootExists:o,dualRoots:a&&o}}async function Rk(t){let e=[t.openSpecRoot,t.changesDir,t.archiveDir,t.specsDir,t.superpowersRoot,t.superpowersSpecsDir,t.superpowersPlansDir,t.superpowersReportsDir];for(let n of e){let r=K(t.projectRoot,n);await J(t.projectRoot,r,{label:`Classic managed physical path ${r}`,expected:"directory"})}}async function ue(t,e){let n=await _k(t,e);if(await Rk(n.paths),!n.configuredRootExists){let r=K(n.paths.projectRoot,n.paths.openSpecRoot),i=K(n.paths.projectRoot,n.alternateRoot);throw new jr(`Configured Classic OpenSpec root is missing: ${r} (alternate ${i} is ${n.alternateRootExists?"present":"missing"})`)}return n.paths}async function on(t,e){let n=X.join(X.resolve(t),".comet","classic-root-move.json");if(await Or(n))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let r=await ue(t,e);if(!await Or(r.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${K(r.projectRoot,r.openSpecRoot)}`);return r}async function lt(t){let e=X.resolve(t),n=null;try{(await wf.lstat(e)).isDirectory()||(e=X.dirname(e))}catch(r){if(!yf(r))throw r}for(;;){X.basename(e)==="openspec"&&(n=X.dirname(e));let r=X.join(e,".comet","config.yaml"),i=!1;if(await Or(r))try{await vf(e);let o=(await ct(e))?.value;i=!!o&&typeof o=="object"&&!Array.isArray(o)&&(o.schema==="comet.project.v1"||o.default_workflow!==void 0||o.native!==void 0)}catch{}if(i||await Or(X.join(e,".git")))return e;let s=X.dirname(e);if(s===e)return n??X.resolve(t);e=s}}function K(t,e){return X.relative(X.resolve(t),e).replaceAll("\\","/")}import an from"node:path";async function bf(t,e,n,r={}){if(n.workflow!=="full"||n.buildMode!=="autonomous")return[];let i=[];if(r.requirePlan!==!1){let s=Ar(n);s.missingFields.includes("tdd_mode")&&i.push("tdd_mode must be selected for autonomous full build"),s.missingFields.includes("review_mode")&&i.push("review_mode must be selected for autonomous full build"),s.invalidFields.some(({field:o})=>o==="review_mode")&&i.push("review_mode must be standard or thorough for autonomous full build"),n.isolation||i.push("isolation must be selected for autonomous full build")}if(!n.designDoc||!await Pe(t,n.designDoc,"Classic autonomous design"))i.push("design_doc must reference a nonempty technical design for autonomous full build");else{let o=(await I(t,n.designDoc,{label:"Classic autonomous design"})).replace(/^\uFEFF/u,"").match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u),a=o?(0,kf.parseDocument)(o[1]):null;(!a||a.errors.length||a.get("comet_change")!==e||a.get("role")!=="technical-design"||a.get("canonical_spec")!=="openspec")&&i.push("design_doc must link the current change and declare role: technical-design and canonical_spec: openspec")}return r.requirePlan!==!1&&(await Ir(t,n.plan,{requireNonempty:!0})).status!=="ready"&&i.push("plan must reference a nonempty implementation plan in the configured plans directory"),i}async function Ir(t,e,n={}){if(!e||e==="null")return{status:"missing",recordedPath:null};let r=await ue(t),i=an.resolve(t,e),s=an.relative(r.superpowersPlansDir,i);return an.isAbsolute(e)||!s||s.startsWith(`..${an.sep}`)||an.isAbsolute(s)||s.includes(an.sep)||an.extname(s).toLowerCase()!==".md"?{status:"broken",recordedPath:e}:await G(t,e,{label:`Classic build plan ${e}`,expected:"file"})&&(!n.requireNonempty||(await I(t,e,{label:`Classic build plan ${e}`})).trim().length>0)?{status:"ready",recordedPath:e}:{status:"broken",recordedPath:e}}import{stripVTControlCharacters as Pk}from"node:util";function Tt(t,e={}){return{code:"CLASSIC_COMMAND_FAILED",message:Pk(t instanceof Error?t.message:String(t)),...e}}import et from"node:path";import{createHash as Ak,randomUUID as WR}from"node:crypto";var Ok=/^(\s*[-*]\s+\[)([ xX])(\]\s+)(.*)$/u,Nk=/\s*<!-- comet-task:([a-zA-Z0-9][a-zA-Z0-9_-]{0,79}) -->\s*$/u;function Ae(t){let e=[],n=new Set,r=null;for(let[i,s]of t.split(/\r?\n/u).entries()){let o=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(s);if(o){r?o[1][0]===r.marker&&o[1].length>=r.length&&!o[2].trim()&&(r=null):r={marker:o[1][0],length:o[1].length};continue}if(r)continue;let a=Ok.exec(s);if(!a)continue;let c=Nk.exec(a[4]),l=c?.[1]??null;if(a[4].includes("<!-- comet-task:")&&(!c||a[4].slice(0,c.index).includes("<!-- comet-task:")))throw new Error(`Malformed Classic task ID at line ${i+1}`);if(l&&n.has(l))throw new Error(`Duplicate Classic task ID: ${l}`);l&&n.add(l);let u=a[4].slice(0,c?.index).trim();if(!u)throw new Error(`Empty Classic task at line ${i+1}`);e.push({id:l,text:u,completed:a[2].toLowerCase()==="x",line:i+1})}return e}function $r(t){let e=t.split(/(?<=\n)/u);for(let n of Ae(t))e[n.line-1]=e[n.line-1].replace(/^(\s*[-*]\s+\[)[ xX](\])/u,"$1 $2");return e.join("")}function ws(t){return Ak("sha256").update($r(t)).digest("hex")}function ys(t,e){let n=Ae(t),r=new Set(e.map(i=>i.id).filter(Boolean));return{total:n.length,unmapped:n.filter(i=>!i.id||!r.has(i.id))}}function Cf(t,e,n){let r=[...t.matchAll(/^<!-- comet-task-authority: (.+) -->$/gmu)];if(!r.length)return"legacy";if(r.length!==1||r[0][1]!==e)throw new Error("Plan task authority must point to this change tasks.md");if(Ae(t).length)throw new Error("Canonical plan must reference tasks, not maintain a second checkbox ledger");if(!n.length||n.some(o=>!o.id))throw new Error("Canonical plan requires stable task IDs");let i=new Set([...t.matchAll(/<!-- comet-task-ref:([a-zA-Z0-9][a-zA-Z0-9_-]{0,79}) -->/gu)].map(o=>o[1])),s=new Set(n.map(o=>o.id));if([...i].some(o=>!s.has(o)))throw new Error("Plan references a missing task ID; update the plan mapping");if(n.some(o=>!i.has(o.id)))throw new Error("Plan must reference each task ID; update the plan mapping");return"canonical"}var Nf=_e(Se(),1);cc();import Ve from"node:path";import{createHash as bs,randomUUID as eP}from"node:crypto";var Kk=new Set(["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_GRAFT_FILE","GIT_SHALLOW_FILE","GIT_PREFIX","GIT_IMPLICIT_WORK_TREE","GIT_NO_REPLACE_OBJECTS","GIT_REPLACE_REF_BASE","GIT_CONFIG","GIT_CONFIG_PARAMETERS","GIT_CONFIG_COUNT"]);function Hk(t=process.env){return Object.fromEntries(Object.entries(t).filter(([e])=>{let n=e.toUpperCase();return!Kk.has(n)&&!/^GIT_CONFIG_(KEY|VALUE)_\d+$/u.test(n)}))}function _f(t){return{...Hk(t.environment),...t.authentication?{}:{GIT_CONFIG_GLOBAL:process.platform==="win32"?"NUL":"/dev/null",GIT_CONFIG_NOSYSTEM:"1"},GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never",SSH_ASKPASS_REQUIRE:"never",GIT_NO_REPLACE_OBJECTS:"1",GH_PROMPT_DISABLED:"1"}}var Rf=["implementing","task-review","checkoff","done","blocked"];function Lt(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Classic progress requires a JSON object");return t}function Cs(t,e){let n=Object.keys(t).filter(r=>!e.includes(r));if(n.length)throw new Error(`Unknown Classic progress field(s): ${n.join(", ")}; allowed fields: ${e.join(", ")}`)}function Le(t,e){if(typeof t!="string"||!t.trim()||t.length>4096||[...t].some(n=>n.charCodeAt(0)<32||n.charCodeAt(0)===127))throw new Error(`Invalid Classic progress ${e}`);return t}function lc(t,e){if(!Array.isArray(t)||t.length>200)throw new Error(`Invalid Classic progress ${e}`);return t.map(n=>Le(n,e))}function zk(t){let e=Lt(t);if(Cs(e,["schemaVersion","taskIds","revision","stage","sessionId","evidence","unresolved","reviewRounds"]),e.schemaVersion!==1)throw new Error("Unsupported Classic checkpoint schemaVersion");let n=lc(e.taskIds,"taskIds");if(!n.length||new Set(n).size!==n.length||n.some(r=>!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}$/u.test(r)))throw new Error("Classic checkpoint taskIds must be unique stable IDs");if(typeof e.revision!="string"||!/^[a-f0-9]{64}$/u.test(e.revision))throw new Error("Invalid Classic checkpoint revision");if(!Rf.includes(e.stage))throw new Error(`Invalid Classic checkpoint stage '${String(e.stage)}'; stages: ${Rf.join("|")}`);if(!Number.isSafeInteger(e.reviewRounds)||e.reviewRounds<0)throw new Error("Invalid Classic checkpoint reviewRounds");return{schemaVersion:1,taskIds:n,revision:e.revision,stage:e.stage,sessionId:Le(e.sessionId,"sessionId"),evidence:lc(e.evidence,"evidence"),unresolved:lc(e.unresolved,"unresolved"),reviewRounds:e.reviewRounds}}async function jf(t,e,n){let r=Ve.join(e,".comet",n);if(await G(t,r,{label:"Classic progress",expected:"file"}))return JSON.parse(await I(t,r,{label:"Classic progress"}))}function Jk(t,e){let n=bs("sha256").update(e).digest("hex");return Ve.join(t,".comet","runtime","classic-delivery",`${n}.json`)}async function Gk(t,e){let n=Jk(t,e);if(!await G(t,n,{label:"Classic delivery reauthorization",expected:"file"}))return null;let r=Lt(JSON.parse(await I(t,n,{label:"Classic delivery reauthorization"})));if(Cs(r,["schemaVersion","changeIdentity","previousAuthorizationId","authorizationId","action","targetBranch","remote","authorizedRemoteUrl"]),r.schemaVersion!==1||r.changeIdentity!==e)throw new Error("Classic delivery reauthorization identity is invalid");let i=dc({action:r.action,targetBranch:r.targetBranch,...r.remote===void 0?{}:{remote:r.remote}},!0);if(i.commit!==void 0||i.prUrl!==void 0)throw new Error("Classic delivery reauthorization cannot change sealed commit or PR evidence");return{schemaVersion:1,changeIdentity:e,previousAuthorizationId:Le(r.previousAuthorizationId,"previousAuthorizationId"),authorizationId:Le(r.authorizationId,"authorizationId"),...i,...r.authorizedRemoteUrl===void 0?{}:{authorizedRemoteUrl:Le(r.authorizedRemoteUrl,"authorizedRemoteUrl")}}}async function If(t,e,n){let r=await jf(t,e,"coordination.json");if(r===void 0)return{checkpoint:null,stale:!1};let i=zk(r),s=new Set(Ae(n).map(o=>o.id));return{checkpoint:i,stale:i.revision!==ws(n)||i.taskIds.some(o=>!s.has(o))}}function dc(t,e=!1){let n=Lt(t);if(Cs(n,["action","targetBranch","remote","commit","prUrl",...e?["schemaVersion","changeIdentity","authorizedRemoteUrl","authorizationId"]:[]]),!["local","push","pr"].includes(n.action))throw new Error(`Invalid Classic delivery action '${String(n.action)}'; actions: local|push|pr`);let r=Le(n.targetBranch,"targetBranch");if(r.startsWith("-")||/[~^:?*[\\\s]/u.test(r)||r.includes("..")||r.includes("@{"))throw new Error("Invalid Classic delivery targetBranch");let i={action:n.action,targetBranch:r};if(n.remote!==void 0){let s=Le(n.remote,"remote");if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/u.test(s))throw new Error("Classic delivery remote must be a name, not a URL");i.remote=s}if(n.commit!==void 0){let s=Le(n.commit,"commit");if(!/^(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/u.test(s))throw new Error("Classic delivery commit must be a full object ID");i.commit=s.toLowerCase()}if(n.prUrl!==void 0){let s=Le(n.prUrl,"prUrl"),o=new URL(s);if(o.protocol!=="https:"||o.username||o.password)throw new Error("Invalid Classic delivery prUrl");i.prUrl=s}return i}function $f(t){let e=(0,Nf.parseDocument)(t,{uniqueKeys:!0});if(e.errors.length)throw new Error("Invalid Classic delivery change state");return Lt(e.toJS())}function Tf(t,e){if(typeof t.run_id=="string"&&t.run_id)return`run:${t.run_id}`;let n=t.archived===!0?Ve.basename(e).replace(/^\d{4}-\d{2}-\d{2}-/u,""):Ve.basename(e);if(typeof t.created_at!="string"||typeof t.base_ref!="string")throw new Error("Classic delivery requires stable change identity");return`legacy:${bs("sha256").update(JSON.stringify([n,t.created_at,t.base_ref])).digest("hex")}`}async function Yk(t,e){return $f(await I(t,Ve.join(e,".comet.yaml"),{label:"Classic delivery state"}))}var ks=class extends Error{constructor(e,n){super(`Classic delivery git command timed out: ${[e,...n].join(" ")}`)}};function uc(t,e,n,r){return Ln(e,n,{cwd:t,timeoutMs:5e3,env:_f({authentication:r})}).trim()}function Mr(t,e,n,r=!1){try{return uc(t,e,n,r)}catch{return null}}function Vk(t,e,n,r=!1){try{return uc(t,e,n,r)}catch(i){if(!(i instanceof Tn)||!i.timedOut)return null;try{return uc(t,e,n,r)}catch(s){if(s instanceof Tn&&s.timedOut)throw new ks(e,n);return null}}}function Lr(t,e){return Mr(t,"git",["-C",t,...e])}function qr(t,e){return Vk(t,"git",["-C",t,...e])}function Pf(t,e,n=!1){return Mr(t,"git",["-C",t,"remote","get-url",...n?["--push"]:[],e],!0)}function Xk(t,e){let n=Ve.relative(t,e).replaceAll("\\","/");return[`:(literal)${n}`,...[".comet-state.lock",".comet-state-transaction.json"].map(r=>`:(exclude,literal)${n}/${r}`)]}function Af(t,e,n,r){let i=Ve.relative(t,e).replaceAll("\\","/"),s=Xk(t,e),o=qr(t,["show",`${n}:${i}/.comet.yaml`]);if(!o)return!1;try{let a=$f(o);return a.archived===!0&&Tf(a,e)===r&&qr(t,["merge-base","--is-ancestor",n,"HEAD"])!==null&&qr(t,["diff","--quiet","--no-ext-diff","--no-textconv",n,"--",...s])!==null&&qr(t,["ls-files","--others","--exclude-standard","--",...s])===""}catch(a){if(a instanceof ks)throw a;return!1}}function Qk(t,e){let n=`${bs("sha256").update(e).digest("hex")}.json`,r=qr(t,["rev-parse","--path-format=absolute","--git-common-dir"]);return[{root:t,file:Ve.join(t,".comet","classic-deliveries",n)},...r?[{root:r,file:Ve.join(r,"comet","classic-deliveries",n)}]:[]]}async function Zk(t,e){let n=null;for(let r of Qk(t,e)){if(!await G(r.root,r.file,{label:"Classic delivery receipt",expected:"file"}))continue;let i=Lt(JSON.parse(await I(r.root,r.file,{label:"Classic delivery receipt"})));if(Cs(i,["schemaVersion","changeIdentity","authorizationId","invalidated","commit","prUrl"]),i.schemaVersion!==1||i.changeIdentity!==e)throw new Error("Invalid Classic delivery receipt schema or identity");if(i.invalidated!==void 0&&typeof i.invalidated!="boolean")throw new Error("Invalid Classic delivery receipt invalidation");let s=dc({action:"local",targetBranch:"main",...i.commit!==void 0?{commit:i.commit}:{},...i.prUrl!==void 0?{prUrl:i.prUrl}:{}}),o={schemaVersion:1,changeIdentity:e,authorizationId:Le(i.authorizationId,"authorizationId"),...i.invalidated===!0?{invalidated:!0}:{},...s.commit?{commit:s.commit}:{},...s.prUrl?{prUrl:s.prUrl}:{}};if(n&&JSON.stringify(n)!==JSON.stringify(o))throw new Error("Conflicting Classic delivery receipts");n=o}return n}function eb(t){return t.authorizationId===void 0?`legacy:${bs("sha256").update(JSON.stringify(t)).digest("hex")}`:Le(t.authorizationId,"authorizationId")}function Of(t,e,n){return e===n||Lr(t,["merge-base","--is-ancestor",e,n])!==null}function tb(t){let e=/^git@([^:/]+):([^/]+\/[^/]+)$/u.exec(t);try{let n=new URL(e?`ssh://git@${e[1]}/${e[2]}`:t);if(!["https:","ssh:"].includes(n.protocol)||n.password||n.search||n.hash||n.port||n.protocol==="https:"&&n.username)return null;let r=n.pathname.replace(/\.git\/?$/u,"").replace(/\/$/u,"").split("/").filter(Boolean);return r.length!==2||r.some(i=>!/^[a-zA-Z0-9_.-]+$/u.test(i))?null:`${n.hostname}/${r.join("/")}`.toLowerCase()}catch{return null}}function vs(t,e){try{let n=new URL(t);if(n.protocol!=="https:"||n.username||n.password||n.port||n.search||n.hash)return null;let r=/^\/([^/]+)\/([^/]+)\/pull\/([1-9]\d*)\/?$/u.exec(n.pathname);return r&&`${n.hostname}/${r[1]}/${r[2]}`.toLowerCase()===e?`https://${n.hostname}/${r[1]}/${r[2]}/pull/${r[3]}`:null}catch{return null}}async function Lf(t,e,n={}){let r=await jf(t,e,"delivery.json");if(r===void 0)return{delivery:null,verification:{status:"needsAuthorization"}};let i=Lt(r);if(i.schemaVersion!==1)throw new Error("Unsupported Classic delivery schemaVersion");let s=dc(i,!0),o=await Yk(t,e),a=Tf(o,e);if(i.changeIdentity!==a)throw new Error("Classic delivery change identity mismatch");let c=eb(i),l=await Gk(t,a);if(l&&l.previousAuthorizationId!==c)throw new Error("Classic delivery reauthorization is stale for the sealed authorization");let u=l?{action:l.action,targetBranch:l.targetBranch,...l.remote===void 0?{}:{remote:l.remote}}:s,d=l?.authorizationId??c,f=await Zk(t,a),p=f?.authorizationId===d?f:null;if(p?.invalidated)return{delivery:null,verification:{status:"needsAuthorization",invalidated:!0}};for(let $ of["commit","prUrl"]){if($==="commit"&&p?.[$]&&u[$]&&p[$]!==u[$])throw new Error("Classic delivery receipt conflicts with authorization evidence");p?.[$]&&(u[$]=p[$])}let g=i.authorizedRemoteUrl===void 0?void 0:Le(i.authorizedRemoteUrl,"authorizedRemoteUrl"),m=l?.authorizedRemoteUrl??g,h={...u,schemaVersion:1,changeIdentity:a,authorizationId:d,...m?{authorizedRemoteUrl:m}:{}},v=Lr(t,["symbolic-ref","--quiet","--short","HEAD"]),y=Ve.relative(t,e).replaceAll("\\","/"),S=null;!u.commit&&o.archived===!0&&(S=Lr(t,["log","-20","--format=%H","HEAD","--",`:(literal)${y}/.comet.yaml`])?.split(/\r?\n/u).find(B=>/^[a-f0-9]{40,64}$/u.test(B)&&Af(t,e,B,a))??null);let b=u.commit??S,x=!!b&&Lr(t,["cat-file","-t",b])==="commit",w=o.archived===!0&&x&&Af(t,e,b,a),C=v===u.targetBranch&&(!o.bound_branch||l!==null||o.bound_branch===v)&&w,k=!1,_=!1,P=null,O=n.verifyRemote&&u.action!=="local"?"unavailable":"notChecked",R="notChecked";if(n.verifyRemote&&C&&u.action!=="local"&&u.remote&&m&&Pf(t,u.remote)===m&&Pf(t,u.remote,!0)===m){let $=`refs/heads/${u.targetBranch}`,B=Mr(t,"git",["-C",t,"-c","protocol.allow=never","-c","protocol.https.allow=always","-c","protocol.ssh.allow=always","-c","protocol.file.allow=always","ls-remote","--refs",u.remote,$],!0),L=B?.split(/\r?\n/u)??[],U=L.length===1?/^([a-f0-9]{40}|[a-f0-9]{64})\t(.+)$/u.exec(L[0]):null,Z=U?.[2]===$?U[1]:null;k=!!b&&!!Z&&Of(t,b,Z),O=k?"verified":B===""?"missing":B===null||!Z||Lr(t,["cat-file","-t",Z])!=="commit"?"unavailable":"missing";let ne=tb(m),Vt=ne&&u.prUrl?vs(u.prUrl,ne):null,Fe=k||B==="",si=ge=>ge.headRefName===u.targetBranch&&typeof ge.headRefOid=="string"&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(ge.headRefOid)&&(k?ge.headRefOid===Z&&["OPEN","MERGED"].includes(ge.state):B===""&&ge.state==="MERGED"&&!!b&&Of(t,b,ge.headRefOid));if(Fe&&u.action==="pr"&&(R="unavailable"),Fe&&u.action==="pr"&&Vt&&ne){let ge=Mr(t,"gh",["pr","view",Vt,"--repo",ne,"--json","url,headRefName,headRefOid,state"],!0);try{let re=ge?Lt(JSON.parse(ge)):null;_=!!re&&typeof re.url=="string"&&vs(re.url,ne)===Vt&&si(re),R=_?"verified":re?"missing":"unavailable"}catch{_=!1,R="unavailable"}}else if(Fe&&u.action==="pr"&&!u.prUrl&&ne){let ge=Mr(t,"gh",["pr","list","--repo",ne,"--head",u.targetBranch,"--state","all","--json","url,headRefName,headRefOid,state","--limit","100"],!0);try{let re=ge===null?null:JSON.parse(ge);if(!Array.isArray(re)||re.length>=100)throw new Error("Incomplete PR discovery");let Xt=re.map(Lt).filter(De=>typeof De.url=="string"&&vs(De.url,ne)&&si(De));Xt.length===1?(P=vs(Xt[0].url,ne),_=!0,R="verified"):R=Xt.length===0?"missing":"unavailable"}catch{R="unavailable"}}}return{delivery:h,verification:{status:C&&(u.action==="local"||(u.action==="push"?k:_))?"complete":"needsVerification",currentBranch:v,commitExists:x,archiveCommitted:w,observedCommit:S,observedPrUrl:P,remoteVerified:k,prVerified:_,remoteStatus:O,prStatus:R}}}var fp=_e(Se(),1);import SS from"node:path";import{createHash as cp}from"crypto";import{createHash as nb}from"node:crypto";function Xe(t,e){return t.replaceAll("\\","/").endsWith("/tasks.md")&&(e=$r(e)),nb("sha256").update(e).digest("hex")}import Oe from"node:path";import{createHash as hb}from"node:crypto";import{AsyncLocalStorage as rb}from"async_hooks";import{promises as qf}from"fs";import Fr from"path";var Dr=new rb;function ib(t,e){let n=Fr.relative(t,e);return n===""||!Fr.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${Fr.sep}`)}async function sb(t){let e=Fr.resolve(t.invocationCwd??process.cwd()),n=Fr.resolve(t.projectRoot??await lt(e)),[r,i]=await Promise.all([qf.realpath(e),qf.realpath(n)]);if(!ib(i,r))throw new Error(`Classic command invocation cwd is outside the discovered project: ${e}`);return{invocationCwd:e,projectRoot:n,observations:new Map}}async function ob(t,e){let n=Dr.getStore();if(n)return e(n);let r=await sb(t);return Dr.run(r,()=>e(r))}function T(){let t=Dr.getStore();if(!t)throw new Error("Classic command project context is unavailable");return t.projectRoot}function un(){let t=Dr.getStore();if(!t)throw new Error("Classic command invocation context is unavailable");return t.invocationCwd}async function Mf(t,e){let n=Dr.getStore();if(!n)return e();let r=n.observations.get(t);if(r)return r;let i=e();n.observations.set(t,i);try{return await i}catch(s){throw n.observations.delete(t),s}}function qn(t){return(e,n)=>ob(n,()=>t(e,n))}var Hf=_e(Se(),1);import{spawnSync as ub}from"child_process";Tr();import{existsSync as Ff,readFileSync as ab}from"node:fs";import Mn from"node:path";function cb(t){let e=t.replaceAll(`\r
|
|
142
|
+
`,n)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){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 n=as(e),r=In(n);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=as(e),r=In(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){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:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Hd.Parser=Da});var Vd=E(Cr=>{"use strict";var zd=Ra(),Av=mr(),br=gr(),Ov=xo(),Nv=D(),jv=Fa(),Jd=Wa();function Gd(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new jv.LineCounter||null,prettyErrors:e}}function Iv(t,e={}){let{lineCounter:n,prettyErrors:r}=Gd(e),i=new Jd.Parser(n?.addNewLine),s=new zd.Composer(e),o=Array.from(s.compose(i.parse(t)));if(r&&n)for(let a of o)a.errors.forEach(br.prettifyError(t,n)),a.warnings.forEach(br.prettifyError(t,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function Yd(t,e={}){let{lineCounter:n,prettyErrors:r}=Gd(e),i=new Jd.Parser(n?.addNewLine),s=new zd.Composer(e),o=null;for(let a of s.compose(i.parse(t),!0,t.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new br.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(o.errors.forEach(br.prettifyError(t,n)),o.warnings.forEach(br.prettifyError(t,n))),o}function $v(t,e,n){let r;typeof e=="function"?r=e:n===void 0&&e&&typeof e=="object"&&(n=e);let i=Yd(t,n);if(!i)return null;if(i.warnings.forEach(s=>Ov.warn(i.options.logLevel,s)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:r},n))}function Tv(t,e,n){let r=null;if(typeof e=="function"||Array.isArray(e)?r=e:n===void 0&&e&&(n=e),typeof n=="string"&&(n=n.length),typeof n=="number"){let i=Math.round(n);n=i<1?void 0:i>8?{indent:8}:{indent:i}}if(t===void 0){let{keepUndefined:i}=n??e??{};if(!i)return}return Nv.isDocument(t)&&!r?t.toString(n):new Av.Document(t,r,n).toString(n)}Cr.parse=$v;Cr.parseAllDocuments=Iv;Cr.parseDocument=Yd;Cr.stringify=Tv});var xe=E(B=>{"use strict";var Lv=Ra(),qv=mr(),Mv=aa(),Ba=gr(),Fv=Xn(),Rt=D(),Dv=Ct(),Wv=Z(),Bv=Et(),Uv=xt(),Kv=ss(),Hv=qa(),zv=Fa(),Jv=Wa(),ls=Vd(),Xd=Jn();B.Composer=Lv.Composer;B.Document=qv.Document;B.Schema=Mv.Schema;B.YAMLError=Ba.YAMLError;B.YAMLParseError=Ba.YAMLParseError;B.YAMLWarning=Ba.YAMLWarning;B.Alias=Fv.Alias;B.isAlias=Rt.isAlias;B.isCollection=Rt.isCollection;B.isDocument=Rt.isDocument;B.isMap=Rt.isMap;B.isNode=Rt.isNode;B.isPair=Rt.isPair;B.isScalar=Rt.isScalar;B.isSeq=Rt.isSeq;B.Pair=Dv.Pair;B.Scalar=Wv.Scalar;B.YAMLMap=Bv.YAMLMap;B.YAMLSeq=Uv.YAMLSeq;B.CST=Kv;B.Lexer=Hv.Lexer;B.LineCounter=zv.LineCounter;B.Parser=Jv.Parser;B.parse=ls.parse;B.parseAllDocuments=ls.parseAllDocuments;B.parseDocument=ls.parseDocument;B.stringify=ls.stringify;B.visit=Xd.visit;B.visitAsync=Xd.visitAsync});import Pt from"path";function Qv(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim();if(n.length===0||Pt.posix.isAbsolute(n)||Pt.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be a project-relative path`);if(n===".")return[];let r=n.replaceAll("\\","/").split("/");if(r.some(i=>i===".."))throw new Error(`${e} must stay inside the project root`);if(r.some(i=>i===""||i==="."))throw new Error(`${e} must not contain empty or dot path segments`);return r}function Er(t){let e=Qv(t,"native.artifact_root");return e.length===0?".":e.join("/")}function af(t,e="docs"){let n=t??e;if(n!=="legacy"&&n!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return n}function fe(t,e,n=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim().replaceAll("\\","/");if(r.length===0||Pt.posix.isAbsolute(r)||Pt.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${e} must be relative to its declared path base`);let i=r.split("/");if(i.some(s=>s===".."))throw new Error(`${e} must stay inside its declared path base`);if(i.some(s=>s===""||s==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!n&&/[*?]/u.test(r))throw new Error(`${e} cannot contain wildcards`);return i.join("/")}function lt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function cf(t,e,n){let r=t??e;if(r!=="en"&&r!=="zh-CN")throw new Error(`${n} must be en or zh-CN`);return r}function xr(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>Ua)throw new Error(`${e} exceeds ${Ua} characters`);let n=0;for(let r=0;r<t.length;r+=1)t[r]==="?"?n+=1:t[r]==="*"&&(n+=1,t[r+1]==="*"&&(r+=1));if(n>Ka)throw new Error(`${e} contains more than ${Ka} wildcard tokens`);return t}function nf(t,e,n){if(t===void 0)return[...n];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(r=>xr(r,e)))].sort((r,i)=>r.localeCompare(i,"en"))}function Sr(t,e,n){let r=t??e;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${n} must be a positive integer`);return r}function rf(t,e,n){let r=Sr(t,e,n);if(r>Math.floor(Number.MAX_SAFE_INTEGER/(1024*1024)))throw new Error(`${n} is too large to convert to bytes safely`);return r}function Zv(t){if(t===void 0)return{...Ae,include:[...Ae.include],exclude:[...Ae.exclude]};let e=lt(t,"native.snapshot");return{include:nf(e.include,"native.snapshot.include",Ae.include),exclude:nf(e.exclude,"native.snapshot.exclude",Ae.exclude),max_files:Sr(e.max_files,Ae.max_files,"native.snapshot.max_files"),max_total_bytes:Sr(e.max_total_bytes,Ae.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Sr(e.max_duration_ms,Ae.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:Sr(e.max_selection_records,Ae.max_selection_records,"native.snapshot.max_selection_records")}}function ek(t){if(t===void 0)return;let e=lt(t,"native.pending_root_move"),n=e.id,r=e.from_artifact_root,i=e.to_artifact_root,s=e.stage;if(typeof n!="string"||!/^[a-f0-9-]{8,}$/u.test(n))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof i!="string")throw new Error("native.pending_root_move roots must be strings");if(s!=="copying"&&s!=="ready"&&s!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(e.cleanup!==void 0){let a=lt(e.cleanup,"native.pending_root_move.cleanup"),c=a.kind,l=a.state,u=a.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:n,fromArtifactRoot:Er(r),toArtifactRoot:Er(i),stage:s,...o?{cleanup:o}:{}}}function tk(t){if(t===void 0)return;let e=lt(t,"native.finish");if(e.pull_request===void 0)return{};let n=lt(e.pull_request,"native.finish.pull_request");if(n.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(n.command)||n.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(n.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let r=n.command.map((s,o)=>{if(typeof s!="string"||s.trim().length===0||s.length>4096||/[\0\r\n]/u.test(s))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return s});if(Pt.posix.isAbsolute(r[0])||Pt.win32.isAbsolute(r[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let i=n.timeout_ms??Gv;if(!Number.isSafeInteger(i)||i<1||i>tf)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${tf}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:i}}}function nk(t,e={}){let n=lt(t,"native"),r=n.artifact_root??(e.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let i=n.clarification_mode??"batch";if(i!=="sequential"&&i!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let s=n.archive_confirmation??"automatic";if(s!=="automatic"&&s!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=n.max_verify_failures??sf;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let a=n.document_writes??"allow";if(a!=="allow"&&a!=="revert")throw new Error("native.document_writes must be allow or revert");let c=ek(n.pending_root_move),l=tk(n.finish);return{artifact_root:Er(r),language:cf(n.language,"en","native.language"),clarification_mode:i,archive_confirmation:s,max_verify_failures:o,...a==="revert"?{document_writes:a}:{},snapshot:Zv(n.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function rk(t){let e=lt(t,"classic"),n=e.context_compression??"off";if(n!=="off"&&n!=="beta")throw new Error("classic.context_compression must be off or beta");let r=e.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let i=e.auto_transition??!0;if(typeof i!="boolean")throw new Error("classic.auto_transition must be true or false");let s=e.document_evidence??"neutral";if(s!=="neutral"&&s!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:af(e.artifact_layout),language:cf(e.language,"zh-CN","classic.language"),context_compression:n,review_mode:r,auto_transition:i,...s==="strict"?{document_evidence:s}:{}}}function ik(t){let n=lt(t,"hook").allow_paths??[];if(!Array.isArray(n))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(n.map((r,i)=>fe(r,`hook.allow_paths[${i}]`)))]}}function sk(t){if(t===void 0)return{...us};let e=lt(t,"memory"),n=e.learning??us.learning,r=e.retrieval??us.retrieval;if(typeof n!="boolean")throw new Error("memory.learning must be true or false");if(typeof r!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:n,retrieval:r}}function za(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function ok(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim();if(n.length===0||n.includes("\\")||n.includes("\0")||Pt.posix.isAbsolute(n)||Pt.win32.isAbsolute(n)||n.startsWith("~")||n.split("/").some(i=>i===""||i==="."||i===".."))throw new Error(`${e} must be a safe project-relative glob`);if(!n.toLowerCase().endsWith(".md"))throw new Error(`${e} must target a Markdown file ending in .md`);if(n.length>Qd)throw new Error(`${e} exceeds ${Qd} characters`);let r=0;for(let i=0;i<n.length;i+=1)n[i]==="?"?r+=1:n[i]==="*"&&(r+=1,n[i+1]==="*"&&(i+=1));if(r>Zd)throw new Error(`${e} contains more than ${Zd} wildcard tokens`);return n}function ak(t){let e=za(t,"knowledge.local"),n=e.include??[];if(!Array.isArray(n))throw new Error("knowledge.local.include must be an array");let r={include:[...new Set(n.map((i,s)=>ok(i,`knowledge.local.include[${s}]`)))],max_file_mb:rf(e.max_file_mb,ef.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:rf(e.max_total_mb,ef.max_total_mb,"knowledge.local.max_total_mb")};if(r.max_file_mb>r.max_total_mb)throw new Error("knowledge.local.max_file_mb must not exceed max_total_mb");return r}function ck(t){if(typeof t!="string"||t.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let e;try{e=new URL(t)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let n=e.hostname.toLowerCase().replace(/^\[|\]$/gu,""),r=n==="localhost"||n==="127.0.0.1"||n==="::1";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&r))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return e.toString()}function lk(t){let e=za(t,"knowledge.remote"),n=ck(e.endpoint),r=e.token_env;if(r!==void 0&&(typeof r!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(r)))throw new Error("knowledge.remote.token_env must be an environment variable name");let i=e.scope;if(i!==void 0&&(typeof i!="string"||i.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let s=e.timeout_ms??5e3;if(typeof s!="number"||!Number.isSafeInteger(s)||s<100||s>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:n,...r===void 0?{}:{token_env:r},...i===void 0?{}:{scope:i},timeout_ms:s}}function uk(t){if(t===void 0)return{...of};let e=za(t,"knowledge"),n=e.provider??"local";if(n!=="local"&&n!=="remote")throw new Error("knowledge.provider must be local or remote");let r=e.local===void 0?void 0:ak(e.local);if(n==="local")return{provider:n,...r?{local:r}:{}};let i=e.remote===void 0?void 0:lk(e.remote);if(i===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:n,...r?{local:r}:{},remote:i}}function dk(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function fk(t,e,n,r,i,s,o,a){let c=t.schema!==void 0;if(!(c||t.default_workflow!==void 0||t.workflows!==void 0||!a.allowPartialProject&&t.native!==void 0)||a.allowPartialProject&&!c)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=t.workflows??[t.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!i)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:d,ambient_resume:o,...e?{hook:e}:{},memory:n,knowledge:r,...i?{native:i}:{},...s?{classic:s}:{}}}function At(t,e={}){let n=(0,Ha.parseDocument)(t,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${n.errors[0].message}`);let r=n.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let i=r,s=dk(i.ambient_resume),o=i.hook===void 0?void 0:ik(i.hook),a=sk(i.memory),c=uk(i.knowledge),l=i.native===void 0?void 0:nk(i.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),u=i.classic===void 0?void 0:rk(i.classic),d=fk(i,o,a,c,l,u,s,{allowPartialProject:e.allowPartialProject??!1});return{value:i,config:d,ambient_resume:s,memory:a,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function Ja(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...us},knowledge:{...of},native:{artifact_root:Er(t),language:e,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:sf,snapshot:{...Ae,include:[...Ae.include],exclude:[...Ae.exclude]}}}}var Ha,$n,Ua,Ka,Qd,Zd,sf,us,ef,of,Gv,tf,Yv,Vv,Xv,Ae,Ve=z(()=>{"use strict";Ha=Pe(xe(),1),$n=Number.MAX_SAFE_INTEGER,Ua=1024,Ka=64,Qd=1024,Zd=64,sf=5,us={learning:!0,retrieval:!0},ef={include:[],max_file_mb:1,max_total_mb:32},of={provider:"local"},Gv=12e4,tf=6e5,Yv=[".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/**"],Vv=["**/.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"],Xv=[...Yv,...Vv].sort((t,e)=>t.localeCompare(e,"en")),Ae={include:["**/*"],exclude:[...Xv],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4}});import{constants as Ot,promises as _e}from"fs";import{createHash as mk}from"node:crypto";function Ga(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function lf(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function jt(t){return{dev:t.dev,ino:t.ino,birthtime:Ga(t)}}function Nt(t,e){let n=jt(t),r=jt(e);return al(n,r)?wt(n,r):wt(n,r)&&Ga(t)===Ga(e)&&lf(t)===lf(e)&&t.size===e.size}async function Ya(t,e,n={}){if(!Number.isSafeInteger(e)||e<1)throw new Error("race-safe read byte limit must be a positive integer");let r=n.label??"file",i=n.bigint===!0,s=await _e.lstat(t,{bigint:i});if(!s.isFile()||s.isSymbolicLink())throw new qe("not-regular-file",`${r} must be a regular file`);if(BigInt(s.size)>BigInt(e))throw new qe("too-large",`${r} exceeds ${e} bytes`);let o=await _e.realpath(t);await n.verify?.("pre-open",{realPath:o,identity:jt(s)});let a=process.platform==="win32"?Ot.O_RDONLY:Ot.O_RDONLY|Ot.O_NOFOLLOW|Ot.O_NONBLOCK,c;try{c=await _e.open(t,a)}catch(l){throw l.code==="ELOOP"?new qe("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:i}),_e.lstat(t,{bigint:i}),_e.realpath(t)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Nt(s,l)||!Nt(s,u))throw new qe("changed",`${r} changed while opening`);await n.verify?.("post-open",{realPath:d,identity:jt(l)}),await n.hooks?.afterOpen?.();let f=[],p=0,g=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let y=e+1-p,{bytesRead:S}=await c.read(g,0,Math.min(g.length,y),null);if(S===0)break;if(p+=S,p>e)throw new qe("too-large",`${r} exceeds ${e} bytes`);f.push(Buffer.from(g.subarray(0,S)))}await n.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([c.stat({bigint:i}),_e.lstat(t,{bigint:i}),_e.realpath(t)]);if(!h.isFile()||h.isSymbolicLink()||v!==o||!Nt(s,m)||!Nt(s,h))throw new qe("changed",`${r} changed while reading`);return await n.verify?.("post-read",{realPath:v,identity:jt(m)}),{bytes:Buffer.concat(f,p),stat:m,realPath:v}}finally{await c.close()}}async function uf(t,e={}){let n=e.label??"file",r=e.bigint===!0,i=await _e.lstat(t,{bigint:r});if(!i.isFile()||i.isSymbolicLink())throw new qe("not-regular-file",`${n} must be a regular file`);let s=await _e.realpath(t);await e.verify?.("pre-open",{realPath:s,identity:jt(i)});let o=process.platform==="win32"?Ot.O_RDONLY:Ot.O_RDONLY|Ot.O_NOFOLLOW|Ot.O_NONBLOCK,a;try{a=await _e.open(t,o)}catch(c){throw c.code==="ELOOP"?new qe("not-regular-file",`${n} must be a regular file`,{cause:c}):c}try{let[c,l,u]=await Promise.all([a.stat({bigint:r}),_e.lstat(t,{bigint:r}),_e.realpath(t)]);if(!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==s||!Nt(i,c)||!Nt(i,l))throw new qe("changed",`${n} changed while opening`);await e.verify?.("post-open",{realPath:u,identity:jt(c)}),await e.hooks?.afterOpen?.();let d=mk(e.algorithm??"sha256"),f=Buffer.allocUnsafe(64*1024);for(;;){let{bytesRead:h}=await a.read(f,0,f.length,null);if(h===0)break;d.update(f.subarray(0,h))}await e.hooks?.beforeFinalCheck?.();let[p,g,m]=await Promise.all([a.stat({bigint:r}),_e.lstat(t,{bigint:r}),_e.realpath(t)]);if(!g.isFile()||g.isSymbolicLink()||m!==s||!Nt(i,p)||!Nt(i,g))throw new qe("changed",`${n} changed while reading`);return await e.verify?.("post-read",{realPath:m,identity:jt(p)}),{digest:d.digest("hex"),stat:p,realPath:m}}finally{await a.close()}}var qe,Va=z(()=>{"use strict";ci();qe=class extends Error{reason;constructor(e,n,r){super(n,r),this.name="RaceSafeReadError",this.reason=e}}});import{promises as It}from"fs";import Ke from"path";async function df(t,e,n){let r=await J(t,e,{label:n.label,expected:"file"});if(!r.exists){let s=new Error(`${n.label} does not exist`);throw s.code="ENOENT",s}let i=await ds(r.projectRoot,n.label);return uf(r.target,{...n,verify:async(s,o)=>{if(!_r(i,o.realPath))throw new Error(`${n.label} resolves outside the project root`);await fs(r.projectRoot,i,r.relative.split("/"),{label:n.label,expected:"file"})}})}function ff(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function _r(t,e){let n=Ke.relative(t,e);return n===""||!Ke.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${Ke.sep}`)}async function ds(t,e){let n=Ke.resolve(t),r=await It.lstat(n);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return It.realpath(n)}async function fs(t,e,n,r){let i=t;for(let s=0;s<n.length;s++){i=Ke.join(i,n[s]);let o;try{o=await It.lstat(i)}catch(u){if(ff(u))return{exists:!1,kind:"missing"};throw u}let a=Ke.relative(t,i).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${a}`);let c=s===n.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${a} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await It.realpath(i);if(!_r(e,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function J(t,e,n){let r=fe(e,n.label),i=Ke.resolve(t),s=await ds(i,n.label),o=r.split("/"),a=Ke.resolve(i,...o);if(!_r(i,a))throw new Error(`${n.label} must stay inside the project root`);let c=await fs(i,s,o,n);return{projectRoot:i,target:a,relative:r,exists:c.exists,kind:c.kind}}async function Xa(t,e,n){let r=fe(e,n.label),i=Ke.resolve(t),s=await ds(i,n.label),o=r.split("/"),a=i;for(let c of o){a=Ke.join(a,c);let l;try{l=await It.lstat(a)}catch(f){if(!ff(f))throw f;try{await It.mkdir(a)}catch(p){if(p.code!=="EEXIST")throw p}l=await It.lstat(a)}let u=Ke.relative(i,a).replaceAll("\\","/");if(l.isSymbolicLink())throw new Error(`${n.label} crosses a symbolic link or junction at ${u}`);if(!l.isDirectory())throw new Error(`${n.label} directory ${u} must be a real directory`);let d=await It.realpath(a);if(!_r(s,d))throw new Error(`${n.label} resolves outside the project root`)}return await fs(i,s,o,{label:n.label,expected:"directory"}),a}async function Qa(t,e,n){return(await J(t,e,{...n,expected:"file"})).exists}async function Y(t,e,n,r){let i=await J(t,e,{label:r.label,expected:"file"});if(!i.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let s=await ds(i.projectRoot,r.label);return Ya(i.target,n,{...r,verify:async(o,a)=>{if(!_r(s,a.realPath))throw new Error(`${r.label} resolves outside the project root`);await fs(i.projectRoot,s,i.relative.split("/"),{label:r.label,expected:"file"})}})}var le=z(()=>{"use strict";Va();Ve()});import{createHash as gk}from"crypto";function wk(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function ut(t,e={}){return(await hs(t,e)).document}async function yk(t){try{return(await Y(t,Nr,$n,{label:Nr})).bytes}catch(e){if(wk(e))return null;throw e}}function vk(t){return t?{exists:!0,sha256:gk("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function hs(t,e={}){let n=await yk(t);return{document:n?At(n.toString("utf8"),e):null,identity:vk(n)}}async function ec(t){return(await ut(t))?.config??null}var Nr,Tt=z(()=>{"use strict";Ve();le();Nr=".comet/config.yaml"});var wR,tc=z(()=>{"use strict";ot();Tt();le();wR=16*1024});var rc=z(()=>{"use strict";ot();Ve();Tt();le();tc()});import{spawn as sc}from"node:child_process";import{existsSync as Sf}from"node:fs";import cn from"node:path";function oc(t,e){let n=e.toLowerCase();return Object.entries(t).find(([r,i])=>r.toLowerCase()===n&&i!==void 0)?.[1]}function Lk(t){let e=(oc(t,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(n=>n.trim().toLowerCase()).filter(Boolean);return[...new Set([...e,".ps1"])]}function qk(t,e,n){let i=cn.win32.isAbsolute(t)||/[\\/]/u.test(t)?[""]:(oc(e,"PATH")??"").split(cn.delimiter).map(a=>a.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=cn.win32.extname(t)?[t]:Lk(e).map(a=>`${t}${a}`);return i.flatMap(a=>o.map(c=>a?cn.join(a,c):cn.resolve(n,c)))}function ln(t,e,n){return qk(t,e,n).find(r=>Sf(r))??t}function Mk(t){let e=oc(t,"SystemRoot");if(e){let n=cn.join(e,"System32","WindowsPowerShell","v1.0","powershell.exe");if(Sf(n))return n}return"powershell.exe"}function ac(t){if(t.some(e=>$k.test(e)))throw new Error("Windows batch check arguments must not contain shell syntax")}function Fk(t,e,n){let r=Buffer.from(JSON.stringify({command:t,arguments:[...e]}),"utf8").toString("base64"),i=Buffer.from(Tk,"utf16le").toString("base64");return sc(Mk(n.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",i],{cwd:n.cwd,env:{...n.env,COMET_COMMAND_PAYLOAD:r},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function Ef(t,e,n){let r=n.env??process.env;if(process.platform!=="win32")return sc(t,[...e],{cwd:n.cwd,env:r,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let i=ln(t,r,n.cwd),s=cn.win32.extname(i).toLowerCase();return Ik.has(s)&&ac(e),jk.has(s)?Fk(i,e,{cwd:n.cwd,env:r}):sc(i,[...e],{cwd:n.cwd,env:r,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}var jk,Ik,$k,Tk,Tr=z(()=>{"use strict";jk=new Set([".bat",".cmd",".ps1"]),Ik=new Set([".bat",".cmd"]),$k=/[&|<>()^%"!\r\n]/u,Tk=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ")});import{execFileSync as Dk}from"node:child_process";import xf from"node:path";function Uk(t){return t instanceof Error&&(t.code==="ETIMEDOUT"||t.killed===!0&&t.signal==="SIGTERM")}function Ln(t,e,n={}){let r=n.timeoutMs??Wk,i=n.maxBufferBytes??Bk;if(!Number.isSafeInteger(r)||r<1)throw new Error("External command timeout must be a positive integer");if(!Number.isSafeInteger(i)||i<1)throw new Error("External command max buffer must be a positive integer");let s=xf.resolve(n.cwd??process.cwd()),o=n.env??process.env,a=process.platform==="win32"?ln(t,o,s):t,c=xf.win32.extname(a).toLowerCase(),l=c===".bat"||c===".cmd";process.platform==="win32"&&l&&ac(e);try{return Dk(a,[...e],{cwd:s,env:o,...n.input!==void 0?{input:n.input}:{},encoding:"utf8",stdio:[n.input===void 0?"ignore":"pipe","pipe","pipe"],timeout:r,maxBuffer:i,windowsHide:!0,shell:process.platform==="win32"&&l})}catch(u){let d=typeof u.stderr=="string"?u.stderr.trim():Buffer.isBuffer(u.stderr)?u.stderr.toString("utf8").trim():"";throw new Tn(t,e,d,{cause:u,timedOut:Uk(u)})}}var Wk,Bk,Tn,cc=z(()=>{"use strict";Tr();Wk=6e4,Bk=8*1024*1024,Tn=class extends Error{constructor(n,r,i,s){super(`${n} ${r.join(" ")} failed${i?`: ${i}`:""}`,s);this.command=n;this.args=r;this.stderr=i;this.name="ExternalCommandError",this.timedOut=s?.timedOut===!0}command;args;stderr;timedOut}});import{promises as Gf}from"node:fs";import Yf from"node:path";function Ob(t){let e=gc.get(t);if(!e)return;let n=e.value===null?Ab:Pb;if(Date.now()-e.at>n){gc.delete(t);return}return e.value}async function wc(t){if(t===process.pid&&hc!==null)return hc;let e=Ob(t);if(e!==void 0)return e;let n=await Nb(t);return t===process.pid&&n!==null&&(hc=n),t!==process.pid&&gc.set(t,{value:n,at:Date.now()}),n}async function Nb(t){if(!Number.isSafeInteger(t)||t<=0)return null;try{if(process.platform==="linux"){let[e,n]=await Promise.all([Gf.readFile(`/proc/${t}/stat`,"utf8"),Gf.readFile("/proc/sys/kernel/random/boot_id","utf8")]),r=e.slice(e.lastIndexOf(")")+2).trim().split(/\s+/u)[19];return/^\d+$/u.test(r??"")?`linux:${n.trim()}:${r}`:null}if(process.platform==="win32")return await Ib(t);if(process.platform==="darwin"){let e=Ln("/bin/ps",["-p",String(t),"-o","lstart="],{timeoutMs:5e3,maxBufferBytes:4096,env:{...process.env,LC_ALL:"C",TZ:"UTC0"}}).trim();return e?`darwin:${e}`:null}}catch{}return null}function jb(t){let e=t.trim();return/^\d+$/u.test(e)?`win32-ps:${e}`:null}async function Ib(t){try{let i=Ln(Yf.win32.join(process.env.SystemRoot??"C:\\Windows","System32","wbem","WMIC.exe"),["process","where",`processid=${t}`,"get","creationdate","/value"],{timeoutMs:5e3,maxBufferBytes:4096}),s=/^CreationDate=(\S+)/mu.exec(i);if(s)return`win32-wmic:${s[1]}`}catch{}let e=process.env.SystemRoot??"C:\\Windows",n=Yf.win32.join(e,"System32","WindowsPowerShell","v1.0","powershell.exe"),r=Ln(n,["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${t} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:8e3,maxBufferBytes:4096}).trim();return jb(r)}function Rs(t){let e=t.indexOf(":");return e===-1?"":t.slice(0,e)}async function Xf(t,e){if(!Number.isSafeInteger(t)||t<=0)return"alive";try{process.kill(t,0)}catch(r){if(r.code==="ESRCH")return"dead"}if(!e)return"unknown";let n=await wc(t);return n===e?"alive":n===null||Rs(n)!==Rs(e)&&Vf.has(Rs(n))&&Vf.has(Rs(e))?"unknown":"dead"}var hc,Pb,Ab,gc,Vf,Qf=z(()=>{"use strict";cc();hc=null,Pb=6e4,Ab=1e4,gc=new Map;Vf=new Set(["win32-wmic","win32-ps"])});import{randomUUID as $b}from"node:crypto";import{promises as fn}from"node:fs";import em from"node:os";import Zf from"node:path";async function tm(t,e,n={}){let r=Zf.resolve(t);await fn.mkdir(Zf.dirname(r),{recursive:!0});let i=Date.now(),s=n.timeoutMs??Tb,o=n.retryMs??Lb,a=n.malformedLockStaleMs??qb,c=await wc(process.pid),l={pid:process.pid,nonce:$b(),createdAt:Date.now(),hostname:em.hostname(),...c===null?{}:{processIdentity:c}},u=!1;for(;!u;){let d;try{d=await fn.open(r,"wx"),await d.writeFile(JSON.stringify(l),"utf8"),u=!0}catch(f){if(f.code!=="EEXIST")throw f;if(await Fb(r,a))continue;if(Date.now()-i>=s)throw new Error(`Timed out waiting for file lock: ${r}`,{cause:f});await new Promise(p=>setTimeout(p,o))}finally{await d?.close()}}try{return await e()}finally{await Db(r,l.nonce)}}async function Fb(t,e){let n,r;try{[n,r]=await Promise.all([fn.readFile(t,"utf8"),fn.stat(t)])}catch(s){return s.code==="ENOENT"}let i=nm(n);if(i!==null&&(i.hostname!==void 0&&i.hostname!==em.hostname()||await Xf(i.pid,i.processIdentity)!=="dead"))return!1;if(i===null){let s=n.trim().length===0?Mb:e;if(Date.now()-Number(r.mtimeMs)<s)return!1}try{return await fn.readFile(t,"utf8")!==n?!1:(await fn.rm(t),!0)}catch(s){return s.code==="ENOENT"}}async function Db(t,e){try{if(nm(await fn.readFile(t,"utf8"))?.nonce!==e)return;await ai(t)}catch(n){let r=n.code;if(r==="ENOENT")return;process.stderr.write(`[comet] warning: could not remove lock file ${t} (${r??n}); it will be recovered automatically
|
|
143
|
+
`)}}function nm(t){try{let e=JSON.parse(t);return Number.isSafeInteger(e.pid)&&Number(e.pid)>0&&typeof e.nonce=="string"&&e.nonce.length>0&&typeof e.createdAt=="number"&&Number.isFinite(e.createdAt)&&(e.hostname===void 0||typeof e.hostname=="string"&&e.hostname.length>0)&&(e.processIdentity===void 0||typeof e.processIdentity=="string"&&e.processIdentity.length>0)?{pid:Number(e.pid),nonce:e.nonce,createdAt:e.createdAt,...e.hostname===void 0?{}:{hostname:e.hostname},...e.processIdentity===void 0?{}:{processIdentity:e.processIdentity}}:null}catch{return null}}var Tb,Lb,qb,Mb,rm=z(()=>{"use strict";oo();Qf();Tb=3e4,Lb=20,qb=5*6e4,Mb=1e4});var Ps=z(()=>{"use strict"});var im=z(()=>{"use strict"});var yc=z(()=>{"use strict";Ps()});var sm=z(()=>{"use strict";Ps();yc()});function zb(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function Jb(t){let e=(0,om.parseDocument)(t,{uniqueKeys:!0});if(e.errors.length>0)throw new Error(`Invalid global Comet config: ${e.errors[0].message}`);let n=e.toJS();if(n==null)return{};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid global Comet config: root must be a mapping");return n}function cm(t){if(t.native?.pending_root_move)throw new Error("Global Comet config cannot contain native.pending_root_move");let e=t.native?(({pending_root_move:n,...r})=>r)(t.native):void 0;return{...t,schema:"comet.global.v1",...e?{native:e}:{}}}function Gb(t){let e=At(JSON.stringify({...t,schema:"comet.project.v1"})).config;if(!e)throw new Error("Invalid global Comet config: workflow template is incomplete");return cm(e)}function Yb(t){let e=At(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e.native&&!e.classic)return null;let n=e.native?"native":"classic",r=e.native?.language??e.classic?.language??"en",i=Ja(e.native?.artifact_root??"docs",r);return{schema:"comet.global.v1",default_workflow:n,workflows:[n],ambient_resume:e.ambient_resume,...e.native?{native:{...i.native,...e.native}}:{},...e.classic?{classic:e.classic}:{}}}function lm(t){let e=Jb(t);if(Object.keys(e).length===0)return null;if(e.schema===void 0)return Yb(t);if(e.schema!=="comet.global.v1")throw new Error("Unsupported Comet global schema");return Gb(e)}async function vc(t){try{let e=await Y(t,am,$n,{label:"global Comet config"});return lm(e.bytes.toString("utf8"))}catch(e){if(zb(e))return null;throw e}}var om,am,kc=z(()=>{"use strict";om=Pe(xe(),1);ot();Ve();le();am=".comet/config.yaml"});var jA,um=z(()=>{"use strict";ot();le();jA=4*1024*1024});function fm(t,e){let n=t;for(let r of e)n+="\0"+(typeof r=="string"?r:JSON.stringify(r));return n}function mm(t,e){return(...n)=>{let r=dm;if(r===null)return e(...n);let i=fm(`async:${t}`,n),s=r.entries.get(i);if(s)return s.value;let o=e(...n).catch(a=>{throw r.entries.delete(i),a});return r.entries.set(i,{value:o}),o}}function bc(t,e){return(...n)=>{let r=dm;if(r===null)return e(...n);let i=fm(`sync:${t}`,n),s=r.entries.get(i);if(s)return s.value;let o=e(...n);return r.entries.set(i,{value:o}),o}}var dm,Cc=z(()=>{"use strict";dm=null});var qA,pm=z(()=>{"use strict";Cc();Tt();qA=mm("hookWritePolicy",async t=>(await ec(t))?.hook??{allow_paths:[]})});var Vb,hm=z(()=>{"use strict";Va();Vb=16*1024});var gm=z(()=>{"use strict";Ps();ot();im();sm();Ve();kc();le();Tt();rc();um();pm();hm();tc();yc()});import{TextDecoder as Xb}from"util";function wm(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function Qb(t,e){try{return new Xb("utf-8",{fatal:!0}).decode(t.bytes)}catch(n){throw new Error(`${e} is not valid UTF-8`,{cause:n})}}async function Sc(t,e,n,r,i={}){try{let s=await Y(t,e,n,{label:r,hooks:i.hooks});return{result:s,text:Qb(s,r)}}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw s}}async function mt(t,e,n,r,i={}){return(await Sc(t,e,n,r,i))?.text??null}async function Wt(t,e,n,r,i,s={}){if(Buffer.byteLength(n,"utf8")>r)throw new Error(`${i} exceeds ${r} bytes`);let o=await Sc(t,e,r,i),a=await J(t,e,{label:i,expected:"file"});await ye(a.target,n,{containedRoot:a.projectRoot,beforeCommit:async()=>{await s.beforeCommit?.();let c=await Sc(t,e,r,i);if(!(!o&&!c)){if(!o||!c)throw new Error(`${i} changed before commit`);if(o.result.realPath!==c.result.realPath||!wt(wm(o.result.stat),wm(c.result.stat))||o.text!==c.text)throw new Error(`${i} changed before commit`)}}})}async function As(t,e,n,r,i,s={}){let o=await mt(t,e,r,i);await Wt(t,e,`${o??""}${n}`,r,i,s)}async function Os(t,e,n,r={}){let i=await J(t,e,{label:n,expected:"file"});return i.exists?Cn(i.target,{containedRoot:i.projectRoot,beforeRemove:r.beforeRemove}):!1}var Ns=z(()=>{"use strict";gm();ci()});var km={};dh(km,{RUN_STATE_FILE:()=>js,applyRunStateToDocument:()=>Ec,readRunState:()=>Is,removeRunState:()=>Jr,runStateFromDocument:()=>Dn,writeRunState:()=>Wn});import Zb from"path";function zr(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return n}function Hr(t,e){let n=zr(t,e);if(Zb.isAbsolute(n)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return n}function eC(t){let e=t.run_retries??"{}",n;try{n=typeof e=="string"?JSON.parse(e):e}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(n))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return n}function Dn(t){if(!t.run_id)return null;let e=zr(t,"run_id"),n=zr(t,"skill"),r=zr(t,"skill_version"),i=zr(t,"skill_hash"),s=Hr(t,"pending_ref"),o=Hr(t,"trajectory_ref"),a=Hr(t,"context_ref"),c=Hr(t,"artifacts_ref"),l=Hr(t,"checkpoint_ref"),u=Number(t.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:n,skillVersion:r,skillHash:i,orchestration:t.orchestration,currentStep:ym(t,"current_step"),iteration:u,pending:ym(t,"pending"),pendingRef:s,trajectoryRef:o,contextRef:a,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:eC(t)}}function Ec(t,e){e?t.run_id=e.runId:delete t.run_id}function tC(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,currentStep:t.currentStep,iteration:t.iteration,pending:t.pending,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,status:t.status,retries:t.retries}}function nC(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)};return Dn(e)}async function Is(t,e={}){let n=await mt(t,js,vm,"Run state",e);if(n===null)return null;let r=JSON.parse(n);return nC(r)}async function Wn(t,e,n={}){await Wt(t,js,JSON.stringify(tC(e),null,2),vm,"Run state",n)}async function Jr(t,e={}){await Os(t,js,"Run state",e)}var ym,js,vm,$s=z(()=>{"use strict";Ns();ym=(t,e)=>{let n=t[e];return n==null?null:String(n)};js=".comet/run-state.json",vm=Number.MAX_SAFE_INTEGER});import{spawn as ES}from"node:child_process";import Bc from"node:path";async function hp(t){let e=t.pid;if(e===void 0){t.kill("SIGKILL");return}if(process.platform==="win32"){let n=process.env.SystemRoot??process.env.WINDIR,r=n&&Bc.win32.isAbsolute(n)?Bc.win32.resolve(n):"C:\\Windows",i=Bc.win32.join(r,"System32","taskkill.exe"),s=()=>new Promise(o=>{let a=!1,c=null,l=null,u=(d,f=!1)=>{a||(a=!0,l&&clearTimeout(l),f&&c?.kill("SIGKILL"),o(d))};try{c=ES(i,["/pid",String(e),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>u(!1)),c.once("close",d=>u(d===0)),l=setTimeout(()=>u(!1,!0),xS)}catch{u(!1)}});for(let o=0;o<_S;o+=1)if(await s()){t.kill("SIGKILL");return}t.kill("SIGKILL"),t.stdin?.destroy(),t.stdout?.destroy(),t.stderr?.destroy();return}try{process.kill(-e,"SIGKILL")}catch(n){if(n.code!=="ESRCH")throw n}t.kill("SIGKILL")}var xS,_S,gp=z(()=>{"use strict";xS=1e3,_S=2});import{createHash as hE}from"crypto";import{promises as gE}from"fs";ot();Ve();le();import Rr from"path";var Za=Number.MAX_SAFE_INTEGER;function ms(t,e,n){let r=Rr.resolve(t),i=Rr.isAbsolute(e)?Rr.resolve(e):Rr.resolve(r,e),s=Rr.relative(r,i).replaceAll("\\","/");return{root:r,relative:fe(s,n),target:i}}async function me(t,e,n){let r=ms(t,e,n.label);return J(r.root,r.relative,n)}async function G(t,e,n){return(await me(t,e,{label:n.label,expected:n.expected??"any"})).exists}async function Oe(t,e,n,r){return await G(t,e,{label:n,expected:"file"})?(await ps(t,e,{label:n,hooks:r})).byteLength>0:!1}async function I(t,e,n){return(await ps(t,e,n)).toString("utf8")}async function ps(t,e,n){let r=ms(t,e,n.label);return(await Y(r.root,r.relative,n.maxBytes??Za,{label:n.label,hooks:n.hooks})).bytes}async function Pr(t,e,n){let r=ms(t,e,n);return Xa(r.root,r.relative,{label:n})}async function $t(t,e,n,r){let i=ms(t,e,r.label);await J(i.root,i.relative,{label:r.label,expected:"file"}),await ye(i.target,n,{containedRoot:i.root,beforeTemporaryOpen:r.beforeTemporaryOpen,beforeCommit:r.beforeCommit,exclusive:r.exclusive})}function Ar(t){if(t.workflow!=="full")return{missingFields:[],invalidFields:[]};let e=[],n=[];return t.buildMode||e.push("build_mode"),t.tddMode||e.push("tdd_mode"),t.reviewMode||e.push("review_mode"),t.buildMode==="subagent-driven-development"&&t.subagentDispatch!=="confirmed"&&e.push("subagent_dispatch"),t.buildMode==="autonomous"&&t.reviewMode==="off"&&n.push({field:"review_mode",reason:"autonomous full build requires review_mode=standard or thorough"}),t.buildMode==="direct"&&t.directOverride!==!0&&n.push({field:"direct_override",reason:"full workflow direct execution requires direct_override=true"}),{missingFields:e,invalidFields:n}}function mf(t){let e=Ar(t);return e.missingFields.length===0&&e.invalidFields.length===0}var kf=Pe(xe(),1);import{promises as wf}from"fs";import X from"path";import{promises as pk}from"fs";async function Or(t){try{return await pk.access(t),!0}catch(e){if(hk(e))return!1;throw e}}function hk(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}Ve();Tt();rc();le();var jr=class extends Error{code="classic-layout-unavailable";constructor(e="Classic artifact layout is unavailable from .comet/config.yaml"){super(e),this.name="ClassicLayoutUnavailableError"}},gf=".comet/config.yaml";function yf(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function vf(t){await J(t,gf,{label:gf,expected:"file"})}function gs(t,e){let n=X.resolve(t),r=e==="docs"?X.join(n,"docs"):n,i=X.join(r,"openspec"),s=X.join(n,"docs","superpowers");return{projectRoot:n,artifactLayout:e,openSpecBase:r,openSpecRoot:i,changesDir:X.join(i,"changes"),archiveDir:X.join(i,"changes","archive"),specsDir:X.join(i,"specs"),superpowersRoot:s,superpowersSpecsDir:X.join(s,"specs"),superpowersPlansDir:X.join(s,"plans"),superpowersReportsDir:X.join(s,"reports")}}async function Ek(t){await vf(t);let e=await ut(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e?.config)throw new jr;if(!(e.config.workflows??[e.config.default_workflow]).includes("classic"))throw new jr("Classic artifact layout is unavailable because Classic is not enabled");return e.classic?.artifact_layout??"legacy"}async function ic(t,e){return gs(t,e??await Ek(t))}async function xk(t){try{return await wf.lstat(t),!0}catch(e){if(yf(e))return!1;throw e}}async function _k(t,e){let n=await ic(t,e),r=n.artifactLayout==="legacy"?"docs":"legacy",i=gs(t,r).openSpecRoot,[s,o]=await Promise.all([J(n.projectRoot,K(n.projectRoot,n.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),xk(i)]),a=s.exists;return{paths:n,configuredRootExists:a,alternateRoot:i,alternateRootExists:o,dualRoots:a&&o}}async function Rk(t){let e=[t.openSpecRoot,t.changesDir,t.archiveDir,t.specsDir,t.superpowersRoot,t.superpowersSpecsDir,t.superpowersPlansDir,t.superpowersReportsDir];for(let n of e){let r=K(t.projectRoot,n);await J(t.projectRoot,r,{label:`Classic managed physical path ${r}`,expected:"directory"})}}async function ue(t,e){let n=await _k(t,e);if(await Rk(n.paths),!n.configuredRootExists){let r=K(n.paths.projectRoot,n.paths.openSpecRoot),i=K(n.paths.projectRoot,n.alternateRoot);throw new jr(`Configured Classic OpenSpec root is missing: ${r} (alternate ${i} is ${n.alternateRootExists?"present":"missing"})`)}return n.paths}async function on(t,e){let n=X.join(X.resolve(t),".comet","classic-root-move.json");if(await Or(n))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let r=await ue(t,e);if(!await Or(r.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${K(r.projectRoot,r.openSpecRoot)}`);return r}async function dt(t){let e=X.resolve(t),n=null;try{(await wf.lstat(e)).isDirectory()||(e=X.dirname(e))}catch(r){if(!yf(r))throw r}for(;;){X.basename(e)==="openspec"&&(n=X.dirname(e));let r=X.join(e,".comet","config.yaml"),i=!1;if(await Or(r))try{await vf(e);let o=(await ut(e))?.value;i=!!o&&typeof o=="object"&&!Array.isArray(o)&&(o.schema==="comet.project.v1"||o.default_workflow!==void 0||o.native!==void 0)}catch{}if(i||await Or(X.join(e,".git")))return e;let s=X.dirname(e);if(s===e)return n??X.resolve(t);e=s}}function K(t,e){return X.relative(X.resolve(t),e).replaceAll("\\","/")}import an from"node:path";async function bf(t,e,n,r={}){if(n.workflow!=="full"||n.buildMode!=="autonomous")return[];let i=[];if(r.requirePlan!==!1){let s=Ar(n);s.missingFields.includes("tdd_mode")&&i.push("tdd_mode must be selected for autonomous full build"),s.missingFields.includes("review_mode")&&i.push("review_mode must be selected for autonomous full build"),s.invalidFields.some(({field:o})=>o==="review_mode")&&i.push("review_mode must be standard or thorough for autonomous full build"),n.isolation||i.push("isolation must be selected for autonomous full build")}if(!n.designDoc||!await Oe(t,n.designDoc,"Classic autonomous design"))i.push("design_doc must reference a nonempty technical design for autonomous full build");else{let o=(await I(t,n.designDoc,{label:"Classic autonomous design"})).replace(/^\uFEFF/u,"").match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u),a=o?(0,kf.parseDocument)(o[1]):null;(!a||a.errors.length||a.get("comet_change")!==e||a.get("role")!=="technical-design"||a.get("canonical_spec")!=="openspec")&&i.push("design_doc must link the current change and declare role: technical-design and canonical_spec: openspec")}return r.requirePlan!==!1&&(await Ir(t,n.plan,{requireNonempty:!0})).status!=="ready"&&i.push("plan must reference a nonempty implementation plan in the configured plans directory"),i}async function Ir(t,e,n={}){if(!e||e==="null")return{status:"missing",recordedPath:null};let r=await ue(t),i=an.resolve(t,e),s=an.relative(r.superpowersPlansDir,i);return an.isAbsolute(e)||!s||s.startsWith(`..${an.sep}`)||an.isAbsolute(s)||s.includes(an.sep)||an.extname(s).toLowerCase()!==".md"?{status:"broken",recordedPath:e}:await G(t,e,{label:`Classic build plan ${e}`,expected:"file"})&&(!n.requireNonempty||(await I(t,e,{label:`Classic build plan ${e}`})).trim().length>0)?{status:"ready",recordedPath:e}:{status:"broken",recordedPath:e}}import{stripVTControlCharacters as Pk}from"node:util";function Lt(t,e={}){return{code:"CLASSIC_COMMAND_FAILED",message:Pk(t instanceof Error?t.message:String(t)),...e}}import tt from"node:path";import{createHash as Ak,randomUUID as BR}from"node:crypto";var Ok=/^(\s*[-*]\s+\[)([ xX])(\]\s+)(.*)$/u,Nk=/\s*<!-- comet-task:([a-zA-Z0-9][a-zA-Z0-9_-]{0,79}) -->\s*$/u;function Ne(t){let e=[],n=new Set,r=null;for(let[i,s]of t.split(/\r?\n/u).entries()){let o=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(s);if(o){r?o[1][0]===r.marker&&o[1].length>=r.length&&!o[2].trim()&&(r=null):r={marker:o[1][0],length:o[1].length};continue}if(r)continue;let a=Ok.exec(s);if(!a)continue;let c=Nk.exec(a[4]),l=c?.[1]??null;if(a[4].includes("<!-- comet-task:")&&(!c||a[4].slice(0,c.index).includes("<!-- comet-task:")))throw new Error(`Malformed Classic task ID at line ${i+1}`);if(l&&n.has(l))throw new Error(`Duplicate Classic task ID: ${l}`);l&&n.add(l);let u=a[4].slice(0,c?.index).trim();if(!u)throw new Error(`Empty Classic task at line ${i+1}`);e.push({id:l,text:u,completed:a[2].toLowerCase()==="x",line:i+1})}return e}function $r(t){let e=t.split(/(?<=\n)/u);for(let n of Ne(t))e[n.line-1]=e[n.line-1].replace(/^(\s*[-*]\s+\[)[ xX](\])/u,"$1 $2");return e.join("")}function ws(t){return Ak("sha256").update($r(t)).digest("hex")}function ys(t,e){let n=Ne(t),r=new Set(e.map(i=>i.id).filter(Boolean));return{total:n.length,unmapped:n.filter(i=>!i.id||!r.has(i.id))}}function Cf(t,e,n){let r=[...t.matchAll(/^<!-- comet-task-authority: (.+) -->$/gmu)];if(!r.length)return"legacy";if(r.length!==1||r[0][1]!==e)throw new Error("Plan task authority must point to this change tasks.md");if(Ne(t).length)throw new Error("Canonical plan must reference tasks, not maintain a second checkbox ledger");if(!n.length||n.some(o=>!o.id))throw new Error("Canonical plan requires stable task IDs");let i=new Set([...t.matchAll(/<!-- comet-task-ref:([a-zA-Z0-9][a-zA-Z0-9_-]{0,79}) -->/gu)].map(o=>o[1])),s=new Set(n.map(o=>o.id));if([...i].some(o=>!s.has(o)))throw new Error("Plan references a missing task ID; update the plan mapping");if(n.some(o=>!i.has(o.id)))throw new Error("Plan must reference each task ID; update the plan mapping");return"canonical"}var Nf=Pe(xe(),1);cc();import Xe from"node:path";import{createHash as bs,randomUUID as tP}from"node:crypto";var Kk=new Set(["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_GRAFT_FILE","GIT_SHALLOW_FILE","GIT_PREFIX","GIT_IMPLICIT_WORK_TREE","GIT_NO_REPLACE_OBJECTS","GIT_REPLACE_REF_BASE","GIT_CONFIG","GIT_CONFIG_PARAMETERS","GIT_CONFIG_COUNT"]);function Hk(t=process.env){return Object.fromEntries(Object.entries(t).filter(([e])=>{let n=e.toUpperCase();return!Kk.has(n)&&!/^GIT_CONFIG_(KEY|VALUE)_\d+$/u.test(n)}))}function _f(t){return{...Hk(t.environment),...t.authentication?{}:{GIT_CONFIG_GLOBAL:process.platform==="win32"?"NUL":"/dev/null",GIT_CONFIG_NOSYSTEM:"1"},GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never",SSH_ASKPASS_REQUIRE:"never",GIT_NO_REPLACE_OBJECTS:"1",GH_PROMPT_DISABLED:"1"}}var Rf=["implementing","task-review","checkoff","done","blocked"];function qt(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Classic progress requires a JSON object");return t}function Cs(t,e){let n=Object.keys(t).filter(r=>!e.includes(r));if(n.length)throw new Error(`Unknown Classic progress field(s): ${n.join(", ")}; allowed fields: ${e.join(", ")}`)}function Me(t,e){if(typeof t!="string"||!t.trim()||t.length>4096||[...t].some(n=>n.charCodeAt(0)<32||n.charCodeAt(0)===127))throw new Error(`Invalid Classic progress ${e}`);return t}function lc(t,e){if(!Array.isArray(t)||t.length>200)throw new Error(`Invalid Classic progress ${e}`);return t.map(n=>Me(n,e))}function zk(t){let e=qt(t);if(Cs(e,["schemaVersion","taskIds","revision","stage","sessionId","evidence","unresolved","reviewRounds"]),e.schemaVersion!==1)throw new Error("Unsupported Classic checkpoint schemaVersion");let n=lc(e.taskIds,"taskIds");if(!n.length||new Set(n).size!==n.length||n.some(r=>!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}$/u.test(r)))throw new Error("Classic checkpoint taskIds must be unique stable IDs");if(typeof e.revision!="string"||!/^[a-f0-9]{64}$/u.test(e.revision))throw new Error("Invalid Classic checkpoint revision");if(!Rf.includes(e.stage))throw new Error(`Invalid Classic checkpoint stage '${String(e.stage)}'; stages: ${Rf.join("|")}`);if(!Number.isSafeInteger(e.reviewRounds)||e.reviewRounds<0)throw new Error("Invalid Classic checkpoint reviewRounds");return{schemaVersion:1,taskIds:n,revision:e.revision,stage:e.stage,sessionId:Me(e.sessionId,"sessionId"),evidence:lc(e.evidence,"evidence"),unresolved:lc(e.unresolved,"unresolved"),reviewRounds:e.reviewRounds}}async function jf(t,e,n){let r=Xe.join(e,".comet",n);if(await G(t,r,{label:"Classic progress",expected:"file"}))return JSON.parse(await I(t,r,{label:"Classic progress"}))}function Jk(t,e){let n=bs("sha256").update(e).digest("hex");return Xe.join(t,".comet","runtime","classic-delivery",`${n}.json`)}async function Gk(t,e){let n=Jk(t,e);if(!await G(t,n,{label:"Classic delivery reauthorization",expected:"file"}))return null;let r=qt(JSON.parse(await I(t,n,{label:"Classic delivery reauthorization"})));if(Cs(r,["schemaVersion","changeIdentity","previousAuthorizationId","authorizationId","action","targetBranch","remote","authorizedRemoteUrl"]),r.schemaVersion!==1||r.changeIdentity!==e)throw new Error("Classic delivery reauthorization identity is invalid");let i=dc({action:r.action,targetBranch:r.targetBranch,...r.remote===void 0?{}:{remote:r.remote}},!0);if(i.commit!==void 0||i.prUrl!==void 0)throw new Error("Classic delivery reauthorization cannot change sealed commit or PR evidence");return{schemaVersion:1,changeIdentity:e,previousAuthorizationId:Me(r.previousAuthorizationId,"previousAuthorizationId"),authorizationId:Me(r.authorizationId,"authorizationId"),...i,...r.authorizedRemoteUrl===void 0?{}:{authorizedRemoteUrl:Me(r.authorizedRemoteUrl,"authorizedRemoteUrl")}}}async function If(t,e,n){let r=await jf(t,e,"coordination.json");if(r===void 0)return{checkpoint:null,stale:!1};let i=zk(r),s=new Set(Ne(n).map(o=>o.id));return{checkpoint:i,stale:i.revision!==ws(n)||i.taskIds.some(o=>!s.has(o))}}function dc(t,e=!1){let n=qt(t);if(Cs(n,["action","targetBranch","remote","commit","prUrl",...e?["schemaVersion","changeIdentity","authorizedRemoteUrl","authorizationId"]:[]]),!["local","push","pr"].includes(n.action))throw new Error(`Invalid Classic delivery action '${String(n.action)}'; actions: local|push|pr`);let r=Me(n.targetBranch,"targetBranch");if(r.startsWith("-")||/[~^:?*[\\\s]/u.test(r)||r.includes("..")||r.includes("@{"))throw new Error("Invalid Classic delivery targetBranch");let i={action:n.action,targetBranch:r};if(n.remote!==void 0){let s=Me(n.remote,"remote");if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/u.test(s))throw new Error("Classic delivery remote must be a name, not a URL");i.remote=s}if(n.commit!==void 0){let s=Me(n.commit,"commit");if(!/^(?:[a-fA-F0-9]{40}|[a-fA-F0-9]{64})$/u.test(s))throw new Error("Classic delivery commit must be a full object ID");i.commit=s.toLowerCase()}if(n.prUrl!==void 0){let s=Me(n.prUrl,"prUrl"),o=new URL(s);if(o.protocol!=="https:"||o.username||o.password)throw new Error("Invalid Classic delivery prUrl");i.prUrl=s}return i}function $f(t){let e=(0,Nf.parseDocument)(t,{uniqueKeys:!0});if(e.errors.length)throw new Error("Invalid Classic delivery change state");return qt(e.toJS())}function Tf(t,e){if(typeof t.run_id=="string"&&t.run_id)return`run:${t.run_id}`;let n=t.archived===!0?Xe.basename(e).replace(/^\d{4}-\d{2}-\d{2}-/u,""):Xe.basename(e);if(typeof t.created_at!="string"||typeof t.base_ref!="string")throw new Error("Classic delivery requires stable change identity");return`legacy:${bs("sha256").update(JSON.stringify([n,t.created_at,t.base_ref])).digest("hex")}`}async function Yk(t,e){return $f(await I(t,Xe.join(e,".comet.yaml"),{label:"Classic delivery state"}))}var ks=class extends Error{constructor(e,n){super(`Classic delivery git command timed out: ${[e,...n].join(" ")}`)}};function uc(t,e,n,r){return Ln(e,n,{cwd:t,timeoutMs:5e3,env:_f({authentication:r})}).trim()}function Mr(t,e,n,r=!1){try{return uc(t,e,n,r)}catch{return null}}function Vk(t,e,n,r=!1){try{return uc(t,e,n,r)}catch(i){if(!(i instanceof Tn)||!i.timedOut)return null;try{return uc(t,e,n,r)}catch(s){if(s instanceof Tn&&s.timedOut)throw new ks(e,n);return null}}}function Lr(t,e){return Mr(t,"git",["-C",t,...e])}function qr(t,e){return Vk(t,"git",["-C",t,...e])}function Pf(t,e,n=!1){return Mr(t,"git",["-C",t,"remote","get-url",...n?["--push"]:[],e],!0)}function Xk(t,e){let n=Xe.relative(t,e).replaceAll("\\","/");return[`:(literal)${n}`,...[".comet-state.lock",".comet-state-transaction.json"].map(r=>`:(exclude,literal)${n}/${r}`)]}function Af(t,e,n,r){let i=Xe.relative(t,e).replaceAll("\\","/"),s=Xk(t,e),o=qr(t,["show",`${n}:${i}/.comet.yaml`]);if(!o)return!1;try{let a=$f(o);return a.archived===!0&&Tf(a,e)===r&&qr(t,["merge-base","--is-ancestor",n,"HEAD"])!==null&&qr(t,["diff","--quiet","--no-ext-diff","--no-textconv",n,"--",...s])!==null&&qr(t,["ls-files","--others","--exclude-standard","--",...s])===""}catch(a){if(a instanceof ks)throw a;return!1}}function Qk(t,e){let n=`${bs("sha256").update(e).digest("hex")}.json`,r=qr(t,["rev-parse","--path-format=absolute","--git-common-dir"]);return[{root:t,file:Xe.join(t,".comet","classic-deliveries",n)},...r?[{root:r,file:Xe.join(r,"comet","classic-deliveries",n)}]:[]]}async function Zk(t,e){let n=null;for(let r of Qk(t,e)){if(!await G(r.root,r.file,{label:"Classic delivery receipt",expected:"file"}))continue;let i=qt(JSON.parse(await I(r.root,r.file,{label:"Classic delivery receipt"})));if(Cs(i,["schemaVersion","changeIdentity","authorizationId","invalidated","commit","prUrl"]),i.schemaVersion!==1||i.changeIdentity!==e)throw new Error("Invalid Classic delivery receipt schema or identity");if(i.invalidated!==void 0&&typeof i.invalidated!="boolean")throw new Error("Invalid Classic delivery receipt invalidation");let s=dc({action:"local",targetBranch:"main",...i.commit!==void 0?{commit:i.commit}:{},...i.prUrl!==void 0?{prUrl:i.prUrl}:{}}),o={schemaVersion:1,changeIdentity:e,authorizationId:Me(i.authorizationId,"authorizationId"),...i.invalidated===!0?{invalidated:!0}:{},...s.commit?{commit:s.commit}:{},...s.prUrl?{prUrl:s.prUrl}:{}};if(n&&JSON.stringify(n)!==JSON.stringify(o))throw new Error("Conflicting Classic delivery receipts");n=o}return n}function eb(t){return t.authorizationId===void 0?`legacy:${bs("sha256").update(JSON.stringify(t)).digest("hex")}`:Me(t.authorizationId,"authorizationId")}function Of(t,e,n){return e===n||Lr(t,["merge-base","--is-ancestor",e,n])!==null}function tb(t){let e=/^git@([^:/]+):([^/]+\/[^/]+)$/u.exec(t);try{let n=new URL(e?`ssh://git@${e[1]}/${e[2]}`:t);if(!["https:","ssh:"].includes(n.protocol)||n.password||n.search||n.hash||n.port||n.protocol==="https:"&&n.username)return null;let r=n.pathname.replace(/\.git\/?$/u,"").replace(/\/$/u,"").split("/").filter(Boolean);return r.length!==2||r.some(i=>!/^[a-zA-Z0-9_.-]+$/u.test(i))?null:`${n.hostname}/${r.join("/")}`.toLowerCase()}catch{return null}}function vs(t,e){try{let n=new URL(t);if(n.protocol!=="https:"||n.username||n.password||n.port||n.search||n.hash)return null;let r=/^\/([^/]+)\/([^/]+)\/pull\/([1-9]\d*)\/?$/u.exec(n.pathname);return r&&`${n.hostname}/${r[1]}/${r[2]}`.toLowerCase()===e?`https://${n.hostname}/${r[1]}/${r[2]}/pull/${r[3]}`:null}catch{return null}}async function Lf(t,e,n={}){let r=await jf(t,e,"delivery.json");if(r===void 0)return{delivery:null,verification:{status:"needsAuthorization"}};let i=qt(r);if(i.schemaVersion!==1)throw new Error("Unsupported Classic delivery schemaVersion");let s=dc(i,!0),o=await Yk(t,e),a=Tf(o,e);if(i.changeIdentity!==a)throw new Error("Classic delivery change identity mismatch");let c=eb(i),l=await Gk(t,a);if(l&&l.previousAuthorizationId!==c)throw new Error("Classic delivery reauthorization is stale for the sealed authorization");let u=l?{action:l.action,targetBranch:l.targetBranch,...l.remote===void 0?{}:{remote:l.remote}}:s,d=l?.authorizationId??c,f=await Zk(t,a),p=f?.authorizationId===d?f:null;if(p?.invalidated)return{delivery:null,verification:{status:"needsAuthorization",invalidated:!0}};for(let $ of["commit","prUrl"]){if($==="commit"&&p?.[$]&&u[$]&&p[$]!==u[$])throw new Error("Classic delivery receipt conflicts with authorization evidence");p?.[$]&&(u[$]=p[$])}let g=i.authorizedRemoteUrl===void 0?void 0:Me(i.authorizedRemoteUrl,"authorizedRemoteUrl"),m=l?.authorizedRemoteUrl??g,h={...u,schemaVersion:1,changeIdentity:a,authorizationId:d,...m?{authorizedRemoteUrl:m}:{}},v=Lr(t,["symbolic-ref","--quiet","--short","HEAD"]),y=Xe.relative(t,e).replaceAll("\\","/"),S=null;!u.commit&&o.archived===!0&&(S=Lr(t,["log","-20","--format=%H","HEAD","--",`:(literal)${y}/.comet.yaml`])?.split(/\r?\n/u).find(U=>/^[a-f0-9]{40,64}$/u.test(U)&&Af(t,e,U,a))??null);let b=u.commit??S,x=!!b&&Lr(t,["cat-file","-t",b])==="commit",w=o.archived===!0&&x&&Af(t,e,b,a),C=v===u.targetBranch&&(!o.bound_branch||l!==null||o.bound_branch===v)&&w,k=!1,_=!1,P=null,O=n.verifyRemote&&u.action!=="local"?"unavailable":"notChecked",R="notChecked";if(n.verifyRemote&&C&&u.action!=="local"&&u.remote&&m&&Pf(t,u.remote)===m&&Pf(t,u.remote,!0)===m){let $=`refs/heads/${u.targetBranch}`,U=Mr(t,"git",["-C",t,"-c","protocol.allow=never","-c","protocol.https.allow=always","-c","protocol.ssh.allow=always","-c","protocol.file.allow=always","ls-remote","--refs",u.remote,$],!0),se=U?.split(/\r?\n/u)??[],de=se.length===1?/^([a-f0-9]{40}|[a-f0-9]{64})\t(.+)$/u.exec(se[0]):null,q=de?.[2]===$?de[1]:null;k=!!b&&!!q&&Of(t,b,q),O=k?"verified":U===""?"missing":U===null||!q||Lr(t,["cat-file","-t",q])!=="commit"?"unavailable":"missing";let W=tb(m),oe=W&&u.prUrl?vs(u.prUrl,W):null,Ce=k||U==="",si=we=>we.headRefName===u.targetBranch&&typeof we.headRefOid=="string"&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(we.headRefOid)&&(k?we.headRefOid===q&&["OPEN","MERGED"].includes(we.state):U===""&&we.state==="MERGED"&&!!b&&Of(t,b,we.headRefOid));if(Ce&&u.action==="pr"&&(R="unavailable"),Ce&&u.action==="pr"&&oe&&W){let we=Mr(t,"gh",["pr","view",oe,"--repo",W,"--json","url,headRefName,headRefOid,state"],!0);try{let te=we?qt(JSON.parse(we)):null;_=!!te&&typeof te.url=="string"&&vs(te.url,W)===oe&&si(te),R=_?"verified":te?"missing":"unavailable"}catch{_=!1,R="unavailable"}}else if(Ce&&u.action==="pr"&&!u.prUrl&&W){let we=Mr(t,"gh",["pr","list","--repo",W,"--head",u.targetBranch,"--state","all","--json","url,headRefName,headRefOid,state","--limit","100"],!0);try{let te=we===null?null:JSON.parse(we);if(!Array.isArray(te)||te.length>=100)throw new Error("Incomplete PR discovery");let Xt=te.map(qt).filter(We=>typeof We.url=="string"&&vs(We.url,W)&&si(We));Xt.length===1?(P=vs(Xt[0].url,W),_=!0,R="verified"):R=Xt.length===0?"missing":"unavailable"}catch{R="unavailable"}}}return{delivery:h,verification:{status:C&&(u.action==="local"||(u.action==="push"?k:_))?"complete":"needsVerification",currentBranch:v,commitExists:x,archiveCommitted:w,observedCommit:S,observedPrUrl:P,remoteVerified:k,prVerified:_,remoteStatus:O,prStatus:R}}}var fp=Pe(xe(),1);import SS from"node:path";import{createHash as cp}from"crypto";import{createHash as nb}from"node:crypto";function Qe(t,e){return t.replaceAll("\\","/").endsWith("/tasks.md")&&(e=$r(e)),nb("sha256").update(e).digest("hex")}import je from"node:path";import{createHash as hb}from"node:crypto";import{AsyncLocalStorage as rb}from"async_hooks";import{promises as qf}from"fs";import Fr from"path";var Dr=new rb;function ib(t,e){let n=Fr.relative(t,e);return n===""||!Fr.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${Fr.sep}`)}async function sb(t){let e=Fr.resolve(t.invocationCwd??process.cwd()),n=Fr.resolve(t.projectRoot??await dt(e)),[r,i]=await Promise.all([qf.realpath(e),qf.realpath(n)]);if(!ib(i,r))throw new Error(`Classic command invocation cwd is outside the discovered project: ${e}`);return{invocationCwd:e,projectRoot:n,observations:new Map}}async function ob(t,e){let n=Dr.getStore();if(n)return e(n);let r=await sb(t);return Dr.run(r,()=>e(r))}function T(){let t=Dr.getStore();if(!t)throw new Error("Classic command project context is unavailable");return t.projectRoot}function un(){let t=Dr.getStore();if(!t)throw new Error("Classic command invocation context is unavailable");return t.invocationCwd}async function Mf(t,e){let n=Dr.getStore();if(!n)return e();let r=n.observations.get(t);if(r)return r;let i=e();n.observations.set(t,i);try{return await i}catch(s){throw n.observations.delete(t),s}}function qn(t){return(e,n)=>ob(n,()=>t(e,n))}var Hf=Pe(xe(),1);import{spawnSync as ub}from"child_process";Tr();import{existsSync as Ff,readFileSync as ab}from"node:fs";import Mn from"node:path";function cb(t){let e=t.replaceAll(`\r
|
|
144
144
|
`,`
|
|
145
|
-
`).trim(),n=/^@ECHO off\nGOTO start\n:find_dp0\nSET dp0=%~dp0\nEXIT \/b\n:start\nSETLOCAL\nCALL :find_dp0\n\nIF EXIST "%dp0%\\node\.exe" \(\n {2}SET "_prog=%dp0%\\node\.exe"\n\) ELSE \(\n {2}SET "_prog=node"\n {2}SET PATHEXT=%PATHEXT:;\.JS;=;%\n\)\n\nendLocal & goto #_undefined_# 2>NUL \|\| title %COMSPEC% & "%_prog%" {2}"%dp0%\\([^"%\r\n]+\.(?:mjs|cjs|js))" %\*$/u.exec(e);if(n)return{target:n[1]};let r=/^@SETLOCAL\n(?:@IF NOT DEFINED NODE_PATH \(\n {2}@SET "NODE_PATH=([^"\r\n]+)"\n\) ELSE \(\n {2}@SET "NODE_PATH=\1;%NODE_PATH%"\n\)\n)?@IF EXIST "%~dp0\\node\.exe" \(\n {2}"%~dp0\\node\.exe" {2}"%~dp0\\([^"%\r\n]+\.(?:mjs|cjs|js))" %\*\n\) ELSE \(\n {2}@SET PATHEXT=%PATHEXT:;\.JS;=;%\n {2}node {2}"%~dp0\\\2" %\*\n\)$/u.exec(e);return r?{target:r[2],...r[1]?{nodePath:r[1]}:{}}:null}function Df(t,e,n){if((n.platform??process.platform)!=="win32")return{command:t,args:[...e]};let r=ln(t,n.env??process.env,n.cwd),i=Mn.extname(r).toLowerCase();if([".mjs",".cjs",".js"].includes(i))return{command:process.execPath,args:[Mn.resolve(n.cwd,r),...e]};if(i===".cmd"){let s=cb(ab(r,"utf8"));if(s){let o=Mn.resolve(Mn.dirname(r),s.target);if(!Ff(o))throw new Error(`Node CLI entry is missing: ${o}`);let a=Mn.join(Mn.dirname(r),"node.exe"),c={...n.env??process.env},l=Object.keys(c).find(d=>d.toUpperCase()==="NODE_PATH"),u=l?c[l]:void 0;return s.nodePath&&(l&&delete c[l],c.NODE_PATH=s.nodePath+(u?`;${u}`:"")),{command:Ff(a)?a:process.execPath,args:[o,...e],...s.nodePath?{env:c}:{}}}}if([".cmd",".bat",".ps1"].includes(i))throw new Error(`Unsupported Node CLI shim: ${r}. Use a standard npm/pnpm .cmd launcher or the Node CLI .js/.mjs/.cjs entry; no shell fallback is allowed.`);return{command:r,args:[...e]}}function fc(t,e){let n=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)?u:{},r=n(t),i=n(r.entry),s=n(r.state??i.state??r),o=n(r.preparation??r.workspace??i.workspace),a=n(r.continuation??i.continuation),c=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:e??null,l=s.stateVersion??s.state_version;return{phase:typeof s.phase=="string"?s.phase:null,status:typeof s.status=="string"?s.status:null,stateVersion:typeof l=="number"?l:null,workspace:{cwd:c},continuation:Object.keys(a).length?{...a,cwd:c}:null}}var Wf=
|
|
146
|
-
Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function Es(t){let e=dn(t);if(e)throw new Error(e)}function fb(t,e){return{label:K(t,e),directory:e}}async function Ss(t,e,n){let r=fb(t,e);if(!(await fe(t,e,{label:n,expected:"directory"})).exists)return{change:r,exists:!1,stateExists:!1};let s=await fe(t,Wr.join(e,".comet.yaml"),{label:`${n} state`,expected:"file"});return{change:r,exists:!0,stateExists:s.exists}}function mb(t,e){let n=e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${n}$`,"u").test(t)}async function pb(t,e,n,r={}){if(!r.skipExactCompatibility){let o=await Ss(t,Wr.join(e,n),`Classic archived change ${n}`);if(o.exists)return o.change}if(!(await fe(t,e,{label:"Classic archive directory",expected:"directory"})).exists)return null;let s=[];for(let o of await mc.readdir(e,{withFileTypes:!0})){if(!mb(o.name,n))continue;let a=await Ss(t,Wr.join(e,o.name),`Classic archived change ${o.name}`);a.exists&&a.stateExists&&s.push(a.change)}return s.sort((o,a)=>a.directory.localeCompare(o.directory))[0]??null}async function Kf(t,e=process.cwd()){Es(t);let n=await ue(e),r=await Ss(n.projectRoot,Wr.join(n.changesDir,t),`Classic active change ${t}`);return{...r.change,exists:r.exists,stateExists:r.stateExists}}async function xs(t,e=process.cwd()){Es(t);let n=await ue(e),r=await Ss(n.projectRoot,Wr.join(n.changesDir,t),`Classic active change ${t}`);if(r.exists)return r.change;let i=await pb(n.projectRoot,n.archiveDir,t);return i||r.change}var gb=".comet/archive-requirements.json";async function zf(t,e){let n=Oe.join(e,gb),r=["proposal.md","design.md","tasks.md"];if(await G(t,n,{label:"Classic archive requirements",expected:"file"})){let s=JSON.parse(await I(t,n,{label:"Classic archive requirements"}));if(s?.schema!=="comet.classic.archive-requirements.v1")throw new Error("Unsupported Classic archive requirements");r=s.files}if(!Array.isArray(r)||!r.includes("proposal.md")||!r.includes("tasks.md")||r.some(s=>typeof s!="string"||!(["proposal.md","design.md","tasks.md"].includes(s)||/^specs\/(?:[^/\\:]+\/)+spec\.md$/u.test(s))||s.split("/").some(o=>o==="."||o==="..")))throw new Error("Invalid Classic archive required files");let i=[];for(let s of r)await Pe(t,Oe.join(e,s),"Classic archived required file")||i.push(`Required archived artifact is missing or empty: ${s}`);return i}function wb(t){if(!t||typeof t!="object")throw new Error("Unsupported OpenSpec status: expected an object");let e=t;if(!Array.isArray(e.artifacts)||!Array.isArray(e.applyRequires))throw new Error("OpenSpec must expose artifacts and applyRequires; upgrade to a supported version");let n=new Map;for(let a of e.artifacts){if(!a||typeof a!="object"||typeof a.id!="string"||typeof a.outputPath!="string"||!["done","skipped","ready","blocked"].includes(a.status)||!Array.isArray(a.requires)||a.requires.some(c=>typeof c!="string"))throw new Error("OpenSpec must expose dependency edges for every artifact; upgrade to a supported version");if(n.has(a.id))throw new Error(`Duplicate OpenSpec artifact: ${a.id}`);n.set(a.id,a)}let r=[],i=new Set,s=new Set,o=a=>{if(typeof a!="string"||!n.has(a))throw new Error(`Missing OpenSpec dependency: ${String(a)}`);if(s.has(a))throw new Error(`Cyclic OpenSpec dependency: ${a}`);if(i.has(a))return;s.add(a);let c=n.get(a);for(let l of c.requires)o(l);s.delete(a),i.add(a),r.push(c)};for(let a of[...e.applyRequires,"proposal","tasks"])o(a);return r}async function Br(t,e){let n=Oe.join(e,".openspec.yaml");if(!await G(t,n,{label:"OpenSpec change metadata",expected:"file"}))return{source:"legacy",required:["proposal","design","tasks"],skipped:[],designRequired:!0,files:["proposal.md","design.md","tasks.md"].map(g=>Oe.join(e,g)),problems:[]};let r=(0,Hf.parseDocument)(await I(t,n,{label:"OpenSpec change metadata"}));if(r.errors.length)throw new Error(`Invalid OpenSpec metadata: ${r.errors[0].message}`);let i=await ue(t),s=await ut(t,Oe.join(e,"specs")),o=hb("sha256");for(let g of[Oe.join(i.openSpecRoot,"config.yaml"),n,...["proposal.md","design.md","tasks.md"].map(m=>Oe.join(e,m)),...s])o.update(g),await G(t,g,{label:"OpenSpec observation input",expected:"file"})?o.update(await I(t,g,{label:"OpenSpec observation input"})):o.update("<missing>");let a=()=>Uf(["status","--change",Oe.basename(e),"--json"],t),l=await G(t,Oe.join(i.openSpecRoot,"schemas"),{label:"OpenSpec local schemas",expected:"directory"})?await a():await Mf(`openspec-status:${e}:${o.digest("hex")}`,a);if(l.exitCode!==0)throw new Error(`Cannot inspect OpenSpec artifact requirements: ${l.stderr??l.exitCode}`);let u;try{u=JSON.parse(l.stdout??"")}catch{throw new Error("Unsupported OpenSpec status: expected JSON")}if(!u||typeof u.changeRoot!="string"||Oe.resolve(u.changeRoot)!==Oe.resolve(e))throw new Error("OpenSpec status resolves outside the selected Classic change");let d=wb(u),f=s,p={source:"openspec",required:d.map(g=>g.id),skipped:[],designRequired:d.some(g=>g.id==="design"),files:[],problems:[]};for(let g of d){if(!["proposal","specs","design","tasks"].includes(g.id))throw new Error(`Unsupported Classic artifact: ${g.id}; use a schema with supported artifact roles`);if(g.id!=="specs"&&g.outputPath!==`${g.id}.md`)throw new Error(`Unsupported Classic artifact output: ${g.outputPath}`);if(g.status==="skipped"){if(g.id!=="specs"||r.get("skip_specs")!==!0||f.length)throw new Error("OpenSpec skipped specs require explicit skip_specs: true and no conflicting spec files");p.skipped.push(g.id);continue}let m=g.outputPath.replaceAll("\\","/");if(Oe.posix.isAbsolute(m)||/^[A-Za-z]:/u.test(m)||m.split("/").includes(".."))throw new Error(`Unsafe OpenSpec artifact path: ${m}`);let h;if(g.id==="specs"&&["specs/**/*.md","specs/**/spec.md","specs/*/spec.md"].includes(m))h=f;else{if(["?","*","[","]","{","}"].some(v=>m.includes(v)))throw new Error(`Unsupported OpenSpec artifact pattern: ${m}`);h=[Oe.join(e,m)]}(g.status!=="done"||!h.length)&&p.problems.push(`Required OpenSpec artifact is not complete: ${g.id}`);for(let v of h)await Pe(t,v,`OpenSpec required artifact ${g.id}`)||p.problems.push(`Required OpenSpec file is missing or empty: ${v}`),p.files.push(v)}return p}var lp=_e(Se(),1);import Dc from"path";import{promises as np}from"fs";import Ne from"path";import{fileURLToPath as rp}from"url";import qt from"path";le();Ye();import Ur from"path";function yb(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Jf(t,e,n,r){let i=de(n,"Classic handoff artifact pointer");if((await J(t,i,{label:"Classic handoff artifact",expected:"file"})).exists)return null;let o=await ue(t),a=`${K(t,o.changesDir)}/`,l=(o.artifactLayout==="docs"?[a,"openspec/changes/"]:[a]).find(y=>i.startsWith(y));if(!l)return null;let u=i.slice(l.length).split("/");if(u.length<4||u[1]!==".comet"||u.slice(2).some(y=>y.length===0))return null;let d=u[0];Es(d);let f=u.slice(2),p=Ur.resolve(e);if(Ur.dirname(p)!==Ur.resolve(o.archiveDir))return null;let g=Ur.basename(p),m=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(g);if(g!==d&&m?.[1]!==d)return null;await J(t,K(t,p),{label:"Classic archived change directory",expected:"directory"});let h=Ur.join(p,".comet",...f),v=K(t,h);try{return await Y(t,v,r,{label:"Historical Classic archived handoff artifact"}),v}catch(y){if(yb(y))return null;throw y}}le();function pc(t,e){return qt.relative(t,e).split(qt.sep).join("/")}async function Kr(t,e,n,r,i){if(!n)return{code:e,satisfied:!1};let s=n.replaceAll("\\","/");if(i)return{code:e,satisfied:!1,source:s,detail:`Classic layout is unsafe or unavailable: ${i instanceof Error?i.message:String(i)}`};try{if(r){let a=r.artifactLayout==="legacy"?"docs":"legacy",c=K(t,gs(t,a).openSpecRoot);if((s===c||s.startsWith(`${c}/`))&&(await J(t,s,{label:`${e} artifact`,expected:"file"})).exists)return{code:e,satisfied:!1,source:s,detail:"standalone OpenSpec root is not a Comet artifact root"}}let o=await Qa(t,s,{label:`${e} artifact`});return{code:e,satisfied:o,source:s,...o?{resolvedSource:s}:{}}}catch(o){return{code:e,satisfied:!1,source:s,detail:`unsafe artifact pointer outside the project or through a special path: ${o instanceof Error?o.message:String(o)}`}}}async function vb(t,e,n,r){try{r??=await ue(t)}catch(s){return{code:"design.handoff",satisfied:!1,...n?{source:n.replaceAll("\\","/")}:{},detail:`Classic layout is unsafe or unavailable for handoff evidence: ${s instanceof Error?s.message:String(s)}`}}let i=await Kr(t,"design.handoff",n,r);if(!n||i.satisfied||i.detail)return i;try{let s=await Jf(t,e,n,Number.MAX_SAFE_INTEGER);return s?{...i,satisfied:!0,resolvedSource:s,detail:`resolved historical legacy pointer from archived change: ${s}`}:i}catch(s){return{...i,satisfied:!1,detail:`unsafe archived handoff fallback: ${s instanceof Error?s.message:String(s)}`}}}async function _s(t,e,n){return Kr(t,e,pc(t,n))}async function kb(t,e){let n=qt.join(e,"specs"),r;try{r=await ut(t,n)}catch(i){return i.code==="ENOENT"?{code:"openspec.delta-spec",satisfied:!1}:{code:"openspec.delta-spec",satisfied:!1,detail:`unsafe delta-spec path: ${i instanceof Error?i.message:String(i)}`}}return{code:"openspec.delta-spec",satisfied:r.length>0,source:r[0]?pc(t,r[0]):void 0,detail:`${r.length} delta spec${r.length===1?"":"s"}`}}async function bb(t,e){let n,r=pc(t,e);try{n=(await Y(t,r,Number.MAX_SAFE_INTEGER,{label:"Classic tasks artifact"})).bytes.toString("utf8")}catch(o){return o.code==="ENOENT"?{code:"build.tasks-complete",satisfied:!1}:{code:"build.tasks-complete",satisfied:!1,source:r,detail:`unsafe tasks artifact: ${o instanceof Error?o.message:String(o)}`}}let i;try{i=Ae(n)}catch(o){return{code:"build.tasks-complete",satisfied:!1,source:r,detail:`malformed tasks.md: ${o instanceof Error?o.message:String(o)}`}}let s=i.filter(o=>o.completed).length;return{code:"build.tasks-complete",satisfied:i.length>0&&s===i.length,source:r,detail:`${s} of ${i.length} tasks complete`}}function Mt(t,e){return t.some(n=>n.code===e&&n.satisfied)}async function Ft(t,e){let n=await lt(t),r=e.classic,i=qt.join(t,"proposal.md"),s=qt.join(t,"design.md"),o=qt.join(t,"tasks.md"),a=e.run?qt.resolve(t,e.run.checkpointRef):qt.join(t,".comet","checkpoint.json"),c,l;try{c=await ue(n)}catch(f){l=f}let u=await Promise.all([_s(n,"openspec.proposal",i),_s(n,"openspec.design",s),_s(n,"openspec.tasks",o),kb(n,t),Kr(n,"design.document",r?.designDoc??null,c,l),(async()=>{let f=await Kr(n,"build.plan",r?.plan??null,c,l);if(!f.satisfied)return f;try{let p=await Ir(n,r?.plan??null,{requireNonempty:r?.buildMode==="autonomous"});return p.status==="ready"?f:{code:f.code,source:f.source,satisfied:!1,detail:`Implementation plan is ${p.status}`}}catch(p){return{code:f.code,source:f.source,satisfied:!1,detail:p instanceof Error?p.message:String(p)}}})(),bb(n,o),Kr(n,"verification.report",r?.verificationReport??null,c,l),vb(n,t,r?.handoffContext??null,c),_s(n,"run.checkpoint",a)]),d=u.find(f=>f.code==="design.handoff");return d&&!r?.handoffHash&&(d.satisfied=!1,d.detail="handoff hash is missing"),u.push({code:"archive.confirmed",satisfied:r?.archiveConfirmation==="confirmed"}),u}import{createHash as YC,randomUUID as VC}from"crypto";import{promises as Lc}from"fs";import ft from"path";function Cb(t){return t.classicProfile??t.workflow}function Sb(t){return t.isolation!==null&&mf(t)}function Eb(t){return(t.buildMode==="direct"||t.buildMode==="autonomous")&&t.tddMode==="direct"&&t.isolation!==null&&t.verifyMode==="light"}function xb(t,e,n){if(t!=="full"&&e.verifyResult==="fail")return`${t}.build.execute`;if(t==="full"){if(Mt(n,"build.plan")&&e.buildPause==="plan-ready")return"full.build.plan-ready";if(!Sb(e))return"full.build.configure";if(!Mt(n,"build.plan"))return"full.build.plan";if(e.verifyResult==="fail")return"full.build.fix"}else if(!Eb(e))throw new Error(`${t} build configuration is incomplete`);return Mt(n,"build.tasks-complete")?`${t}.build.complete`:`${t}.build.execute`}function _b(t,e,n){return e.verifyResult!=="pass"||!Mt(n,"verification.report")?`${t}.verify.run`:`${t}.verify.branch`}function Rb(t,e){if(e.verifyResult!=="pass")throw new Error("archive requires verify_result=pass");return e.archiveConfirmation==="confirmed"?`${t}.archive.execute`:`${t}.archive.confirm`}function Fn(t,e){let n=Cb(t);if(t.archived&&t.phase!=="archive")throw new Error("archived=true requires phase=archive");if(t.archived)return"completed";if(n!=="full"&&t.phase==="design")throw new Error(`${n} workflow cannot enter design`);switch(t.phase){case"open":return`${n}.open`;case"design":return Mt(e,"design.handoff")?"full.design.document":"full.design.handoff";case"build":return xb(n,t,e);case"verify":return _b(n,t,e);case"archive":return Rb(n,t)}}rm();le();var Ls=_e(Se(),1);it();le();import Wt from"path";import{AsyncLocalStorage as kC}from"node:async_hooks";$s();var bm=["full","hotfix","tweak"],mn=1,rC=["open","design","build","verify","archive"],iC=["en","zh-CN"],sC=["off","beta"],oC=["subagent-driven-development","executing-plans","direct","autonomous"],aC=["plan-ready"],cC=["confirmed"],lC=["tdd","direct"],uC=["off","standard","thorough"],dC=["current","branch","worktree"],fC=["light","full"],mC=["pending","pass","fail"],pC=["pending","handled"],hC=["pending","confirmed"],Qe=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","check_epoch","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],pn=["run_id"],gC=new Set([...Qe,...pn]),Sm=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function xc(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Bn(t,e){let n=t[e];if(n==null||n==="")return null;if(typeof n!="string")throw new Error(`Invalid Classic state: ${e} must be a string or null`);return n}function ye(t,e,n,r=!0){let i=t[e];if(i==null||i===""){if(r)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof i!="string"||!n.includes(i))throw new Error(`Invalid Classic state: ${e} must be one of ${n.join(", ")}${r?" or null":""}`);return i}function _c(t,e,n=!0){let r=t[e];if(r==null||r===""){if(n)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof r!="boolean")throw new Error(`Invalid Classic state: ${e} must be true or false`);return r}function Cm(t,e,n=0){let r=t[e];if(r==null||r==="")return n;if(typeof r!="number"||!Number.isSafeInteger(r)||r<0)throw new Error(`Invalid Classic state: ${e} must be a non-negative integer`);return r}function Ts(t,e){let n=Bn(t,e);if(n===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${e} must be a relative repository path`);return n}function wC(t,e){let n=Bn(t,e);if(n!==null&&!/^[a-f0-9]{64}$/u.test(n))throw new Error(`Invalid Classic state: ${e} must be a sha256 hex digest`);return n}function yC(t){let e=t.classic_migration;if(e==null||e==="")return null;if(e!==mn)throw new Error(`Invalid Classic state: classic_migration must be ${mn}`);return e}function vC(t){if(!Qe.some(n=>xc(t,n)))return null;for(let n of Sm)if(!xc(t,n))return null;return{workflow:ye(t,"workflow",bm,!1),language:ye(t,"language",iC),phase:ye(t,"phase",rC,!1),contextCompression:ye(t,"context_compression",sC),buildMode:ye(t,"build_mode",oC),buildPause:ye(t,"build_pause",aC),subagentDispatch:ye(t,"subagent_dispatch",cC),tddMode:ye(t,"tdd_mode",lC),reviewMode:ye(t,"review_mode",uC),isolation:ye(t,"isolation",dC),boundBranch:Bn(t,"bound_branch"),verifyMode:ye(t,"verify_mode",fC),autoTransition:_c(t,"auto_transition"),baseRef:Bn(t,"base_ref"),designDoc:Ts(t,"design_doc"),plan:Ts(t,"plan"),verifyResult:ye(t,"verify_result",mC,!1),verifyFailures:Cm(t,"verify_failures"),...xc(t,"check_epoch")?{checkEpoch:Cm(t,"check_epoch")}:{},verificationReport:Ts(t,"verification_report"),branchStatus:ye(t,"branch_status",pC),createdAt:Bn(t,"created_at"),verifiedAt:Bn(t,"verified_at"),archiveConfirmation:ye(t,"archive_confirmation",hC),archived:_c(t,"archived",!1),directOverride:_c(t,"direct_override"),handoffContext:Ts(t,"handoff_context"),handoffHash:wC(t,"handoff_hash"),classicProfile:ye(t,"classic_profile",bm),classicMigration:yC(t)}}function Rc(t,e){let n=e??null;if(n===null&&e===void 0&&t.run_id&&t.skill)try{n=Dn(t)}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(i.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:r})}return{classic:vC(t),run:n,unknownKeys:Object.keys(t).filter(r=>!gC.has(r))}}function Em(t){return{workflow:t.workflow,language:t.language,phase:t.phase,context_compression:t.contextCompression,build_mode:t.buildMode,build_pause:t.buildPause,subagent_dispatch:t.subagentDispatch,tdd_mode:t.tddMode,review_mode:t.reviewMode,isolation:t.isolation,bound_branch:t.boundBranch,verify_mode:t.verifyMode,auto_transition:t.autoTransition,base_ref:t.baseRef,design_doc:t.designDoc,plan:t.plan,verify_result:t.verifyResult,verify_failures:t.verifyFailures,...t.checkEpoch===void 0?{}:{check_epoch:t.checkEpoch},verification_report:t.verificationReport,branch_status:t.branchStatus,created_at:t.createdAt,verified_at:t.verifiedAt,archive_confirmation:t.archiveConfirmation,archived:t.archived,direct_override:t.directOverride,handoff_context:t.handoffContext,handoff_hash:t.handoffHash,classic_profile:t.classicProfile,classic_migration:t.classicMigration}}$s();var xm=new kC,Pc=".comet-state-transaction.json";async function me(t,e){let n=Wt.resolve(t);return xm.getStore()===n?e():(await J(n,".comet-state.lock",{label:"Classic state lock",expected:"file"}),tm(Wt.join(n,".comet-state.lock"),()=>xm.run(n,async()=>(await Rm(n),e()))))}async function Ac(t,e){try{return(await Y(t,e,Number.MAX_SAFE_INTEGER,{label:"Classic state transaction"})).bytes.toString("utf8")}catch(n){if(n.code==="ENOENT")return null;throw n}}function bC(t){if(t===null)return null;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Invalid Classic transaction Run");let e=t,n=Dn({run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:e.retries});if(!n)throw new Error("Invalid Classic transaction Run identity");return n}async function Rm(t){let e=await Ac(t,Pc);if(e===null)return;let n=JSON.parse(e);if(!n||n.schema!=="comet.classic.state-transaction.v1"||n.beforeYaml!==null&&typeof n.beforeYaml!="string"||typeof n.afterYaml!="string")throw new Error("Invalid Classic state transaction");let r=await Ac(t,".comet.yaml");if(r!==n.beforeYaml&&r!==n.afterYaml)throw new Error("Classic state transaction conflicts with current YAML; preserve files for recovery");let i=bC(r===n.afterYaml?n.afterRun:n.beforeRun);i?await Wn(t,i):await Jr(t),await Cn(Wt.join(t,Pc),{containedRoot:t})}function Gr(t){let e=t.toJS();if(e===null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic state document: root must be a mapping");return e}function _m(t,e,n){t.get(e)!==n&&t.set(e,n)}function CC(t,e){if(e.classic)for(let[n,r]of Object.entries(Em(e.classic)))n==="auto_transition"&&r===null&&!t.has(n)||_m(t,n,r);else for(let n of Qe)t.delete(n);Ec(t.toJS(),e.run),e.run?_m(t,"run_id",e.run.runId):t.delete("run_id")}function SC(t){let e=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let n of e)t.delete(n)}function EC(t){let e=!1;for(let n of["build_command","verify_command"])t.has(n)&&(t.delete(n),e=!0);return e}async function Pm(t){let e;try{e=(await Y(Wt.dirname(t),Wt.basename(t),Number.MAX_SAFE_INTEGER,{label:"Classic state document"})).bytes.toString("utf8")}catch(r){if(r.code!=="ENOENT")throw r;return new Ls.Document({})}let n=(0,Ls.parseDocument)(e);if(n.errors.length>0)throw new Error(`Invalid Classic state document: ${n.errors[0].message}`);return Gr(n),n}async function V(t,e={}){return me(t,()=>xC(t,e))}async function xC(t,e){let n=e.migrate!==!1,r=Wt.join(t,".comet.yaml"),i=await Pm(r),s=Gr(i),o=EC(i);o&&(s=Gr(i));let a=await Is(t);if(!a&&s.run_id&&s.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>($s(),km));a=c(s),a&&n&&(await Wn(t,a),SC(i),o=!0)}return o&&n&&await we(r,i.toString(),{containedRoot:t}),Rc(Gr(i),a)}async function hn(t,e,n={}){return me(t,()=>_C(t,e,n))}async function _C(t,e,n){let r=Wt.join(t,".comet.yaml"),i=await Pm(r),s=i.get("check_epoch")??0;if(typeof s=="number"&&s>(e.classic?.checkEpoch??0))throw new Error("Classic state changed during this operation; reload before retrying");CC(i,{...e,unknownKeys:e.unknownKeys??[]}),Rc(Gr(i),e.run??null);let o=await Ac(t,".comet.yaml"),a=i.toString();if(o===a){await n.beforeCommit?.(),e.run?await Wn(t,e.run):await Jr(t);return}let c=Wt.join(t,Pc);await we(c,JSON.stringify({schema:"comet.classic.state-transaction.v1",beforeYaml:o,afterYaml:a,beforeRun:await Is(t),afterRun:e.run}),{containedRoot:t});try{e.run?await Wn(t,e.run):await Jr(t),await we(r,a,{containedRoot:t,beforeCommit:n.beforeCommit})}catch(l){throw await Rm(t).catch(()=>{}),l}await Cn(c,{containedRoot:t}).catch(()=>{})}function Am(t,e,n){return{runId:e,skill:t.definition.metadata.name,skillVersion:t.definition.metadata.version,skillHash:n,orchestration:t.definition.orchestration.mode,currentStep:t.definition.orchestration.entry??null,iteration:0,pending:null,pendingRef:".comet/pending-action.json",trajectoryRef:".comet/trajectory.jsonl",contextRef:".comet/context.md",artifactsRef:".comet/artifacts.json",checkpointRef:".comet/checkpoint.json",status:"running",retries:{}}}Ns();import qs from"path";var Ze={trajectory:Number.MAX_SAFE_INTEGER,artifacts:Number.MAX_SAFE_INTEGER,context:Number.MAX_SAFE_INTEGER,pendingAction:Number.MAX_SAFE_INTEGER,checkpoint:Number.MAX_SAFE_INTEGER};function Ke(t,e){if(qs.isAbsolute(e))throw new Error("Run path must stay inside the change directory");let n=qs.resolve(t),r=qs.resolve(n,e);if(r!==n&&!r.startsWith(n+qs.sep))throw new Error("Run path must stay inside the change directory")}async function Bt(t,e,n,r={}){Ke(t,e),await As(t,e,`${JSON.stringify(n)}
|
|
147
|
-
`,
|
|
148
|
-
`,
|
|
149
|
-
`,
|
|
150
|
-
`,
|
|
151
|
-
`}async function Qm(t){let e=HC(t),n=await JC(t);return{document:e,files:n,hash:GC(e,n)}}async function Us(t){return(await Qm(t)).hash}async function Ym(t){try{return await
|
|
152
|
-
`),await
|
|
153
|
-
`));let l=await Us(a);if(l!==e)throw new Error(`calculated hash is ${l}`);return a}catch(i){throw new Error(`Skill snapshot is invalid or missing: ${e}`,{cause:i})}}async function Zm(t){try{return await Lc.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}function ep(t){return YC("sha256").update(t).digest("hex")}function XC(t){return ep(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)))))}function QC(t){return t.replaceAll(".","_").replaceAll("-","_")}async function ZC(t,e){let n=await lt(t),r=Object.fromEntries(e.filter(o=>o.satisfied&&o.source).map(o=>[QC(o.code),o.source])),i=ft.join(t,"subagent-progress.md");await Zm(i)&&(r.subagent_progress=ft.relative(n,i).split(ft.sep).join("/"));let s=e.find(o=>o.code==="design.handoff"&&o.satisfied);return s?.source&&(r.handoff_context=s.source),r}function eS(t,e,n){return[{sequence:1,timestamp:n,type:"run_started",runId:t.runId,data:{skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash}},{sequence:2,timestamp:n,type:"state_migrated",runId:t.runId,data:{kind:"classic",migrationVersion:mn,profile:e,source:"pre-migration"}}]}async function tS(t){await Promise.all(t.map(e=>Lc.rm(e,{recursive:!0,force:!0})))}async function tp(t,e){return me(t,()=>nS(t,e))}async function nS(t,e){let n=await V(t);if(!n.classic)throw new Error("Classic migration requires a legacy state projection");let r=n.classic,i=r.classicProfile??r.workflow;if(n.run){if(r.classicMigration!==mn)throw new Error("Classic Run exists without a supported classic_migration marker");if(n.run.skill!==e.skillPackage.definition.metadata.name)throw new Error(`Classic Run skill mismatch: expected ${e.skillPackage.definition.metadata.name}, got ${n.run.skill}`);if(await Us(e.skillPackage)!==n.run.skillHash)return await Tc(t,n.run.skillHash),{classic:r,run:n.run,evidence:await Ft(t,n),migrated:!1,snapshotDir:ft.join(t,".comet","skill-snapshots",n.run.skillHash)};let f=await $c(e.skillPackage,t);return{classic:r,run:n.run,evidence:await Ft(t,n),migrated:!1,snapshotDir:f.snapshotDir}}let s=await Ft(t,n),o=Fn(r,s);if(!e.skillPackage.definition.orchestration.steps?.some(d=>d.id===o))throw new Error(`Classic Skill package does not define resolved step: ${o}`);let a=await Us(e.skillPackage),c=ft.join(t,".comet","skill-snapshots",a),l=await Zm(c),u=[];try{let d=await $c(e.skillPackage,t),f=Am(e.skillPackage,e.runId?.()??VC(),d.hash);f.currentStep=o,o==="completed"&&(f.status="completed");let p={...r,classicProfile:i,classicMigration:mn},g=await ZC(t,s),m=await lt(t),h=s.find(b=>b.code==="design.handoff"&&b.satisfied),v=null;h?.source&&(v=await I(m,h.resolvedSource??h.source,{label:"Classic migration handoff context",hooks:e.handoffReadHooks}),await Fs(t,f.contextRef,v),u.push(ft.resolve(t,f.contextRef))),await Ms(t,f.artifactsRef,g),u.push(ft.resolve(t,f.artifactsRef));let y=(e.now?.()??new Date).toISOString(),S={runId:f.runId,stateVersion:1,trajectoryOffset:2,contextHash:v===null?null:ep(v),artifactsHash:XC(g),createdAt:y};await Ds(t,f.checkpointRef,S),u.push(ft.resolve(t,f.checkpointRef)),u.push(ft.resolve(t,f.trajectoryRef));for(let b of eS(f,i,y))await Bt(t,f.trajectoryRef,b);return await hn(t,{classic:p,run:f,unknownKeys:n.unknownKeys}),{classic:p,run:f,evidence:s,migrated:!0,snapshotDir:d.snapshotDir}}catch(d){throw await tS(u),l||await Lc.rm(c,{recursive:!0,force:!0}),d}}async function rS(t){try{return(await np.stat(t)).isDirectory()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Ks(t){try{return(await np.stat(t)).isFile()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function iS(t){return await rS(t)?await Ks(Ne.join(t,"skill.yaml"))?!0:await Ks(Ne.join(t,"SKILL.md"))&&await Ks(Ne.join(t,"comet","skill.yaml")):!1}function sS(t){return{root:t,packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-classic",version:"1",description:"Internal compatibility orchestration for classic Comet full, hotfix, and tweak workflows"},goal:{statement:"Advance or restore a classic Comet Run without changing the user command surface",inputs:[{name:"classic-state",description:"Validated ClassicState consistent with the Run projection",required:!0},{name:"evidence",description:"Structured evidence produced by the Classic Evidence collector",required:!0}],outputs:[{name:"run-state",description:"Atomically synchronized Classic and Run state",required:!0}],success:["Legacy fields and Run fields remain consistent","Every step invokes only a declared public Comet Skill","The completed state passes its completion eval"]},orchestration:{mode:"deterministic",entry:"full.open",steps:[{id:"full.open",action:{type:"invoke_skill",ref:"comet-open"},next:"full.design.handoff"},{id:"full.design.handoff",action:{type:"invoke_skill",ref:"comet-design"},next:"full.design.document"},{id:"full.design.document",action:{type:"invoke_skill",ref:"comet-design"},next:"full.build.configure"},{id:"full.build.plan",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.plan-ready"},{id:"full.build.plan-ready",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.build.configure",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.plan"},{id:"full.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.complete"},{id:"full.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"full.verify.run"},{id:"full.build.fix",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.verify.branch"},{id:"full.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.archive.confirm"},{id:"full.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"full.archive.execute"},{id:"full.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"hotfix.open",action:{type:"invoke_skill",ref:"comet-hotfix"},next:"hotfix.build.execute"},{id:"hotfix.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.build.complete"},{id:"hotfix.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.verify.run"},{id:"hotfix.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.verify.branch"},{id:"hotfix.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.archive.confirm"},{id:"hotfix.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"hotfix.archive.execute"},{id:"hotfix.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"tweak.open",action:{type:"invoke_skill",ref:"comet-tweak"},next:"tweak.build.execute"},{id:"tweak.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.build.complete"},{id:"tweak.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.verify.run"},{id:"tweak.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.verify.branch"},{id:"tweak.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.archive.confirm"},{id:"tweak.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"tweak.archive.execute"},{id:"tweak.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"completed",action:{type:"checkpoint"},completionEvals:["classic-completed"]}]},skills:[{id:"comet-open"},{id:"comet-design"},{id:"comet-build"},{id:"comet-verify"},{id:"comet-archive"},{id:"comet-hotfix"},{id:"comet-tweak"}],agents:[],tools:[]},guardrails:{allowedSkills:["comet-open","comet-design","comet-build","comet-verify","comet-archive","comet-hotfix","comet-tweak"],allowedAgents:[],allowedTools:[],maxIterations:500,maxRetriesPerAction:3,confirmationRequiredFor:[]},evals:[{id:"classic-completed",scope:"completion",type:"state_equals",field:"status",equals:"completed"}]}}async function oS(){let t=Ne.dirname(rp(import.meta.url)),e=[process.env.COMET_RUNTIME_CLASSIC_ROOT,Ne.resolve(t,"..","runtime","classic"),Ne.resolve(t,"..","..","comet","runtime","classic"),Ne.resolve(t,"..","..","assets","skills","comet","runtime","classic"),Ne.resolve("assets","skills","comet","runtime","classic"),process.env.COMET_CLASSIC_SKILL_ROOT,Ne.resolve(t,"..","..","comet-classic"),Ne.resolve(t,"..","..","assets","skills","comet-classic"),Ne.resolve("assets","skills","comet-classic")].filter(n=>!!n);for(let n of e)if(await iS(n))return n;return null}async function aS(t){return await Ks(Ne.join(t,"skill.yaml"))?Um(t):Bm(t)}async function Kn(t){let e=await oS();return tp(t,{skillPackage:e?await aS(e):sS(Ne.dirname(rp(import.meta.url)))})}async function ip(t){let e=await V(t),n=Array.from(new Set(e.unknownKeys)).sort();if(n.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${n.join(", ")}`);return Kn(t)}async function Hs(t,e,n,r){return me(t,()=>cS(t,e,n,r))}async function cS(t,e,n,r){let i=await V(t);if(!i.classic||!i.run)throw new Error("Classic transition requires synchronized Classic and Run projections");if(i.run.runId!==n.runId||i.run.iteration!==n.iteration||(e.checkEpoch??0)<(i.classic.checkEpoch??0))throw new Error("Classic transition became stale; reload the current state");let s=await Ft(t,{classic:e,run:n,unknownKeys:i.unknownKeys}),o=Fn(e,s),a={...n,currentStep:o,iteration:n.iteration+1,status:o==="completed"?"completed":"running"};await hn(t,{classic:e,run:a,unknownKeys:i.unknownKeys});let c=await gn(t,a.trajectoryRef);return await Bt(t,a.trajectoryRef,{sequence:c.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:a.runId,data:{kind:"classic",fromStep:n.currentStep,toStep:o,...r}}),a}function Vr(t){return t==="zh-CN"?"zh-CN":"en"}function Yr(t,e,n){return t==="zh-CN"?n:e}var qc={open:{en:"open (clarifying the request)",zh:"open(需求澄清)"},design:{en:"design",zh:"design(方案设计)"},build:{en:"build",zh:"build(实现)"},verify:{en:"verify",zh:"verify(验证)"},archive:{en:"archive",zh:"archive(归档)"}};function zs(t,e){return qc[t]?Yr(e,qc[t].en,qc[t].zh):t}function sp(t){let{name:e,phase:n,failed:r,total:i,locale:s}=t;return r===0?{summary:Yr(s,`Change ${e} passed every check for leaving the ${zs(n,s)} stage (${i} total) and is ready to proceed.`,`需求 ${e} 通过了离开 ${zs(n,s)}阶段的全部 ${i} 项检查,可以继续推进。`)}:{summary:Yr(s,`Change ${e} is not ready to leave the ${zs(n,s)} stage yet: ${r} of ${i} checks failed. The failing items below are the Agent's checklist, not user actions.`,`需求 ${e} 暂时还不能离开 ${zs(n,s)}阶段:${r}/${i} 项检查未通过。下方的失败项是给 Agent 的检查清单,不需要用户处理。`),user_message:Yr(s,"A few preparation items are still missing before this change can move to the next stage; the Agent is filling them in and will continue afterwards.","这条需求要进入下一阶段还差几项准备工作;Agent 正在补齐,之后会自动继续。")}}function Mc(t){let{name:e,locale:n}=t;return{summary:Yr(n,`Handoff context for ${e} was written and recorded; the Build phase can resume from it.`,`需求 ${e} 的交接上下文已写入并记录,Build 阶段可据此继续。`)}}var lS="\x1B[32m",uS="\x1B[31m",dS="\x1B[33m",Wc="\x1B[0m";function Ht(t){return`${lS}${t}${Wc}`}function je(t){return`${uS}${t}${Wc}`}function op(t){return`${dS}${t}${Wc}`}var pe=class extends Error{constructor(n,r=1){super(n);this.exitCode=r}exitCode},Fc=class{stdout=[];stderr=[];envelope;toResult(e=0){return{exitCode:e,...this.stdout.length>0?{stdout:this.stdout.join(`
|
|
145
|
+
`).trim(),n=/^@ECHO off\nGOTO start\n:find_dp0\nSET dp0=%~dp0\nEXIT \/b\n:start\nSETLOCAL\nCALL :find_dp0\n\nIF EXIST "%dp0%\\node\.exe" \(\n {2}SET "_prog=%dp0%\\node\.exe"\n\) ELSE \(\n {2}SET "_prog=node"\n {2}SET PATHEXT=%PATHEXT:;\.JS;=;%\n\)\n\nendLocal & goto #_undefined_# 2>NUL \|\| title %COMSPEC% & "%_prog%" {2}"%dp0%\\([^"%\r\n]+\.(?:mjs|cjs|js))" %\*$/u.exec(e);if(n)return{target:n[1]};let r=/^@SETLOCAL\n(?:@IF NOT DEFINED NODE_PATH \(\n {2}@SET "NODE_PATH=([^"\r\n]+)"\n\) ELSE \(\n {2}@SET "NODE_PATH=\1;%NODE_PATH%"\n\)\n)?@IF EXIST "%~dp0\\node\.exe" \(\n {2}"%~dp0\\node\.exe" {2}"%~dp0\\([^"%\r\n]+\.(?:mjs|cjs|js))" %\*\n\) ELSE \(\n {2}@SET PATHEXT=%PATHEXT:;\.JS;=;%\n {2}node {2}"%~dp0\\\2" %\*\n\)$/u.exec(e);return r?{target:r[2],...r[1]?{nodePath:r[1]}:{}}:null}function Df(t,e,n){if((n.platform??process.platform)!=="win32")return{command:t,args:[...e]};let r=ln(t,n.env??process.env,n.cwd),i=Mn.extname(r).toLowerCase();if([".mjs",".cjs",".js"].includes(i))return{command:process.execPath,args:[Mn.resolve(n.cwd,r),...e]};if(i===".cmd"){let s=cb(ab(r,"utf8"));if(s){let o=Mn.resolve(Mn.dirname(r),s.target);if(!Ff(o))throw new Error(`Node CLI entry is missing: ${o}`);let a=Mn.join(Mn.dirname(r),"node.exe"),c={...n.env??process.env},l=Object.keys(c).find(d=>d.toUpperCase()==="NODE_PATH"),u=l?c[l]:void 0;return s.nodePath&&(l&&delete c[l],c.NODE_PATH=s.nodePath+(u?`;${u}`:"")),{command:Ff(a)?a:process.execPath,args:[o,...e],...s.nodePath?{env:c}:{}}}}if([".cmd",".bat",".ps1"].includes(i))throw new Error(`Unsupported Node CLI shim: ${r}. Use a standard npm/pnpm .cmd launcher or the Node CLI .js/.mjs/.cjs entry; no shell fallback is allowed.`);return{command:r,args:[...e]}}function fc(t,e){let n=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)?u:{},r=n(t),i=n(r.entry),s=n(r.state??i.state??r),o=n(r.preparation??r.workspace??i.workspace),a=n(r.continuation??i.continuation),c=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:e??null,l=s.stateVersion??s.state_version;return{phase:typeof s.phase=="string"?s.phase:null,status:typeof s.status=="string"?s.status:null,stateVersion:typeof l=="number"?l:null,workspace:{cwd:c},continuation:Object.keys(a).length?{...a,cwd:c}:null}}var Wf=Pe(xe(),1);le();import lb from"path";async function Bf(t,e){let n=e??await ue(t),r=lb.join(n.openSpecRoot,"config.yaml"),i=K(n.projectRoot,r),s;try{s=(await Y(n.projectRoot,i,Number.MAX_SAFE_INTEGER,{label:"Classic OpenSpec project config",bigint:!0})).bytes.toString("utf8")}catch(l){throw l.code==="ENOENT"?new Error(`Classic OpenSpec root is unhealthy: ${i} is missing; rerun OpenSpec initialization for the configured Classic layout`,{cause:l}):new Error(`Classic OpenSpec root is unhealthy: ${l instanceof Error?l.message:String(l)}`,{cause:l})}let o=(0,Wf.parseDocument)(s,{uniqueKeys:!0});if(o.errors.length>0)throw new Error(`Classic OpenSpec root is unhealthy: ${i} is invalid YAML (${o.errors[0].message})`);let a=o.toJS();if(!a||typeof a!="object"||Array.isArray(a))throw new Error(`Classic OpenSpec root is unhealthy: ${i} must contain a mapping`);let c=a.schema;if(typeof c!="string"||c.trim()==="")throw new Error(`Classic OpenSpec root is unhealthy: ${i} must declare a non-empty schema`);return{layout:n,configPath:i,schema:c}}function db(t){return t[0]==="--"?t.slice(1):[...t]}async function Uf(t,e=process.cwd()){let n=db(t);if(n.length===0)return{exitCode:64,stderr:"Usage: comet classic openspec -- <openspec-args...>"};let r=await dt(e),i=await on(r);await Bf(r,i);let s=process.env.COMET_OPENSPEC||"openspec",o=Df(s,n,{cwd:i.openSpecBase}),a=ub(o.command,o.args,{cwd:i.openSpecBase,encoding:"utf8",shell:!1,windowsHide:!0,timeout:12e4,...o.env?{env:o.env}:{}});if(a.error){let c=a.error.code;return{exitCode:c==="ENOENT"?127:70,stdout:a.stdout||void 0,stderr:a.stderr||(c==="ENOENT"?`OpenSpec CLI not found: ${s}`:a.error.message)}}return{exitCode:a.status??1,stdout:a.stdout||void 0,stderr:a.stderr||void 0}}import{promises as mc}from"fs";import Wr from"path";async function ft(t,e){let n=[],r=new Set;async function i(s,o){let a=await me(t,s,{label:"Classic capability directory",expected:"directory"});if(!a.exists)return;let c=await mc.realpath(a.target);if(r.has(c))throw new Error(`Classic capability directory cycle: ${s}`);if(r.add(c),o){let u=`${s}/spec.md`;(await me(t,u,{label:"Classic capability spec",expected:"file"})).exists&&n.push(u)}let l=(await mc.readdir(a.target,{withFileTypes:!0})).sort((u,d)=>u.name.localeCompare(d.name));for(let u of l)if(u.isDirectory()||u.isSymbolicLink()){if(u.name==="spec.md")continue;await i(`${s}/${u.name}`,!0)}r.delete(c)}return await i(e.replaceAll("\\","/"),!1),n}function dn(t){return t?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)?t.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${t}'
|
|
146
|
+
Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function Es(t){let e=dn(t);if(e)throw new Error(e)}function fb(t,e){return{label:K(t,e),directory:e}}async function Ss(t,e,n){let r=fb(t,e);if(!(await me(t,e,{label:n,expected:"directory"})).exists)return{change:r,exists:!1,stateExists:!1};let s=await me(t,Wr.join(e,".comet.yaml"),{label:`${n} state`,expected:"file"});return{change:r,exists:!0,stateExists:s.exists}}function mb(t,e){let n=e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${n}$`,"u").test(t)}async function pb(t,e,n,r={}){if(!r.skipExactCompatibility){let o=await Ss(t,Wr.join(e,n),`Classic archived change ${n}`);if(o.exists)return o.change}if(!(await me(t,e,{label:"Classic archive directory",expected:"directory"})).exists)return null;let s=[];for(let o of await mc.readdir(e,{withFileTypes:!0})){if(!mb(o.name,n))continue;let a=await Ss(t,Wr.join(e,o.name),`Classic archived change ${o.name}`);a.exists&&a.stateExists&&s.push(a.change)}return s.sort((o,a)=>a.directory.localeCompare(o.directory))[0]??null}async function Kf(t,e=process.cwd()){Es(t);let n=await ue(e),r=await Ss(n.projectRoot,Wr.join(n.changesDir,t),`Classic active change ${t}`);return{...r.change,exists:r.exists,stateExists:r.stateExists}}async function xs(t,e=process.cwd()){Es(t);let n=await ue(e),r=await Ss(n.projectRoot,Wr.join(n.changesDir,t),`Classic active change ${t}`);if(r.exists)return r.change;let i=await pb(n.projectRoot,n.archiveDir,t);return i||r.change}var gb=".comet/archive-requirements.json";async function zf(t,e){let n=je.join(e,gb),r=["proposal.md","design.md","tasks.md"];if(await G(t,n,{label:"Classic archive requirements",expected:"file"})){let s=JSON.parse(await I(t,n,{label:"Classic archive requirements"}));if(s?.schema!=="comet.classic.archive-requirements.v1")throw new Error("Unsupported Classic archive requirements");r=s.files}if(!Array.isArray(r)||!r.includes("proposal.md")||!r.includes("tasks.md")||r.some(s=>typeof s!="string"||!(["proposal.md","design.md","tasks.md"].includes(s)||/^specs\/(?:[^/\\:]+\/)+spec\.md$/u.test(s))||s.split("/").some(o=>o==="."||o==="..")))throw new Error("Invalid Classic archive required files");let i=[];for(let s of r)await Oe(t,je.join(e,s),"Classic archived required file")||i.push(`Required archived artifact is missing or empty: ${s}`);return i}function wb(t){if(!t||typeof t!="object")throw new Error("Unsupported OpenSpec status: expected an object");let e=t;if(!Array.isArray(e.artifacts)||!Array.isArray(e.applyRequires))throw new Error("OpenSpec must expose artifacts and applyRequires; upgrade to a supported version");let n=new Map;for(let a of e.artifacts){if(!a||typeof a!="object"||typeof a.id!="string"||typeof a.outputPath!="string"||!["done","skipped","ready","blocked"].includes(a.status)||!Array.isArray(a.requires)||a.requires.some(c=>typeof c!="string"))throw new Error("OpenSpec must expose dependency edges for every artifact; upgrade to a supported version");if(n.has(a.id))throw new Error(`Duplicate OpenSpec artifact: ${a.id}`);n.set(a.id,a)}let r=[],i=new Set,s=new Set,o=a=>{if(typeof a!="string"||!n.has(a))throw new Error(`Missing OpenSpec dependency: ${String(a)}`);if(s.has(a))throw new Error(`Cyclic OpenSpec dependency: ${a}`);if(i.has(a))return;s.add(a);let c=n.get(a);for(let l of c.requires)o(l);s.delete(a),i.add(a),r.push(c)};for(let a of[...e.applyRequires,"proposal","tasks"])o(a);return r}async function Br(t,e){let n=je.join(e,".openspec.yaml");if(!await G(t,n,{label:"OpenSpec change metadata",expected:"file"}))return{source:"legacy",required:["proposal","design","tasks"],skipped:[],designRequired:!0,files:["proposal.md","design.md","tasks.md"].map(g=>je.join(e,g)),problems:[]};let r=(0,Hf.parseDocument)(await I(t,n,{label:"OpenSpec change metadata"}));if(r.errors.length)throw new Error(`Invalid OpenSpec metadata: ${r.errors[0].message}`);let i=await ue(t),s=await ft(t,je.join(e,"specs")),o=hb("sha256");for(let g of[je.join(i.openSpecRoot,"config.yaml"),n,...["proposal.md","design.md","tasks.md"].map(m=>je.join(e,m)),...s])o.update(g),await G(t,g,{label:"OpenSpec observation input",expected:"file"})?o.update(await I(t,g,{label:"OpenSpec observation input"})):o.update("<missing>");let a=()=>Uf(["status","--change",je.basename(e),"--json"],t),l=await G(t,je.join(i.openSpecRoot,"schemas"),{label:"OpenSpec local schemas",expected:"directory"})?await a():await Mf(`openspec-status:${e}:${o.digest("hex")}`,a);if(l.exitCode!==0)throw new Error(`Cannot inspect OpenSpec artifact requirements: ${l.stderr??l.exitCode}`);let u;try{u=JSON.parse(l.stdout??"")}catch{throw new Error("Unsupported OpenSpec status: expected JSON")}if(!u||typeof u.changeRoot!="string"||je.resolve(u.changeRoot)!==je.resolve(e))throw new Error("OpenSpec status resolves outside the selected Classic change");let d=wb(u),f=s,p={source:"openspec",required:d.map(g=>g.id),skipped:[],designRequired:d.some(g=>g.id==="design"),files:[],problems:[]};for(let g of d){if(!["proposal","specs","design","tasks"].includes(g.id))throw new Error(`Unsupported Classic artifact: ${g.id}; use a schema with supported artifact roles`);if(g.id!=="specs"&&g.outputPath!==`${g.id}.md`)throw new Error(`Unsupported Classic artifact output: ${g.outputPath}`);if(g.status==="skipped"){if(g.id!=="specs"||r.get("skip_specs")!==!0||f.length)throw new Error("OpenSpec skipped specs require explicit skip_specs: true and no conflicting spec files");p.skipped.push(g.id);continue}let m=g.outputPath.replaceAll("\\","/");if(je.posix.isAbsolute(m)||/^[A-Za-z]:/u.test(m)||m.split("/").includes(".."))throw new Error(`Unsafe OpenSpec artifact path: ${m}`);let h;if(g.id==="specs"&&["specs/**/*.md","specs/**/spec.md","specs/*/spec.md"].includes(m))h=f;else{if(["?","*","[","]","{","}"].some(v=>m.includes(v)))throw new Error(`Unsupported OpenSpec artifact pattern: ${m}`);h=[je.join(e,m)]}(g.status!=="done"||!h.length)&&p.problems.push(`Required OpenSpec artifact is not complete: ${g.id}`);for(let v of h)await Oe(t,v,`OpenSpec required artifact ${g.id}`)||p.problems.push(`Required OpenSpec file is missing or empty: ${v}`),p.files.push(v)}return p}var lp=Pe(xe(),1);import Dc from"path";import{promises as np}from"fs";import Ie from"path";import{fileURLToPath as rp}from"url";import Mt from"path";le();Ve();import Ur from"path";function yb(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function Jf(t,e,n,r){let i=fe(n,"Classic handoff artifact pointer");if((await J(t,i,{label:"Classic handoff artifact",expected:"file"})).exists)return null;let o=await ue(t),a=`${K(t,o.changesDir)}/`,l=(o.artifactLayout==="docs"?[a,"openspec/changes/"]:[a]).find(y=>i.startsWith(y));if(!l)return null;let u=i.slice(l.length).split("/");if(u.length<4||u[1]!==".comet"||u.slice(2).some(y=>y.length===0))return null;let d=u[0];Es(d);let f=u.slice(2),p=Ur.resolve(e);if(Ur.dirname(p)!==Ur.resolve(o.archiveDir))return null;let g=Ur.basename(p),m=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(g);if(g!==d&&m?.[1]!==d)return null;await J(t,K(t,p),{label:"Classic archived change directory",expected:"directory"});let h=Ur.join(p,".comet",...f),v=K(t,h);try{return await Y(t,v,r,{label:"Historical Classic archived handoff artifact"}),v}catch(y){if(yb(y))return null;throw y}}le();function pc(t,e){return Mt.relative(t,e).split(Mt.sep).join("/")}async function Kr(t,e,n,r,i){if(!n)return{code:e,satisfied:!1};let s=n.replaceAll("\\","/");if(i)return{code:e,satisfied:!1,source:s,detail:`Classic layout is unsafe or unavailable: ${i instanceof Error?i.message:String(i)}`};try{if(r){let a=r.artifactLayout==="legacy"?"docs":"legacy",c=K(t,gs(t,a).openSpecRoot);if((s===c||s.startsWith(`${c}/`))&&(await J(t,s,{label:`${e} artifact`,expected:"file"})).exists)return{code:e,satisfied:!1,source:s,detail:"standalone OpenSpec root is not a Comet artifact root"}}let o=await Qa(t,s,{label:`${e} artifact`});return{code:e,satisfied:o,source:s,...o?{resolvedSource:s}:{}}}catch(o){return{code:e,satisfied:!1,source:s,detail:`unsafe artifact pointer outside the project or through a special path: ${o instanceof Error?o.message:String(o)}`}}}async function vb(t,e,n,r){try{r??=await ue(t)}catch(s){return{code:"design.handoff",satisfied:!1,...n?{source:n.replaceAll("\\","/")}:{},detail:`Classic layout is unsafe or unavailable for handoff evidence: ${s instanceof Error?s.message:String(s)}`}}let i=await Kr(t,"design.handoff",n,r);if(!n||i.satisfied||i.detail)return i;try{let s=await Jf(t,e,n,Number.MAX_SAFE_INTEGER);return s?{...i,satisfied:!0,resolvedSource:s,detail:`resolved historical legacy pointer from archived change: ${s}`}:i}catch(s){return{...i,satisfied:!1,detail:`unsafe archived handoff fallback: ${s instanceof Error?s.message:String(s)}`}}}async function _s(t,e,n){return Kr(t,e,pc(t,n))}async function kb(t,e){let n=Mt.join(e,"specs"),r;try{r=await ft(t,n)}catch(i){return i.code==="ENOENT"?{code:"openspec.delta-spec",satisfied:!1}:{code:"openspec.delta-spec",satisfied:!1,detail:`unsafe delta-spec path: ${i instanceof Error?i.message:String(i)}`}}return{code:"openspec.delta-spec",satisfied:r.length>0,source:r[0]?pc(t,r[0]):void 0,detail:`${r.length} delta spec${r.length===1?"":"s"}`}}async function bb(t,e){let n,r=pc(t,e);try{n=(await Y(t,r,Number.MAX_SAFE_INTEGER,{label:"Classic tasks artifact"})).bytes.toString("utf8")}catch(o){return o.code==="ENOENT"?{code:"build.tasks-complete",satisfied:!1}:{code:"build.tasks-complete",satisfied:!1,source:r,detail:`unsafe tasks artifact: ${o instanceof Error?o.message:String(o)}`}}let i;try{i=Ne(n)}catch(o){return{code:"build.tasks-complete",satisfied:!1,source:r,detail:`malformed tasks.md: ${o instanceof Error?o.message:String(o)}`}}let s=i.filter(o=>o.completed).length;return{code:"build.tasks-complete",satisfied:i.length>0&&s===i.length,source:r,detail:`${s} of ${i.length} tasks complete`}}function Ft(t,e){return t.some(n=>n.code===e&&n.satisfied)}async function Dt(t,e){let n=await dt(t),r=e.classic,i=Mt.join(t,"proposal.md"),s=Mt.join(t,"design.md"),o=Mt.join(t,"tasks.md"),a=e.run?Mt.resolve(t,e.run.checkpointRef):Mt.join(t,".comet","checkpoint.json"),c,l;try{c=await ue(n)}catch(f){l=f}let u=await Promise.all([_s(n,"openspec.proposal",i),_s(n,"openspec.design",s),_s(n,"openspec.tasks",o),kb(n,t),Kr(n,"design.document",r?.designDoc??null,c,l),(async()=>{let f=await Kr(n,"build.plan",r?.plan??null,c,l);if(!f.satisfied)return f;try{let p=await Ir(n,r?.plan??null,{requireNonempty:r?.buildMode==="autonomous"});return p.status==="ready"?f:{code:f.code,source:f.source,satisfied:!1,detail:`Implementation plan is ${p.status}`}}catch(p){return{code:f.code,source:f.source,satisfied:!1,detail:p instanceof Error?p.message:String(p)}}})(),bb(n,o),Kr(n,"verification.report",r?.verificationReport??null,c,l),vb(n,t,r?.handoffContext??null,c),_s(n,"run.checkpoint",a)]),d=u.find(f=>f.code==="design.handoff");return d&&!r?.handoffHash&&(d.satisfied=!1,d.detail="handoff hash is missing"),u.push({code:"archive.confirmed",satisfied:r?.archiveConfirmation==="confirmed"}),u}import{createHash as YC,randomUUID as VC}from"crypto";import{promises as Lc}from"fs";import pt from"path";function Cb(t){return t.classicProfile??t.workflow}function Sb(t){return t.isolation!==null&&mf(t)}function Eb(t){return(t.buildMode==="direct"||t.buildMode==="autonomous")&&t.tddMode==="direct"&&t.isolation!==null&&t.verifyMode==="light"}function xb(t,e,n){if(t!=="full"&&e.verifyResult==="fail")return`${t}.build.execute`;if(t==="full"){if(Ft(n,"build.plan")&&e.buildPause==="plan-ready")return"full.build.plan-ready";if(!Sb(e))return"full.build.configure";if(!Ft(n,"build.plan"))return"full.build.plan";if(e.verifyResult==="fail")return"full.build.fix"}else if(!Eb(e))throw new Error(`${t} build configuration is incomplete`);return Ft(n,"build.tasks-complete")?`${t}.build.complete`:`${t}.build.execute`}function _b(t,e,n){return e.verifyResult!=="pass"||!Ft(n,"verification.report")?`${t}.verify.run`:`${t}.verify.branch`}function Rb(t,e){if(e.verifyResult!=="pass")throw new Error("archive requires verify_result=pass");return e.archiveConfirmation==="confirmed"?`${t}.archive.execute`:`${t}.archive.confirm`}function Fn(t,e){let n=Cb(t);if(t.archived&&t.phase!=="archive")throw new Error("archived=true requires phase=archive");if(t.archived)return"completed";if(n!=="full"&&t.phase==="design")throw new Error(`${n} workflow cannot enter design`);switch(t.phase){case"open":return`${n}.open`;case"design":return Ft(e,"design.handoff")?"full.design.document":"full.design.handoff";case"build":return xb(n,t,e);case"verify":return _b(n,t,e);case"archive":return Rb(n,t)}}rm();le();var Ls=Pe(xe(),1);ot();le();import Bt from"path";import{AsyncLocalStorage as kC}from"node:async_hooks";$s();var bm=["full","hotfix","tweak"],mn=1,rC=["open","design","build","verify","archive"],iC=["en","zh-CN"],sC=["off","beta"],oC=["subagent-driven-development","executing-plans","direct","autonomous"],aC=["plan-ready"],cC=["confirmed"],lC=["tdd","direct"],uC=["off","standard","thorough"],dC=["current","branch","worktree"],fC=["light","full"],mC=["pending","pass","fail"],pC=["pending","handled"],hC=["pending","confirmed"],Ze=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","check_epoch","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],pn=["run_id"],gC=new Set([...Ze,...pn]),Sm=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function xc(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Bn(t,e){let n=t[e];if(n==null||n==="")return null;if(typeof n!="string")throw new Error(`Invalid Classic state: ${e} must be a string or null`);return n}function ve(t,e,n,r=!0){let i=t[e];if(i==null||i===""){if(r)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof i!="string"||!n.includes(i))throw new Error(`Invalid Classic state: ${e} must be one of ${n.join(", ")}${r?" or null":""}`);return i}function _c(t,e,n=!0){let r=t[e];if(r==null||r===""){if(n)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof r!="boolean")throw new Error(`Invalid Classic state: ${e} must be true or false`);return r}function Cm(t,e,n=0){let r=t[e];if(r==null||r==="")return n;if(typeof r!="number"||!Number.isSafeInteger(r)||r<0)throw new Error(`Invalid Classic state: ${e} must be a non-negative integer`);return r}function Ts(t,e){let n=Bn(t,e);if(n===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${e} must be a relative repository path`);return n}function wC(t,e){let n=Bn(t,e);if(n!==null&&!/^[a-f0-9]{64}$/u.test(n))throw new Error(`Invalid Classic state: ${e} must be a sha256 hex digest`);return n}function yC(t){let e=t.classic_migration;if(e==null||e==="")return null;if(e!==mn)throw new Error(`Invalid Classic state: classic_migration must be ${mn}`);return e}function vC(t){if(!Ze.some(n=>xc(t,n)))return null;for(let n of Sm)if(!xc(t,n))return null;return{workflow:ve(t,"workflow",bm,!1),language:ve(t,"language",iC),phase:ve(t,"phase",rC,!1),contextCompression:ve(t,"context_compression",sC),buildMode:ve(t,"build_mode",oC),buildPause:ve(t,"build_pause",aC),subagentDispatch:ve(t,"subagent_dispatch",cC),tddMode:ve(t,"tdd_mode",lC),reviewMode:ve(t,"review_mode",uC),isolation:ve(t,"isolation",dC),boundBranch:Bn(t,"bound_branch"),verifyMode:ve(t,"verify_mode",fC),autoTransition:_c(t,"auto_transition"),baseRef:Bn(t,"base_ref"),designDoc:Ts(t,"design_doc"),plan:Ts(t,"plan"),verifyResult:ve(t,"verify_result",mC,!1),verifyFailures:Cm(t,"verify_failures"),...xc(t,"check_epoch")?{checkEpoch:Cm(t,"check_epoch")}:{},verificationReport:Ts(t,"verification_report"),branchStatus:ve(t,"branch_status",pC),createdAt:Bn(t,"created_at"),verifiedAt:Bn(t,"verified_at"),archiveConfirmation:ve(t,"archive_confirmation",hC),archived:_c(t,"archived",!1),directOverride:_c(t,"direct_override"),handoffContext:Ts(t,"handoff_context"),handoffHash:wC(t,"handoff_hash"),classicProfile:ve(t,"classic_profile",bm),classicMigration:yC(t)}}function Rc(t,e){let n=e??null;if(n===null&&e===void 0&&t.run_id&&t.skill)try{n=Dn(t)}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(i.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:r})}return{classic:vC(t),run:n,unknownKeys:Object.keys(t).filter(r=>!gC.has(r))}}function Em(t){return{workflow:t.workflow,language:t.language,phase:t.phase,context_compression:t.contextCompression,build_mode:t.buildMode,build_pause:t.buildPause,subagent_dispatch:t.subagentDispatch,tdd_mode:t.tddMode,review_mode:t.reviewMode,isolation:t.isolation,bound_branch:t.boundBranch,verify_mode:t.verifyMode,auto_transition:t.autoTransition,base_ref:t.baseRef,design_doc:t.designDoc,plan:t.plan,verify_result:t.verifyResult,verify_failures:t.verifyFailures,...t.checkEpoch===void 0?{}:{check_epoch:t.checkEpoch},verification_report:t.verificationReport,branch_status:t.branchStatus,created_at:t.createdAt,verified_at:t.verifiedAt,archive_confirmation:t.archiveConfirmation,archived:t.archived,direct_override:t.directOverride,handoff_context:t.handoffContext,handoff_hash:t.handoffHash,classic_profile:t.classicProfile,classic_migration:t.classicMigration}}$s();var xm=new kC,Pc=".comet-state-transaction.json";async function pe(t,e){let n=Bt.resolve(t);return xm.getStore()===n?e():(await J(n,".comet-state.lock",{label:"Classic state lock",expected:"file"}),tm(Bt.join(n,".comet-state.lock"),()=>xm.run(n,async()=>(await Rm(n),e()))))}async function Ac(t,e){try{return(await Y(t,e,Number.MAX_SAFE_INTEGER,{label:"Classic state transaction"})).bytes.toString("utf8")}catch(n){if(n.code==="ENOENT")return null;throw n}}function bC(t){if(t===null)return null;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Invalid Classic transaction Run");let e=t,n=Dn({run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:e.retries});if(!n)throw new Error("Invalid Classic transaction Run identity");return n}async function Rm(t){let e=await Ac(t,Pc);if(e===null)return;let n=JSON.parse(e);if(!n||n.schema!=="comet.classic.state-transaction.v1"||n.beforeYaml!==null&&typeof n.beforeYaml!="string"||typeof n.afterYaml!="string")throw new Error("Invalid Classic state transaction");let r=await Ac(t,".comet.yaml");if(r!==n.beforeYaml&&r!==n.afterYaml)throw new Error("Classic state transaction conflicts with current YAML; preserve files for recovery");let i=bC(r===n.afterYaml?n.afterRun:n.beforeRun);i?await Wn(t,i):await Jr(t),await Cn(Bt.join(t,Pc),{containedRoot:t})}function Gr(t){let e=t.toJS();if(e===null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic state document: root must be a mapping");return e}function _m(t,e,n){t.get(e)!==n&&t.set(e,n)}function CC(t,e){if(e.classic)for(let[n,r]of Object.entries(Em(e.classic)))n==="auto_transition"&&r===null&&!t.has(n)||_m(t,n,r);else for(let n of Ze)t.delete(n);Ec(t.toJS(),e.run),e.run?_m(t,"run_id",e.run.runId):t.delete("run_id")}function SC(t){let e=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let n of e)t.delete(n)}function EC(t){let e=!1;for(let n of["build_command","verify_command"])t.has(n)&&(t.delete(n),e=!0);return e}async function Pm(t){let e;try{e=(await Y(Bt.dirname(t),Bt.basename(t),Number.MAX_SAFE_INTEGER,{label:"Classic state document"})).bytes.toString("utf8")}catch(r){if(r.code!=="ENOENT")throw r;return new Ls.Document({})}let n=(0,Ls.parseDocument)(e);if(n.errors.length>0)throw new Error(`Invalid Classic state document: ${n.errors[0].message}`);return Gr(n),n}async function V(t,e={}){return pe(t,()=>xC(t,e))}async function xC(t,e){let n=e.migrate!==!1,r=Bt.join(t,".comet.yaml"),i=await Pm(r),s=Gr(i),o=EC(i);o&&(s=Gr(i));let a=await Is(t);if(!a&&s.run_id&&s.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>($s(),km));a=c(s),a&&n&&(await Wn(t,a),SC(i),o=!0)}return o&&n&&await ye(r,i.toString(),{containedRoot:t}),Rc(Gr(i),a)}async function hn(t,e,n={}){return pe(t,()=>_C(t,e,n))}async function _C(t,e,n){let r=Bt.join(t,".comet.yaml"),i=await Pm(r),s=i.get("check_epoch")??0;if(typeof s=="number"&&s>(e.classic?.checkEpoch??0))throw new Error("Classic state changed during this operation; reload before retrying");CC(i,{...e,unknownKeys:e.unknownKeys??[]}),Rc(Gr(i),e.run??null);let o=await Ac(t,".comet.yaml"),a=i.toString();if(o===a){await n.beforeCommit?.(),e.run?await Wn(t,e.run):await Jr(t);return}let c=Bt.join(t,Pc);await ye(c,JSON.stringify({schema:"comet.classic.state-transaction.v1",beforeYaml:o,afterYaml:a,beforeRun:await Is(t),afterRun:e.run}),{containedRoot:t});try{e.run?await Wn(t,e.run):await Jr(t),await ye(r,a,{containedRoot:t,beforeCommit:n.beforeCommit})}catch(l){throw await Rm(t).catch(()=>{}),l}await Cn(c,{containedRoot:t}).catch(()=>{})}function Am(t,e,n){return{runId:e,skill:t.definition.metadata.name,skillVersion:t.definition.metadata.version,skillHash:n,orchestration:t.definition.orchestration.mode,currentStep:t.definition.orchestration.entry??null,iteration:0,pending:null,pendingRef:".comet/pending-action.json",trajectoryRef:".comet/trajectory.jsonl",contextRef:".comet/context.md",artifactsRef:".comet/artifacts.json",checkpointRef:".comet/checkpoint.json",status:"running",retries:{}}}Ns();import qs from"path";var et={trajectory:Number.MAX_SAFE_INTEGER,artifacts:Number.MAX_SAFE_INTEGER,context:Number.MAX_SAFE_INTEGER,pendingAction:Number.MAX_SAFE_INTEGER,checkpoint:Number.MAX_SAFE_INTEGER};function He(t,e){if(qs.isAbsolute(e))throw new Error("Run path must stay inside the change directory");let n=qs.resolve(t),r=qs.resolve(n,e);if(r!==n&&!r.startsWith(n+qs.sep))throw new Error("Run path must stay inside the change directory")}async function Ut(t,e,n,r={}){He(t,e),await As(t,e,`${JSON.stringify(n)}
|
|
147
|
+
`,et.trajectory,"Run trajectory",r)}async function gn(t,e,n={}){He(t,e);let r=await mt(t,e,et.trajectory,"Run trajectory",n);return r===null?[]:r.split(/\r?\n/).map((i,s)=>({line:i,number:s+1})).filter(({line:i})=>i.length>0).map(({line:i,number:s})=>{try{return JSON.parse(i)}catch(o){throw new Error(`Invalid Trajectory event at line ${s}`,{cause:o})}})}async function Oc(t,e,n={}){He(t,e);let r=await mt(t,e,et.artifacts,"Run artifacts",n);return r===null?{}:JSON.parse(r)}async function Ms(t,e,n,r={}){He(t,e),await Wt(t,e,JSON.stringify(n,null,2)+`
|
|
148
|
+
`,et.artifacts,"Run artifacts",r)}async function Fs(t,e,n,r={}){He(t,e),await Wt(t,e,n,et.context,"Run context",r)}async function Om(t,e,n={}){return He(t,e),mt(t,e,et.context,"Run context",n)}async function Nm(t,e,n,r={}){He(t,e),await Wt(t,e,JSON.stringify(n,null,2)+`
|
|
149
|
+
`,et.pendingAction,"Run pending action",r)}async function Nc(t,e,n={}){He(t,e);let r=await mt(t,e,et.pendingAction,"Run pending action",n);return r===null?null:JSON.parse(r)}async function jm(t,e,n={}){He(t,e),await Os(t,e,"Run pending action",n)}async function Ds(t,e,n,r={}){He(t,e),await Wt(t,e,JSON.stringify(n,null,2)+`
|
|
150
|
+
`,et.checkpoint,"Run checkpoint",r)}async function Im(t,e,n={}){He(t,e);let r=await mt(t,e,et.checkpoint,"Run checkpoint",n);return r===null?null:JSON.parse(r)}import{createHash as Jm,randomUUID as KC}from"crypto";import{promises as ie}from"fs";import ee from"path";var Lm=Pe(xe(),1);import{promises as jc}from"fs";import Fe from"path";var RC=["invoke_skill","call_tool","handoff","ask_user","checkpoint"],PC=["deterministic","adaptive"],AC=["function","mcp","script","agent"],OC=["none","read","write","external"],NC=["progress","step","completion"],jC=["artifact_exists","state_equals"];function wn(t,e,n){return new Error(`${t}: ${e} ${n}`)}function Re(t,e,n="document"){if(t===null||typeof t!="object"||Array.isArray(t))throw wn(e,n,"must be an object")}function Kt(t,e,n){if(!Array.isArray(t))throw wn(e,n,"must be an array")}function ke(t,e,n){if(typeof t!="string")throw wn(e,n,"must be a string")}function ze(t,e,n,r){e in t&&ke(t[e],n,`${r}.${e}`)}function qm(t,e,n,r){if(e in t&&typeof t[e]!="boolean")throw wn(n,`${r}.${e}`,"must be a boolean")}function Ht(t,e,n,r){if(typeof t!="string"||!e.includes(t))throw wn(n,r,`must be one of ${e.join(", ")}`)}function Ws(t,e,n){Kt(t,e,n),t.forEach((r,i)=>{ke(r,e,`${n}[${i}]`)})}function $m(t,e,n){Re(t,e,n),ke(t.name,e,`${n}.name`),ke(t.description,e,`${n}.description`),qm(t,"required",e,n)}function IC(t,e,n){Re(t,e,n),ke(t.id,e,`${n}.id`),ze(t,"source",e,n),ze(t,"version",e,n)}function $C(t,e,n){Re(t,e,n),ke(t.id,e,`${n}.id`),ke(t.role,e,`${n}.role`),ze(t,"instructions",e,n)}function TC(t,e,n){Re(t,e,n),ke(t.id,e,`${n}.id`),Ht(t.kind,AC,e,`${n}.kind`),ke(t.source,e,`${n}.source`),Ht(t.sideEffect,OC,e,`${n}.sideEffect`),qm(t,"requiresConfirmation",e,n)}function LC(t,e,n){Re(t,e,n),Ht(t.type,RC,e,`${n}.type`),ze(t,"ref",e,n),ze(t,"prompt",e,n),ze(t,"question",e,n),"options"in t&&Ws(t.options,e,`${n}.options`)}function qC(t,e,n){Re(t,e,n),ke(t.id,e,`${n}.id`),LC(t.action,e,`${n}.action`),ze(t,"next",e,n),"completionEvals"in t&&Ws(t.completionEvals,e,`${n}.completionEvals`)}function MC(t,e){let n="goal";Re(t,e,n),ke(t.statement,e,`${n}.statement`),Kt(t.inputs,e,`${n}.inputs`),t.inputs.forEach((r,i)=>{$m(r,e,`${n}.inputs[${i}]`)}),Kt(t.outputs,e,`${n}.outputs`),t.outputs.forEach((r,i)=>{$m(r,e,`${n}.outputs[${i}]`)}),Ws(t.success,e,`${n}.success`)}function FC(t,e){let n="orchestration";Re(t,e,n),Ht(t.mode,PC,e,`${n}.mode`),ze(t,"entry",e,n),"steps"in t&&(Kt(t.steps,e,`${n}.steps`),t.steps.forEach((r,i)=>{qC(r,e,`${n}.steps[${i}]`)}))}function Mm(t,e){return Re(t,e),Ht(t.apiVersion,["comet/v1alpha1"],e,"apiVersion"),Ht(t.kind,["Skill"],e,"kind"),Re(t.metadata,e,"metadata"),ke(t.metadata.name,e,"metadata.name"),ke(t.metadata.version,e,"metadata.version"),ke(t.metadata.description,e,"metadata.description"),MC(t.goal,e),FC(t.orchestration,e),Kt(t.skills,e,"skills"),t.skills.forEach((n,r)=>{IC(n,e,`skills[${r}]`)}),Kt(t.agents,e,"agents"),t.agents.forEach((n,r)=>{$C(n,e,`agents[${r}]`)}),Kt(t.tools,e,"tools"),t.tools.forEach((n,r)=>{TC(n,e,`tools[${r}]`)}),t}function Fm(t,e){Re(t,e);for(let n of["allowedSkills","allowedAgents","allowedTools","confirmationRequiredFor"])n in t&&Ws(t[n],e,n);for(let n of["maxIterations","maxRetriesPerAction"])if(n in t&&(typeof t[n]!="number"||!Number.isFinite(t[n])))throw wn(e,n,"must be a finite number");return t}function DC(t,e){return Re(t,e),"runtime"in t&&Dm(t.runtime,e,"runtime"),t}function Dm(t,e,n){return Kt(t,e,n),t.forEach((r,i)=>{let s=`${n}[${i}]`;Re(r,e,s),ke(r.id,e,`${s}.id`),Ht(r.scope,NC,e,`${s}.scope`),Ht(r.type,jC,e,`${s}.type`),ze(r,"artifact",e,s),ze(r,"field",e,s),ze(r,"equals",e,s)}),t}async function Ic(t){let e=await jc.readFile(t,"utf8");try{return(0,Lm.parse)(e)}catch(n){let r=n instanceof Error?n.message:String(n);throw wn(t,"document",r)}}async function WC(t){try{return await Ic(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function Tm(t){try{return await jc.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function BC(t){let e=Fe.join(t,"checks.yaml"),n=Fe.join(t,"evals.yaml"),[r,i]=await Promise.all([Tm(e),Tm(n)]);if(i)throw new Error(`${n}: evals.yaml is no longer supported; use checks.yaml`);return r?{document:DC(await Ic(e),e)}:{document:null}}async function Wm(t){let e=Fe.resolve(t.root),n=Fe.resolve(t.controlRoot);t.requireSkillMarkdown&&await jc.access(Fe.join(e,"SKILL.md"));let r=Fe.join(n,"skill.yaml"),i=Fe.join(n,"guardrails.yaml"),s=Mm(await Ic(r),r),o=await WC(i),a=o===null?null:Fm(o,i),c=await BC(n),l={allowedSkills:s.skills.map(u=>u.id),allowedAgents:s.agents.map(u=>u.id),allowedTools:s.tools.map(u=>u.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:s.tools.filter(u=>u.requiresConfirmation).map(u=>u.id)};return{root:e,packageKind:t.packageKind==="runtime"?"runtime":void 0,definition:s,guardrails:{...l,...a},evals:c.document?.runtime??[]}}async function Bm(t){let e=Fe.resolve(t);return Wm({root:e,controlRoot:Fe.join(e,"comet"),packageKind:"skill",requireSkillMarkdown:!0})}async function Um(t){let e=Fe.resolve(t);return Wm({root:e,controlRoot:e,packageKind:"runtime",requireSkillMarkdown:!1})}function Km(t,e,n=Fe.join(e,"package.json")){Re(t,n);let r=t.packageKind==="runtime"?"runtime":void 0,i=Mm(t.definition,n),s=Fm(t.guardrails,n),o=Dm(t.evals,n,"evals"),a={allowedSkills:i.skills.map(c=>c.id),allowedAgents:i.agents.map(c=>c.id),allowedTools:i.tools.map(c=>c.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:i.tools.filter(c=>c.requiresConfirmation).map(c=>c.id)};return{root:Fe.resolve(e),packageKind:r,definition:i,guardrails:{...a,...s},evals:o}}import Hm from"path";function UC(t,e,n,r){t.type==="invoke_skill"&&!e.definition.skills.some(i=>i.id===t.ref)&&n.push(`step ${r} references undeclared skill: ${t.ref??"(missing)"}`),t.type==="call_tool"&&!e.definition.tools.some(i=>i.id===t.ref)&&n.push(`step ${r} references undeclared tool: ${t.ref??"(missing)"}`),t.type==="handoff"&&!e.definition.agents.some(i=>i.id===t.ref)&&n.push(`step ${r} references undeclared agent: ${t.ref??"(missing)"}`),t.type==="ask_user"&&!t.question&&n.push(`step ${r} ask_user action requires question`)}function zm(t){let e=[],{definition:n,guardrails:r,evals:i}=t;n.apiVersion!=="comet/v1alpha1"&&e.push("unsupported apiVersion"),n.kind!=="Skill"&&e.push("kind must be Skill"),n.metadata.name||e.push("metadata.name is required"),n.goal.statement||e.push("goal.statement is required"),r.maxIterations<1&&e.push("maxIterations must be at least 1"),r.maxRetriesPerAction<0&&e.push("maxRetriesPerAction must not be negative");let s=n.orchestration.steps??[];if(n.orchestration.mode==="adaptive")(n.orchestration.entry||s.length>0)&&e.push("adaptive orchestration must not define entry or steps");else{let o=new Set;for(let a of s)o.has(a.id)&&e.push(`duplicate step id: ${a.id}`),o.add(a.id),UC(a.action,t,e,a.id);(!n.orchestration.entry||!o.has(n.orchestration.entry))&&e.push(`orchestration.entry references unknown step: ${n.orchestration.entry??"(missing)"}`);for(let a of s){a.next&&!o.has(a.next)&&e.push(`step ${a.id} has unknown next step: ${a.next}`);for(let c of a.completionEvals??[])i.some(l=>l.id===c)||e.push(`step ${a.id} references unknown eval: ${c}`)}}for(let o of n.tools){if(o.kind!=="script")continue;let a=Hm.posix.normalize(o.source.replaceAll("\\","/"));(Hm.isAbsolute(o.source)||a===".."||a.startsWith("../"))&&e.push(`script tool ${o.id} must reference a relative path inside the Skill package`)}for(let o of r.allowedSkills)n.skills.some(a=>a.id===o)||e.push(`guardrails allow undeclared skill: ${o}`);for(let o of r.allowedAgents)n.agents.some(a=>a.id===o)||e.push(`guardrails allow undeclared agent: ${o}`);for(let o of r.allowedTools)n.tools.some(a=>a.id===o)||e.push(`guardrails allow undeclared tool: ${o}`);return e}function Bs(t){return Array.isArray(t)?t.map(Bs):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,Bs(n)])):t}function HC(t){return Bs({...t.packageKind==="runtime"?{packageKind:"runtime"}:{},definition:t.definition,guardrails:t.guardrails,evals:t.evals})}function zC(t){return ee.posix.normalize(t.replaceAll("\\","/"))}function Un(t,e,n){let r=ee.relative(t,e);if(!(r===""||!ee.isAbsolute(r)&&!r.startsWith(`..${ee.sep}`)))throw new Error(`${n} resolves outside the Skill package`)}async function Gm(t,e,n){let r=zC(e);if(ee.posix.isAbsolute(r)||r===".."||r.startsWith("../"))throw new Error(`${n} resolves outside the Skill package`);let i=ee.resolve(t,...r.split("/"));Un(t,i,n);let s;try{s=await ie.realpath(i)}catch(o){throw o.code==="ENOENT"?new Error(`${n} does not exist: ${e}`,{cause:o}):o}if(Un(t,s,n),!(await ie.stat(s)).isFile())throw new Error(`${n} is not a file: ${e}`);return{path:r,content:await ie.readFile(s)}}async function JC(t){let e=await ie.realpath(t.root),n=t.packageKind==="runtime"?[]:[await Gm(e,"SKILL.md","SKILL.md")];for(let r of t.definition.tools)r.kind==="script"&&n.push(await Gm(e,r.source,`Script tool ${r.id}`));return n.sort((r,i)=>r.path.localeCompare(i.path))}function GC(t,e){let n=e.map(r=>({path:r.path,sha256:Jm("sha256").update(r.content).digest("hex")}));return Jm("sha256").update(JSON.stringify(Bs({package:t,files:n}))).digest("hex")}function Xm(t){return JSON.stringify(t,null,2)+`
|
|
151
|
+
`}async function Qm(t){let e=HC(t),n=await JC(t);return{document:e,files:n,hash:GC(e,n)}}async function Us(t){return(await Qm(t)).hash}async function Ym(t){try{return await ie.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Vm(t,e){try{if((await ie.readFile(ee.join(t,"sha256"),"utf8")).trim()!==e.hash)throw new Error("hash mismatch");if(await ie.readFile(ee.join(t,"package.json"),"utf8")!==Xm(e.document))throw new Error("package mismatch");for(let i of e.files)if(!(await ie.readFile(ee.join(t,...i.path.split("/")))).equals(i.content))throw new Error(`file mismatch: ${i.path}`)}catch(n){throw new Error(`Existing Skill snapshot is invalid: ${e.hash}`,{cause:n})}}async function $c(t,e){let n=await Qm(t),r=ee.resolve(e,".comet","skill-snapshots"),i=ee.join(r,n.hash);if(await ie.mkdir(r,{recursive:!0}),await Ym(i))return await Vm(i,n),{hash:n.hash,snapshotDir:i};let s=ee.join(r,`.tmp-${KC()}`);Un(r,s,"Temporary snapshot"),Un(r,i,"Published snapshot");try{await ie.mkdir(s);for(let o of n.files){let a=ee.join(s,...o.path.split("/"));Un(s,a,`Snapshot file ${o.path}`),await ie.mkdir(ee.dirname(a),{recursive:!0}),await ie.writeFile(a,o.content)}await ie.writeFile(ee.join(s,"package.json"),Xm(n.document)),await ie.writeFile(ee.join(s,"sha256"),n.hash+`
|
|
152
|
+
`),await ie.rename(s,i)}catch(o){if(await Ym(i)){try{await Vm(i,n)}finally{await ie.rm(s,{recursive:!0,force:!0})}return{hash:n.hash,snapshotDir:i}}throw await ie.rm(s,{recursive:!0,force:!0}),o}return{hash:n.hash,snapshotDir:i}}async function Tc(t,e){if(!/^[a-f0-9]{64}$/u.test(e))throw new Error(`Invalid Skill snapshot hash: ${e}`);let n=ee.resolve(t,".comet","skill-snapshots"),r=ee.join(n,e);Un(n,r,"Skill snapshot");try{let i=(await ie.readFile(ee.join(r,"sha256"),"utf8")).trim();if(i!==e)throw new Error(`stored hash is ${i||"(empty)"}`);let s=ee.join(r,"package.json"),o=JSON.parse(await ie.readFile(s,"utf8")),a=Km(o,r,s),c=zm(a);if(c.length>0)throw new Error(c.map(u=>` - ${u}`).join(`
|
|
153
|
+
`));let l=await Us(a);if(l!==e)throw new Error(`calculated hash is ${l}`);return a}catch(i){throw new Error(`Skill snapshot is invalid or missing: ${e}`,{cause:i})}}async function Zm(t){try{return await Lc.access(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}function ep(t){return YC("sha256").update(t).digest("hex")}function XC(t){return ep(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)))))}function QC(t){return t.replaceAll(".","_").replaceAll("-","_")}async function ZC(t,e){let n=await dt(t),r=Object.fromEntries(e.filter(o=>o.satisfied&&o.source).map(o=>[QC(o.code),o.source])),i=pt.join(t,"subagent-progress.md");await Zm(i)&&(r.subagent_progress=pt.relative(n,i).split(pt.sep).join("/"));let s=e.find(o=>o.code==="design.handoff"&&o.satisfied);return s?.source&&(r.handoff_context=s.source),r}function eS(t,e,n){return[{sequence:1,timestamp:n,type:"run_started",runId:t.runId,data:{skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash}},{sequence:2,timestamp:n,type:"state_migrated",runId:t.runId,data:{kind:"classic",migrationVersion:mn,profile:e,source:"pre-migration"}}]}async function tS(t){await Promise.all(t.map(e=>Lc.rm(e,{recursive:!0,force:!0})))}async function tp(t,e){return pe(t,()=>nS(t,e))}async function nS(t,e){let n=await V(t);if(!n.classic)throw new Error("Classic migration requires a legacy state projection");let r=n.classic,i=r.classicProfile??r.workflow;if(n.run){if(r.classicMigration!==mn)throw new Error("Classic Run exists without a supported classic_migration marker");if(n.run.skill!==e.skillPackage.definition.metadata.name)throw new Error(`Classic Run skill mismatch: expected ${e.skillPackage.definition.metadata.name}, got ${n.run.skill}`);if(await Us(e.skillPackage)!==n.run.skillHash)return await Tc(t,n.run.skillHash),{classic:r,run:n.run,evidence:await Dt(t,n),migrated:!1,snapshotDir:pt.join(t,".comet","skill-snapshots",n.run.skillHash)};let f=await $c(e.skillPackage,t);return{classic:r,run:n.run,evidence:await Dt(t,n),migrated:!1,snapshotDir:f.snapshotDir}}let s=await Dt(t,n),o=Fn(r,s);if(!e.skillPackage.definition.orchestration.steps?.some(d=>d.id===o))throw new Error(`Classic Skill package does not define resolved step: ${o}`);let a=await Us(e.skillPackage),c=pt.join(t,".comet","skill-snapshots",a),l=await Zm(c),u=[];try{let d=await $c(e.skillPackage,t),f=Am(e.skillPackage,e.runId?.()??VC(),d.hash);f.currentStep=o,o==="completed"&&(f.status="completed");let p={...r,classicProfile:i,classicMigration:mn},g=await ZC(t,s),m=await dt(t),h=s.find(b=>b.code==="design.handoff"&&b.satisfied),v=null;h?.source&&(v=await I(m,h.resolvedSource??h.source,{label:"Classic migration handoff context",hooks:e.handoffReadHooks}),await Fs(t,f.contextRef,v),u.push(pt.resolve(t,f.contextRef))),await Ms(t,f.artifactsRef,g),u.push(pt.resolve(t,f.artifactsRef));let y=(e.now?.()??new Date).toISOString(),S={runId:f.runId,stateVersion:1,trajectoryOffset:2,contextHash:v===null?null:ep(v),artifactsHash:XC(g),createdAt:y};await Ds(t,f.checkpointRef,S),u.push(pt.resolve(t,f.checkpointRef)),u.push(pt.resolve(t,f.trajectoryRef));for(let b of eS(f,i,y))await Ut(t,f.trajectoryRef,b);return await hn(t,{classic:p,run:f,unknownKeys:n.unknownKeys}),{classic:p,run:f,evidence:s,migrated:!0,snapshotDir:d.snapshotDir}}catch(d){throw await tS(u),l||await Lc.rm(c,{recursive:!0,force:!0}),d}}async function rS(t){try{return(await np.stat(t)).isDirectory()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Ks(t){try{return(await np.stat(t)).isFile()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function iS(t){return await rS(t)?await Ks(Ie.join(t,"skill.yaml"))?!0:await Ks(Ie.join(t,"SKILL.md"))&&await Ks(Ie.join(t,"comet","skill.yaml")):!1}function sS(t){return{root:t,packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-classic",version:"1",description:"Internal compatibility orchestration for classic Comet full, hotfix, and tweak workflows"},goal:{statement:"Advance or restore a classic Comet Run without changing the user command surface",inputs:[{name:"classic-state",description:"Validated ClassicState consistent with the Run projection",required:!0},{name:"evidence",description:"Structured evidence produced by the Classic Evidence collector",required:!0}],outputs:[{name:"run-state",description:"Atomically synchronized Classic and Run state",required:!0}],success:["Legacy fields and Run fields remain consistent","Every step invokes only a declared public Comet Skill","The completed state passes its completion eval"]},orchestration:{mode:"deterministic",entry:"full.open",steps:[{id:"full.open",action:{type:"invoke_skill",ref:"comet-open"},next:"full.design.handoff"},{id:"full.design.handoff",action:{type:"invoke_skill",ref:"comet-design"},next:"full.design.document"},{id:"full.design.document",action:{type:"invoke_skill",ref:"comet-design"},next:"full.build.configure"},{id:"full.build.plan",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.plan-ready"},{id:"full.build.plan-ready",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.build.configure",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.plan"},{id:"full.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.complete"},{id:"full.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"full.verify.run"},{id:"full.build.fix",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{id:"full.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.verify.branch"},{id:"full.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"full.archive.confirm"},{id:"full.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"full.archive.execute"},{id:"full.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"hotfix.open",action:{type:"invoke_skill",ref:"comet-hotfix"},next:"hotfix.build.execute"},{id:"hotfix.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.build.complete"},{id:"hotfix.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"hotfix.verify.run"},{id:"hotfix.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.verify.branch"},{id:"hotfix.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"hotfix.archive.confirm"},{id:"hotfix.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"hotfix.archive.execute"},{id:"hotfix.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"tweak.open",action:{type:"invoke_skill",ref:"comet-tweak"},next:"tweak.build.execute"},{id:"tweak.build.execute",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.build.complete"},{id:"tweak.build.complete",action:{type:"invoke_skill",ref:"comet-build"},next:"tweak.verify.run"},{id:"tweak.verify.run",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.verify.branch"},{id:"tweak.verify.branch",action:{type:"invoke_skill",ref:"comet-verify"},next:"tweak.archive.confirm"},{id:"tweak.archive.confirm",action:{type:"invoke_skill",ref:"comet-archive"},next:"tweak.archive.execute"},{id:"tweak.archive.execute",action:{type:"invoke_skill",ref:"comet-archive"},next:"completed"},{id:"completed",action:{type:"checkpoint"},completionEvals:["classic-completed"]}]},skills:[{id:"comet-open"},{id:"comet-design"},{id:"comet-build"},{id:"comet-verify"},{id:"comet-archive"},{id:"comet-hotfix"},{id:"comet-tweak"}],agents:[],tools:[]},guardrails:{allowedSkills:["comet-open","comet-design","comet-build","comet-verify","comet-archive","comet-hotfix","comet-tweak"],allowedAgents:[],allowedTools:[],maxIterations:500,maxRetriesPerAction:3,confirmationRequiredFor:[]},evals:[{id:"classic-completed",scope:"completion",type:"state_equals",field:"status",equals:"completed"}]}}async function oS(){let t=Ie.dirname(rp(import.meta.url)),e=[process.env.COMET_RUNTIME_CLASSIC_ROOT,Ie.resolve(t,"..","runtime","classic"),Ie.resolve(t,"..","..","comet","runtime","classic"),Ie.resolve(t,"..","..","assets","skills","comet","runtime","classic"),Ie.resolve("assets","skills","comet","runtime","classic"),process.env.COMET_CLASSIC_SKILL_ROOT,Ie.resolve(t,"..","..","comet-classic"),Ie.resolve(t,"..","..","assets","skills","comet-classic"),Ie.resolve("assets","skills","comet-classic")].filter(n=>!!n);for(let n of e)if(await iS(n))return n;return null}async function aS(t){return await Ks(Ie.join(t,"skill.yaml"))?Um(t):Bm(t)}async function Kn(t){let e=await oS();return tp(t,{skillPackage:e?await aS(e):sS(Ie.dirname(rp(import.meta.url)))})}async function ip(t){let e=await V(t),n=Array.from(new Set(e.unknownKeys)).sort();if(n.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${n.join(", ")}`);return Kn(t)}async function Hs(t,e,n,r){return pe(t,()=>cS(t,e,n,r))}async function cS(t,e,n,r){let i=await V(t);if(!i.classic||!i.run)throw new Error("Classic transition requires synchronized Classic and Run projections");if(i.run.runId!==n.runId||i.run.iteration!==n.iteration||(e.checkEpoch??0)<(i.classic.checkEpoch??0))throw new Error("Classic transition became stale; reload the current state");let s=await Dt(t,{classic:e,run:n,unknownKeys:i.unknownKeys}),o=Fn(e,s),a={...n,currentStep:o,iteration:n.iteration+1,status:o==="completed"?"completed":"running"};await hn(t,{classic:e,run:a,unknownKeys:i.unknownKeys});let c=await gn(t,a.trajectoryRef);return await Ut(t,a.trajectoryRef,{sequence:c.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:a.runId,data:{kind:"classic",fromStep:n.currentStep,toStep:o,...r}}),a}function Vr(t){return t==="zh-CN"?"zh-CN":"en"}function Yr(t,e,n){return t==="zh-CN"?n:e}var qc={open:{en:"open (clarifying the request)",zh:"open(需求澄清)"},design:{en:"design",zh:"design(方案设计)"},build:{en:"build",zh:"build(实现)"},verify:{en:"verify",zh:"verify(验证)"},archive:{en:"archive",zh:"archive(归档)"}};function zs(t,e){return qc[t]?Yr(e,qc[t].en,qc[t].zh):t}function sp(t){let{name:e,phase:n,failed:r,total:i,locale:s}=t;return r===0?{summary:Yr(s,`Change ${e} passed every check for leaving the ${zs(n,s)} stage (${i} total) and is ready to proceed.`,`需求 ${e} 通过了离开 ${zs(n,s)}阶段的全部 ${i} 项检查,可以继续推进。`)}:{summary:Yr(s,`Change ${e} is not ready to leave the ${zs(n,s)} stage yet: ${r} of ${i} checks failed. The failing items below are the Agent's checklist, not user actions.`,`需求 ${e} 暂时还不能离开 ${zs(n,s)}阶段:${r}/${i} 项检查未通过。下方的失败项是给 Agent 的检查清单,不需要用户处理。`),user_message:Yr(s,"A few preparation items are still missing before this change can move to the next stage; the Agent is filling them in and will continue afterwards.","这条需求要进入下一阶段还差几项准备工作;Agent 正在补齐,之后会自动继续。")}}function Mc(t){let{name:e,locale:n}=t;return{summary:Yr(n,`Handoff context for ${e} was written and recorded; the Build phase can resume from it.`,`需求 ${e} 的交接上下文已写入并记录,Build 阶段可据此继续。`)}}var lS="\x1B[32m",uS="\x1B[31m",dS="\x1B[33m",Wc="\x1B[0m";function zt(t){return`${lS}${t}${Wc}`}function $e(t){return`${uS}${t}${Wc}`}function op(t){return`${dS}${t}${Wc}`}var he=class extends Error{constructor(n,r=1){super(n);this.exitCode=r}exitCode},Fc=class{stdout=[];stderr=[];envelope;toResult(e=0){return{exitCode:e,...this.stdout.length>0?{stdout:this.stdout.join(`
|
|
154
154
|
`)+`
|
|
155
155
|
`}:{},...this.stderr.length>0?{stderr:this.stderr.join(`
|
|
156
156
|
`)+`
|
|
157
|
-
`}:{},...this.envelope===void 0?{}:{envelope:this.envelope}}}};async function
|
|
158
|
-
`)).digest("hex")}async function mS(t,e,n){let r=await Js(t,e,"handoff_context");if(!r||r==="null")return null;let i=await
|
|
159
|
-
`&&(n+=1,n===e))return t.slice(0,r+1);return t}async function hS(t,e,n,r,i,s,o){let a=["# Comet Design Handoff","",`- Change: ${r}`,"- Phase: design",`- Mode: ${i}`,`- Context hash: ${s}`,"","Generated-by: comet-handoff.sh","Task hash policy: task-content-v1. Read tasks.md for live completion; excerpts are design-time context.","","OpenSpec remains the canonical capability spec. This handoff is a deterministic, source-traceable context pack, not an agent-authored summary.",""];for(let c of await vn(t,e)){let l=yn(e,n,c),u=await
|
|
160
|
-
`),"Classic handoff markdown output")}async function gS(t,e,n,r,i,s,o){let a=[];for(let u of await vn(t,e)){let d=yn(e,n,u),f=await
|
|
157
|
+
`}:{},...this.envelope===void 0?{}:{envelope:this.envelope}}}};async function De(t,e,n){return await G(t,e,{label:n,expected:"file"})?I(t,e,{label:n}):null}async function Ys(t,e,n,r){await $t(t,e,n,{label:r})}function fS(t){let e=dn(t);if(e)throw new he($e(`ERROR: ${e}`))}function Vs(t){return cp("sha256").update(t).digest("hex")}function up(t){return Vs(JSON.stringify(Object.fromEntries(Object.entries(t).sort(([e],[n])=>e.localeCompare(n)))))}async function vn(t,e){let n=[`${e}/proposal.md`,`${e}/design.md`,`${e}/tasks.md`];return await G(t,`${e}/.openspec.yaml`,{label:"OpenSpec metadata",expected:"file"})&&n.push(`${e}/.openspec.yaml`),n.push(...await ft(t,`${e}/specs`)),n}function yn(t,e,n){let r=Dc.relative(t,n).replaceAll("\\","/");return`${e}/${r}`}async function Gs(t,e,n){let r=[];for(let i of await vn(t,e)){let s=yn(e,n,i),o=await De(t,i,`Classic handoff source ${s}`);o!==null&&r.push(`path:${s}`,`sha256:${Qe(i,o)}`)}return cp("sha256").update(r.join(`
|
|
158
|
+
`)).digest("hex")}async function mS(t,e,n){let r=await Js(t,e,"handoff_context");if(!r||r==="null")return null;let i=await De(t,`${r.replace(/\.json$/u,"")}.md`,"Classic handoff markdown");if(i===null)return null;let s=new Map,o=null;for(let c of i.split(/\r?\n/u)){let l=/^- Source: (.+)$/u.exec(c);if(l){o=l[1];continue}let u=/^- SHA256: ([a-f0-9]{64})$/u.exec(c);u&&o!==null&&(s.set(o,u[1]),o=null)}if(s.size===0)return null;let a=[];for(let c of await vn(t,e)){let l=yn(e,n,c),u=s.get(l);if(u===void 0)continue;let d=await De(t,c,`Classic handoff source ${l}`);(d===null||Qe(c,d)!==u)&&a.push(l)}return a}function ap(t){return t.replace(/\\/gu,"\\\\").replace(/"/gu,'\\"')}function dp(t){return(t.match(/\n/gu)??[]).length}function pS(t,e){let n=0;for(let r=0;r<t.length;r+=1)if(t[r]===`
|
|
159
|
+
`&&(n+=1,n===e))return t.slice(0,r+1);return t}async function hS(t,e,n,r,i,s,o){let a=["# Comet Design Handoff","",`- Change: ${r}`,"- Phase: design",`- Mode: ${i}`,`- Context hash: ${s}`,"","Generated-by: comet-handoff.sh","Task hash policy: task-content-v1. Read tasks.md for live completion; excerpts are design-time context.","","OpenSpec remains the canonical capability spec. This handoff is a deterministic, source-traceable context pack, not an agent-authored summary.",""];for(let c of await vn(t,e)){let l=yn(e,n,c),u=await De(t,c,`Classic handoff source ${l}`);if(u===null)continue;let d=dp(u);a.push(`## ${l}`,"",`- Source: ${l}`,`- Lines: 1-${d}`,`- SHA256: ${Qe(c,u)}`,""),i==="full"||d<=80?a.push("```md",u,"```"):a.push("[TRUNCATED]","","```md",pS(u,80),"```","",`Full source: ${l}`),a.push("")}await Ys(t,o,a.join(`
|
|
160
|
+
`),"Classic handoff markdown output")}async function gS(t,e,n,r,i,s,o){let a=[];for(let u of await vn(t,e)){let d=yn(e,n,u),f=await De(t,u,`Classic handoff source ${d}`);f!==null&&a.push(` { "path": "${ap(d)}", "sha256": "${Qe(u,f)}" }`)}let c=a.join(`,
|
|
161
161
|
`),l=["{",` "change": "${ap(r)}",`,' "phase": "design",',` "mode": "${i}",`,' "canonical_spec": "openspec",',' "task_hash_policy": "task-content-v1",',' "generated_by": "comet-handoff.sh",',` "context_hash": "${s}",`,' "files": [',c," ]","}",""].join(`
|
|
162
|
-
`);await Ys(t,o,l,"Classic handoff JSON output")}async function wS(t,e){return[`## ${t}`,"",`- Source: ${t}`,`- Lines: 1-${dp(e)}`,`- SHA256: ${Vs(e)}`,"","```md",e,"```",""]}async function yS(t,e,n,r,i,s){let o=["# Comet Spec Context","",`- Change: ${r}`,"- Phase: design","- Mode: beta",`- Context hash: ${i}`,"","Generated-by: comet-handoff.sh","","OpenSpec remains the canonical capability spec. This beta context pack verbatim-projects spec files and references supporting artifacts by hash, not an agent-authored summary.","","## Source References",""];for(let l of await vn(t,e)){let u=yn(e,n,l),d=await
|
|
163
|
-
`),"Classic handoff spec markdown output")}async function vS(t,e,n,r,i,s){let o=[];for(let a of await vn(t,e)){let c=yn(e,n,a),l=await
|
|
164
|
-
`,"Classic handoff spec JSON output")}async function Js(t,e,n){let r=Dc.join(e,".comet.yaml"),i=(0,lp.parseDocument)(await I(t,r,{label:"Classic change state"}),{uniqueKeys:!1});if(i.errors.length>0)throw new
|
|
165
|
-
`)));let p=f.files.map(
|
|
166
|
-
`));let b=K(c.projectRoot,y),x=K(c.projectRoot,S),w=await Gs(c.projectRoot,u,d),C=`classic-handoff:${w}`,k=await V(u);if(!k.classic)throw new
|
|
167
|
-
`))e.stderr.push(l);return e.toResult(c.exitCode)}throw c}});async function mp(t,e,n){let r=[],i=SS.basename(e);if(n.designDoc)try{let o=await I(t,n.designDoc,{label:"Classic Design Doc"}),a=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u.exec(o)?.[1],c=a===void 0?null:(0,fp.parseDocument)(a);for(let[l,u]of Object.entries({comet_change:i,role:"technical-design",canonical_spec:"openspec"})){let d=c?.get(l)??null;(c?.errors.length||d!==u)&&r.push({code:"CLASSIC_DESIGN_METADATA_INVALID",field:l,path:n.designDoc,actual:d,expected:u,message:`Design Doc ${l} must be ${u}.`,remediation:"Repair the reported metadata in the selected change design; preserve confirmed content."})}}catch(o){r.push(
|
|
162
|
+
`);await Ys(t,o,l,"Classic handoff JSON output")}async function wS(t,e){return[`## ${t}`,"",`- Source: ${t}`,`- Lines: 1-${dp(e)}`,`- SHA256: ${Vs(e)}`,"","```md",e,"```",""]}async function yS(t,e,n,r,i,s){let o=["# Comet Spec Context","",`- Change: ${r}`,"- Phase: design","- Mode: beta",`- Context hash: ${i}`,"","Generated-by: comet-handoff.sh","","OpenSpec remains the canonical capability spec. This beta context pack verbatim-projects spec files and references supporting artifacts by hash, not an agent-authored summary.","","## Source References",""];for(let l of await vn(t,e)){let u=yn(e,n,l),d=await De(t,l,`Classic handoff source ${u}`);d!==null&&o.push(`- Source: ${u}`,`- SHA256: ${Qe(l,d)}`)}o.push("","## Acceptance Projection","");let a=`${e}/specs`,c=!1;for(let l of await ft(t,a)){let u=await De(t,l,`Classic handoff spec ${l}`);u!==null&&(c=!0,o.push(...await wS(yn(e,n,l),u)))}c||o.push("No delta spec files found.",""),o.push("Full source files remain canonical. If a required heading or scenario is missing here, regenerate the handoff or read the source spec directly. Supporting files (proposal, design, tasks) are referenced by hash only.","Task hash policy: task-content-v1. Read tasks.md for live completion; task hashes ignore checkbox completion only."),await Ys(t,s,o.join(`
|
|
163
|
+
`),"Classic handoff spec markdown output")}async function vS(t,e,n,r,i,s){let o=[];for(let a of await vn(t,e)){let c=yn(e,n,a),l=await De(t,a,`Classic handoff source ${c}`);if(l===null)continue;let u=/\/specs\/.+\/spec\.md$/u.test(c)?"spec":"supporting";o.push({path:c,sha256:Qe(a,l),role:u})}await Ys(t,s,`${JSON.stringify({change:r,phase:"design",mode:"beta",task_hash_policy:"task-content-v1",canonical_spec:"openspec",generated_by:"comet-handoff.sh",context_hash:i,files:o},null,2)}
|
|
164
|
+
`,"Classic handoff spec JSON output")}async function Js(t,e,n){let r=Dc.join(e,".comet.yaml"),i=(0,lp.parseDocument)(await I(t,r,{label:"Classic change state"}),{uniqueKeys:!1});if(i.errors.length>0)throw new he(`ERROR: Invalid .comet.yaml: ${i.errors[0].message}`);let o=i.toJS()[n];return o==null?"":typeof o=="object"?JSON.stringify(o):String(o)}async function kS(t,e,n){let r=await gn(t,e.trajectoryRef);r.some(s=>s.type==="recovery_reconciled"&&s.data.kind==="classic-handoff"&&s.data.actionId===n)||await Ut(t,e.trajectoryRef,{sequence:r.length+1,timestamp:new Date().toISOString(),type:"recovery_reconciled",runId:e.runId,data:{kind:"classic-handoff",actionId:n}})}async function bS(t,e,n,r){let i=await De(t,n,"Classic handoff markdown output");if(i===null)return!1;let s=new Set(i.split(/\r?\n/u));if(!s.has(`- Context hash: ${r}`))return!1;for(let o of await vn(t,e)){let a=await De(t,o,`Classic handoff source ${o}`);if(a!==null&&!s.has(`- SHA256: ${Qe(o,a)}`))return!1}return!0}async function CS(t,e,n,r,i,s,o,a){let[c,l,u]=await Promise.all([Om(e,n.contextRef),Oc(e,n.artifactsRef),Im(e,n.checkpointRef)]),[d,f]=await Promise.all([De(t,i,"Classic handoff JSON output"),De(t,s,"Classic handoff markdown output")]);return d===null||f===null||c!==f||l.handoff_context!==o||l.handoff_markdown!==a?!1:u?.runId===n.runId&&u.contextHash===(c===null?null:Vs(c))&&u.artifactsHash===up(l)&&r.length===64}var nj=qn(async t=>{let e=new Fc,[n,r,i,s]=t,o=t.length===2&&r==="--hash-only",a=r==="design"&&i==="--write"&&(t.length===3||t.length===4&&s==="--full");if(!o&&!a)return{exitCode:64,stderr:"Usage: comet handoff <change-name> design --write [--full] | comet handoff <change-name> --hash-only"};try{fS(n);let c=await on(T()),l=await Kf(n,c.projectRoot),u=l.directory,d=K(c.projectRoot,u);if(!l.exists)throw new he($e(`ERROR: change directory not found: ${d}`));return await pe(u,async()=>{let f=await Br(c.projectRoot,u);if(f.problems.length)throw new he($e(f.problems.join(`
|
|
165
|
+
`)));let p=f.files.map(te=>Dc.relative(u,te).replaceAll("\\","/"));if(r==="--hash-only"){if(!l.exists)throw new he($e(`ERROR: change directory not found: ${d}`));for(let We of p)if(!await Oe(c.projectRoot,`${u}/${We}`,`Classic handoff source ${We}`))throw new he($e(`ERROR: required file missing or empty: ${d}/${We}`));let te=await Gs(c.projectRoot,u,d);e.stdout.push(te);let Xt=l.stateExists?(await Js(c.projectRoot,u,"handoff_hash")).trim():"";if(/^[a-f0-9]{64}$/u.test(Xt)&&Xt===te)e.stderr.push("[HANDOFF] status: FRESH"),e.stderr.push("Recorded handoff hash matches the current OpenSpec artifacts; reuse content already in context and read only missing acceptance sections.");else{let We=l.stateExists?await mS(c.projectRoot,u,d).catch(()=>null):null;e.stderr.push(`[HANDOFF] status: STALE${We?.length?` (changed: ${We.join(", ")})`:""}`),e.stderr.push(`Recorded: ${Xt||"none"}`),e.stderr.push(`Current: ${te}`),e.stderr.push(We?.length?`NEXT: comet handoff ${n} design --write, then read the changed artifacts listed above in full before verifying acceptance`:`NEXT: comet handoff ${n} design --write, then read every required source file in full because the recorded handoff is missing or predates the current artifacts`)}return e.toResult(0)}let g=s==="--full"?"full":"compact";if(!l.exists)throw new he($e(`ERROR: change directory not found: ${d}`));if(!l.stateExists)throw new he($e(`ERROR: .comet.yaml not found at ${d}/.comet.yaml`));let m=await Js(c.projectRoot,u,"phase");if(m!=="design"&&m!=="build")throw new he($e("ERROR: design handoff requires phase: design or build"));for(let te of p)if(!await Oe(c.projectRoot,`${u}/${te}`,`Classic handoff source ${te}`))throw new he($e(`ERROR: required OpenSpec artifact missing or empty: ${d}/${te}`));let h=`${u}/.comet/handoff`;await me(c.projectRoot,`${u}/.comet`,{label:"Classic change runtime directory",expected:"directory"}),await me(c.projectRoot,h,{label:"Classic handoff directory",expected:"directory"});let v=await Js(c.projectRoot,u,"context_compression")||"off",y,S;if(v==="off")y=`${h}/design-context.json`,S=`${h}/design-context.md`;else if(v==="beta")g==="full"&&e.stderr.push(op("[HANDOFF] --full is ignored in beta mode; spec files are projected verbatim")),g="beta",y=`${h}/spec-context.json`,S=`${h}/spec-context.md`;else throw new he([$e(`ERROR: invalid context_compression: ${v}`),$e("Valid values: off, beta")].join(`
|
|
166
|
+
`));let b=K(c.projectRoot,y),x=K(c.projectRoot,S),w=await Gs(c.projectRoot,u,d),C=`classic-handoff:${w}`,k=await V(u);if(!k.classic)throw new he($e("ERROR: design handoff requires Classic state"));let _=k.run?await Nc(u,k.run.pendingRef):null,P=_?.id===C&&_.type==="handoff"&&_.ref===w;k.classic.handoffHash&&k.classic.handoffHash!==w&&!P&&e.stderr.push(op(`[HANDOFF] refreshing stale design handoff: previous hash ${k.classic.handoffHash}`)),await Pr(c.projectRoot,`${u}/.comet`,"Classic change runtime directory"),await Pr(c.projectRoot,h,"Classic handoff directory");let O=await Kn(u),R=await Nc(u,O.run.pendingRef),$=R?.id===C&&R.type==="handoff"&&R.ref===w;if(O.run.pending&&O.run.pending!==C)throw new he($e(`ERROR: another action is pending: ${O.run.pending}`));if(O.classic.handoffHash===w&&O.classic.handoffContext===b&&!O.run.pending&&!R&&await CS(c.projectRoot,u,O.run,w,y,S,b,x)&&await bS(c.projectRoot,u,S,w))return e.envelope=Mc({name:n,locale:Vr(O.classic.language)}),e.stderr.push(e.envelope.summary),e.stderr.push(zt(`[HANDOFF] wrote ${b}`)),e.stderr.push(zt(`[HANDOFF] wrote ${x}`)),e.stderr.push(zt(`[HANDOFF] handoff_hash=${w}`)),e.toResult(0);let U={id:C,stepId:O.run.currentStep,type:"handoff",ref:w};await Nm(u,O.run.pendingRef,U);let se={...O.run,pending:C,status:"waiting"};await hn(u,{classic:O.classic,run:se,unknownKeys:(await V(u)).unknownKeys}),g==="beta"?(await yS(c.projectRoot,u,d,n,w,S),await vS(c.projectRoot,u,d,n,w,y)):(await hS(c.projectRoot,u,d,n,g,w,S),await gS(c.projectRoot,u,d,n,g,w,y));let de=await I(c.projectRoot,S,{label:"Classic handoff markdown output"});await Fs(u,se.contextRef,de);let q={...await Oc(u,se.artifactsRef),handoff_context:b,handoff_markdown:x};await Ms(u,se.artifactsRef,q);let W={...O.classic,handoffContext:b,handoffHash:w},Ce={...se.currentStep==="full.design.handoff"?await Hs(u,W,se,{actionId:C,kind:"classic-handoff"}):se,pending:null,status:"running"};(P||$)&&await kS(u,Ce,C);let si=await gn(u,Ce.trajectoryRef),we={runId:Ce.runId,stateVersion:Ce.iteration,trajectoryOffset:si.length,contextHash:Vs(de),artifactsHash:up(q),createdAt:new Date().toISOString()};return await Ds(u,Ce.checkpointRef,we),await hn(u,{classic:W,run:Ce,unknownKeys:(await V(u)).unknownKeys}),await jm(u,Ce.pendingRef),e.envelope=Mc({name:n,locale:Vr(W.language)}),e.stderr.push(e.envelope.summary),e.stderr.push(zt(`[SET] handoff_context=${y}`)),e.stderr.push(zt(`[SET] handoff_hash=${w}`)),e.stderr.push(zt(`[HANDOFF] wrote ${b}`)),e.stderr.push(zt(`[HANDOFF] wrote ${x}`)),e.stderr.push(zt(`[HANDOFF] handoff_hash=${w}`)),e.toResult(0)})}catch(c){if(c instanceof he){for(let l of c.message.split(`
|
|
167
|
+
`))e.stderr.push(l);return e.toResult(c.exitCode)}throw c}});async function mp(t,e,n){let r=[],i=SS.basename(e);if(n.designDoc)try{let o=await I(t,n.designDoc,{label:"Classic Design Doc"}),a=/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u.exec(o)?.[1],c=a===void 0?null:(0,fp.parseDocument)(a);for(let[l,u]of Object.entries({comet_change:i,role:"technical-design",canonical_spec:"openspec"})){let d=c?.get(l)??null;(c?.errors.length||d!==u)&&r.push({code:"CLASSIC_DESIGN_METADATA_INVALID",field:l,path:n.designDoc,actual:d,expected:u,message:`Design Doc ${l} must be ${u}.`,remediation:"Repair the reported metadata in the selected change design; preserve confirmed content."})}}catch(o){r.push(Lt(o,{code:"CLASSIC_DESIGN_UNREADABLE",field:"design_doc",path:n.designDoc,remediation:"Restore the recorded Design Doc or register its correct repository-relative reference. Do not clear valid design work."}))}let s="missing";if(n.handoffContext&&n.handoffHash)try{let o=n.handoffContext.replace(/\.json$/u,".md"),a=await Gs(t,e,K(t,e));s=await Oe(t,n.handoffContext,"Classic design handoff")&&await Oe(t,o,"Classic design handoff markdown")&&a===n.handoffHash?"ready":"stale"}catch{s="stale"}return{design:n.designDoc?r.length?"invalid":"ready":"missing",handoff:s,issues:r}}async function pp(t,e,n,r=!1,i){let s=await ue(t),o=i===void 0?await V(e,{migrate:!1}):{classic:n,run:i??null},a=tt.join(e,"tasks.md"),c=await G(t,a,{label:"Classic task authority",expected:"file"}),l=c?await I(t,a,{label:"Classic recovery task authority"}):"",u;try{u=Ne(l)}catch{u=[]}let d=u.find(w=>!w.completed)??null,p=!!(n.plan&&await G(t,n.plan,{label:"Classic plan",expected:"file"}))?await I(t,n.plan,{label:"Classic recovery plan mapping"}):"",g=ys(p,u),m=n.workflow==="full"?await Ir(t,n.plan):null,h=Ar(n),v=h.missingFields.length>0||h.invalidFields.length>0,y=await If(t,e,l),S=n.phase==="archive"?await Lf(t,e):null,b={kind:"continue-phase",reason:"Continue the current phase using confirmed artifacts."},x=n.phase==="design"?await mp(t,e,n):null;if(x)b={kind:x.design==="invalid"?"repair-design":x.design==="missing"?"design":"complete-design",reason:x.design==="invalid"?"Repair only the reported Design Doc metadata or reference; preserve existing confirmed work.":x.design==="missing"?"Continue the existing design and obtain explicit confirmation before registering it.":`Retain the registered Design Doc. Handoff is ${x.handoff}; after confirming recorded user authorization, complete only the remaining Design steps.`,...x.design==="ready"?{cwd:t,argv:["comet","state","complete-design",tt.basename(e),"--design-doc",n.designDoc,"--json"]}:{}};else if(n.phase==="build"){if(n.workflow==="full"&&!n.isolation?b={kind:"workspace",reason:"Resume /comet-open to restore the missing isolation decision without regenerating valid artifacts."}:n.workflow==="full"&&v?b={kind:"configure",reason:`Complete only the missing or invalid configuration in /comet-build before planning (${[...h.missingFields.length?[`missing: ${h.missingFields.join(", ")}`]:[],...h.invalidFields.length?[`invalid: ${h.invalidFields.map(({field:w,reason:C})=>`${w} (${C})`).join("; ")}`]:[]].join("; ")}); retain confirmed settings and any valid plan.`}:n.workflow==="full"&&m?.status!=="ready"?b={kind:"plan",reason:n.buildMode==="autonomous"?"Restore or create the compact implementation plan in the configured plans directory using confirmed design and task IDs. No external planning Skill is required. Preserve existing work.":"Restore the implementation plan in the configured plans directory, or use the confirmed planning method to create it. Preserve existing work and confirmed execution strategy."}:g.unmapped.length?b={kind:"reconcile-plan",reason:"Inspect implementation and acceptance, then map legacy plan items to task IDs or add genuinely extra tasks. Do not reimplement from checkbox state."}:n.buildPause?b={kind:"paused",reason:"Keep the valid plan and confirmed configuration. Clear the explicit plan-ready pause only after the user asks to continue."}:u.length?d?b={kind:"reconcile-task",taskId:d.id,reason:"Check current code, checks and review evidence. Record accepted completion; otherwise finish only the missing implementation, checks or review."}:b={kind:"check",reason:"All tasks done in the authoritative tasks.md. Revalidate or execute Build checks, then run guard --apply."}:b={kind:"reconcile-task",reason:"Restore the task authority and match existing work before proceeding."},b.kind==="reconcile-task"&&y.checkpoint&&!y.stale){let w=u.find(C=>y.checkpoint.taskIds.includes(C.id??"")&&!C.completed);w&&(b={kind:y.checkpoint.stage==="task-review"?"review":["checkoff","done"].includes(y.checkpoint.stage)?y.checkpoint.unresolved.length?"blocked":"checkoff":y.checkpoint.stage==="blocked"?"blocked":"reconcile-task",taskId:w.id,reason:["checkoff","done"].includes(y.checkpoint.stage)&&y.checkpoint.unresolved.length?"Resolve the recorded unresolved items and reconcile acceptance evidence before recording task completion.":"Reconcile the recorded work package with current code and evidence, then resume its exact missing step; do not restart implementation from checkbox state."})}}else n.phase==="verify"?b={kind:n.verifyResult==="pass"?"transition":"verify",reason:n.verifyResult==="pass"?"Verification passed; continue to Archive.":"Resume missing checks or independent review; retain valid evidence."}:n.phase==="archive"&&(b={kind:n.archived?"delivery":n.archiveConfirmation==="confirmed"?"archive":"confirm-archive",reason:n.archived?"Do not archive again. Inspect recorded authorization and actual delivery before continuing.":"Preserve explicit archive and delivery authorization; do not infer it from branch_status."});return{projectRoot:t,workspace:{projectRoot:t},status:o.run?.status??null,stateVersion:null,iteration:o.run?.iteration??null,changeDir:e,artifactRefs:{change:tt.relative(t,e).replaceAll("\\","/"),tasks:tt.relative(t,a).replaceAll("\\","/"),designDoc:n.designDoc??tt.relative(t,tt.join(e,"design.md")).replaceAll("\\","/"),plan:n.plan,plansRoot:tt.relative(t,tt.join(s.superpowersRoot,"plans")).replaceAll("\\","/"),handoffContext:n.handoffContext},...x?{designReadiness:x,issues:x.issues}:{},layout:{schema:"comet.classic-layout.v1",openSpecRoot:s.openSpecRoot,changesRoot:s.changesDir,archiveRoot:s.archiveDir,specsRoot:s.specsDir,superpowersRoot:s.superpowersRoot},configurationReadiness:h,nextAction:b,continuation:{...b,cwd:t,skill:n.phase==="build"&&["hotfix","tweak"].includes(n.workflow)?`comet-${n.workflow}`:`comet-${n.phase}`,automatic:n.autoTransition??!0},evidence:{status:"not-revalidated",reason:"entry"},nextTask:d?.text??null,taskState:{authority:a,exists:c,revision:ws(l),total:u.length,completed:u.filter(w=>w.completed).length,needsIds:u.some(w=>!w.id),next:d,...r?{tasks:u}:{}},planMapping:{status:g.unmapped.length?"reconciliation-required":"ready",unmappedCount:g.unmapped.length,...r?{unmapped:g.unmapped}:{}},coordination:{path:y.checkpoint?tt.join(e,".comet","coordination.json"):null,stale:y.stale,...y.checkpoint?{taskIds:y.checkpoint.taskIds,stage:y.checkpoint.stage,sessionId:y.checkpoint.sessionId,reviewRounds:y.checkpoint.reviewRounds,unresolved:y.checkpoint.unresolved,...r?{checkpoint:y.checkpoint}:{}}:{}},delivery:S,requiredFiles:[a,...n.plan?[tt.resolve(t,n.plan)]:[]]}}import M from"path";var Zc=Pe(xe(),1);import be from"path";import{createHash as Op,randomUUID as Pp}from"node:crypto";import{promises as Zs}from"node:fs";gp();Tr();import{spawnSync as NS}from"node:child_process";import{createHash as zc}from"node:crypto";import{promises as Je}from"node:fs";import F from"node:path";le();Tr();Ve();import{createHash as bp}from"node:crypto";import{createHash as RS}from"node:crypto";function wp(t){return[...t].sort((e,n)=>e.p<n.p?-1:e.p>n.p?1:0).map(e=>JSON.stringify({p:e.p,h:e.h,s:e.s??null,m:e.m??null})).join(`
|
|
168
168
|
`)}function Uc(t){return RS("sha256").update(t).digest("hex")}function yp(t){let e=[];for(let n of t.split(`
|
|
169
|
-
`)){if(!n)continue;let r=JSON.parse(n);if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid check manifest entry");let{p:i,h:s,s:o,m:a}=r;if(typeof i!="string"||!i||typeof s!="string"||!s)throw new Error("Invalid check manifest entry");if(o!==null&&typeof o!="number")throw new Error("Invalid check manifest entry");if(a!==null&&typeof a!="string")throw new Error("Invalid check manifest entry");e.push({p:i,h:s,s:o,m:a})}return e}function Kc(t,e){let n=new Map(t.map(s=>[s.p,s])),r=new Map(e.map(s=>[s.p,s])),i=s=>[...s].sort();return{added:i([...r.keys()].filter(s=>!n.has(s))),removed:i([...n.keys()].filter(s=>!r.has(s))),changed:i([...n.keys()].filter(s=>r.has(s)&&n.get(s).h!==r.get(s).h))}}function Hn(t){return/[*?]/u.test(t)}function Hc(t){let e=[];for(let r=0;r<t.length;r+=1){let i=t[r];i==="*"&&t[r+1]==="*"?(r+=1,t[r+1]==="/"?(r+=1,e.push({kind:"globstar-slash"})):e.push({kind:"globstar"})):i==="*"?e.push({kind:"star"}):i==="?"?e.push({kind:"question"}):e.push({kind:"literal",value:i})}let n=r=>{let i=new Set(r),s=[...r];for(;s.length>0;){let o=s.pop(),a=e[o];a&&(a.kind==="star"||a.kind==="globstar"||a.kind==="globstar-slash")&&!i.has(o+1)&&(i.add(o+1),s.push(o+1))}return i};return r=>{let i=n(new Set([0]));for(let s of r){let o=new Set;for(let a of i){let c=e[a];c&&(c.kind==="literal"&&c.value===s||c.kind==="question"&&s!=="/"?o.add(a+1):c.kind==="star"&&s!=="/"||c.kind==="globstar"?o.add(a):c.kind==="globstar-slash"&&(o.add(a),s==="/"&&o.add(a+1)))}if(i=n(o),i.size===0)return!1}return n(i).has(e.length)}}var vp=".comet/check-policy.json",PS=["argv","cwd","files","outputs","env","git","taskCheckboxes"];function AS(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);let n=t;if(Object.keys(n).some(s=>!PS.includes(s)))throw new Error(`${e} has unknown fields`);if(!Array.isArray(n.argv)||!n.argv.length||!n.argv[0]||n.argv.some(s=>typeof s!="string"||s.includes("\0")))throw new Error(`${e} argv must bind literal command arguments`);if(typeof n.cwd!="string"||!n.cwd)throw new Error(`${e} cwd must bind a project-relative directory`);let r=n.cwd==="."?".":de(n.cwd,`${e} cwd`),i={argv:[...n.argv],cwd:r,git:"none",taskCheckboxes:"ignore"};for(let s of["files","outputs","env"])if(n[s]!==void 0&&(!Array.isArray(n[s])||n[s].some(o=>typeof o!="string"||!o)))throw new Error(`${e} ${s} must be an array of nonempty strings`);if(n.files!==void 0&&(i.files=[...new Set(n.files.map(s=>Hn(s)?xr(s,`${e} file`):de(s,`${e} file`)))].sort((s,o)=>s.localeCompare(o,"en"))),n.outputs!==void 0&&(i.outputs=[...new Set(n.outputs.map(s=>Hn(s)?xr(s,`${e} output`):de(s,`${e} output`)))].sort((s,o)=>s.localeCompare(o,"en"))),n.env!==void 0){if(n.env.some(s=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s)))throw new Error(`${e} has an invalid environment variable name`);i.env=[...new Set(n.env)].sort((s,o)=>s.localeCompare(o,"en"))}if(n.git!==void 0){if(!["all","none"].includes(n.git))throw new Error(`${e} has an invalid git binding`);i.git=n.git}if(n.taskCheckboxes!==void 0){if(!["include","ignore"].includes(n.taskCheckboxes))throw new Error(`${e} has an invalid taskCheckboxes mode`);i.taskCheckboxes=n.taskCheckboxes}return i}function OS(t){return bp("sha256").update(JSON.stringify({argv:t.argv,cwd:t.cwd,files:t.files??null,outputs:t.outputs??null,env:t.env??null,git:t.git,taskCheckboxes:t.taskCheckboxes})).digest("hex")}function kp(t,e){return e.cwd===t.cwd&&JSON.stringify(e.argv)===JSON.stringify(t.argv)}async function tt(t,e,n=!1){let r=n?{digest:"",git:"all",taskCheckboxes:"include"}:{digest:"",git:"none",taskCheckboxes:"ignore"};if(!await G(t,vp,{label:"Classic check policy",expected:"file"}))return r;let i=await I(t,vp,{label:"Classic check policy"});try{let s=JSON.parse(i);if(!s||Array.isArray(s))throw new Error("Expected a policy object");let o=bp("sha256").update(i).digest("hex");if(s.version===2){if(Object.keys(s).some(p=>p!=="version"&&p!=="commands"))throw new Error("version 2 allows only version and commands");if(!Array.isArray(s.commands)||!s.commands.length)throw new Error("commands must be a nonempty array");let u=s.commands.map((p,g)=>AS(p,`Classic check policy commands[${g}]`));if(new Set(u.map(p=>JSON.stringify([p.argv,p.cwd]))).size!==u.length)throw new Error("commands must not repeat an argv and cwd pair");if(!e||!u.some(p=>kp(p,e)))return{...r,digest:o};let f=u.find(p=>kp(p,e));return{digest:o,entryDigest:OS(f),declaredCwd:f.cwd,files:f.files,outputs:f.outputs,env:f.env,git:f.git,taskCheckboxes:f.taskCheckboxes}}if(s.version!==1||Object.keys(s).some(u=>!["version","argv","cwd","files","outputs","env","git","taskCheckboxes"].includes(u)))throw new Error("Expected version 1 or 2 with known fields");if(!Array.isArray(s.argv)||!s.argv.length||!s.argv[0]||s.argv.some(u=>typeof u!="string"||u.includes("\0")))throw new Error("argv must bind literal command arguments");if(typeof s.cwd!="string"||!s.cwd)throw new Error("cwd must bind a project-relative directory");let a=s.cwd==="."?".":de(s.cwd,"Classic check policy cwd");for(let u of["files","outputs","env"])if(s[u]!==void 0&&(!Array.isArray(s[u])||s[u].some(d=>typeof d!="string"||!d)))throw new Error(`${u} must be an array of nonempty strings`);let c=s.files?.map(u=>{if(/[?*[\]{}]/.test(u))throw new Error("files accepts literal paths, not globs");return de(u,"Classic check policy file")}),l=s.outputs?.map(u=>{if(/[?*[\]{}]/u.test(u))throw new Error("outputs accepts literal paths, not globs");return de(u,"Classic check policy output")});if(s.env?.some(u=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(u)))throw new Error("Invalid environment variable name");if(s.git!==void 0&&!["all","none"].includes(s.git))throw new Error("Invalid git binding");if(s.taskCheckboxes!==void 0&&!["include","ignore"].includes(s.taskCheckboxes))throw new Error("Invalid taskCheckboxes mode");return!e||e.cwd!==a||JSON.stringify(e.argv)!==JSON.stringify(s.argv)?{...r,digest:o}:{digest:o,files:c,outputs:l,env:s.env,git:s.git??r.git,taskCheckboxes:s.taskCheckboxes??r.taskCheckboxes}}catch(s){throw new Error(`Invalid Classic check policy: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}function mt(t,e){let n=NS("git",["-C",t,...e],{encoding:"utf8",windowsHide:!0,timeout:3e4,maxBuffer:268435456});return n.status===0?n.stdout:null}function Xr(t,e){return e?t?.digest??"":t?.entryDigest??t?.digest??""}var Cp=new Map;async function jS(t,e){let n=`${t}\0${e}`,r=Cp.get(n);if(r!==void 0)return r;let i=process.platform==="win32"?ln(t,process.env,e):t.includes("/")?F.resolve(e,t):(await Promise.all((process.env.PATH??"").split(F.delimiter).map(async s=>{let o=F.resolve(e,s,t);return await ze.access(o,ze.constants.X_OK).then(()=>o,()=>null)}))).find(s=>s!==null)??null;return Cp.set(n,i),i}async function Qr(t,e,n,r=!1){let i=await jS(t[0],e),s=i?await ze.realpath(i).catch(()=>null):null,o=s?await ze.stat(s):null,a=n?.env;return zc("sha256").update(JSON.stringify([process.platform,process.arch,process.execPath,process.version,t,e,s,o&&[o.size,o.mtimeMs,o.ctimeMs,o.ino],Object.entries(process.env).filter(([c])=>a?a.some(l=>process.platform==="win32"?l.toLowerCase()===c.toLowerCase():l===c):r).sort(([c],[l])=>c.localeCompare(l)),...Xr(n,r)?[Xr(n,r)]:[]])).digest("hex")}async function Zr(t,e,n,r={}){t=F.resolve(t),e=F.resolve(e);let i=r.legacy===!0,s=zc("sha256"),o=await tt(t,n,i);s.update(Xr(o,i));let a=[],c=r.contentCache??new Map,u=(await V(e,{migrate:!1})).classic?.verificationReport,d=u&&u.endsWith(".md")?F.resolve(t,u):null,f=(o.outputs??[]).map(w=>Hc(w)),p=[t,await ze.realpath(t).catch(()=>t)],g=(w,C=t)=>{let k=F.relative(C,w);return k===""||k!==".."&&!k.startsWith(`..${F.sep}`)&&!F.isAbsolute(k)},m=[process.env.HOME,process.env.USERPROFILE].filter(w=>!!w),h=[...new Set((await Promise.all(m.map(async w=>{let C=F.resolve(w);return[C,await ze.realpath(C).catch(()=>C)]}))).flat())].filter(w=>p.some(C=>w!==C&&g(w,C))),v=w=>f.some(C=>C(F.relative(t,w).replaceAll("\\","/")))||h.some(C=>w===C||w.startsWith(C+F.sep))||w===F.join(e,".comet.yaml")||w===F.join(e,".comet-state.lock")||w===F.join(e,".comet-state-transaction.json")||w.startsWith(F.join(e,".comet")+F.sep)||w===d||w===F.join(t,".comet","current-change.json"),y=w=>F.relative(t,w).replaceAll("\\","/")||".";async function S(w){let C=[];async function k(_){let O=_===w||await ze.lstat(F.join(_,".git")).then(()=>!0,()=>!1)?mt(_,["ls-files","-z","--cached","--others","--exclude-standard"]):null,R=F.relative(w,_).replaceAll("\\","/");if(O!==null){for(let $ of[...new Set(O.split("\0").filter(Boolean))].sort())C.push(R?`${R}/${$}`:$);return}for(let $ of(await ze.readdir(_,{withFileTypes:!0})).sort((B,L)=>B.name.localeCompare(L.name))){if($.name===".git"||$.name==="node_modules")continue;let B=R?`${R}/${$.name}`:$.name;$.isDirectory()?await k(F.join(_,$.name)):C.push(B)}}return await k(w),C}async function b(w,C){if(v(w))return;let k=F.relative(t,w).replaceAll("\\","/"),_=await ze.lstat(w,{bigint:!0}).catch($=>{if($.code==="ENOENT")return null;throw $});if(s.update(JSON.stringify([k,_?_.isFile()?Number(_.size):null:"missing"])),!_){a.push({p:k,h:"missing",s:null,m:null}),await fe(t,w,{label:"Classic check input",expected:"any"});return}if(_.isSymbolicLink())throw new Error(`Check input is a symbolic link: ${k}. Symbolic links cannot be check inputs; either remove the link, or bind this command's inputs in .comet/check-policy.json (version 2) with a files list that excludes it`);if(_.isDirectory()){await fe(t,w,{label:"Classic check input",expected:"directory"}),await x(w);return}let P=`${k}|${_.size}|${_.mtimeNs}|${_.mode}`,O=o.taskCheckboxes==="ignore"&&w===F.join(e,"tasks.md"),R=i?void 0:O?c.get(P):C??c.get(P);if(R===void 0)if(!i&&!O)R=(await df(t,k,{label:"Classic check input"})).digest;else{let $=await ps(t,w,{label:"Classic check input",maxBytes:Number.MAX_SAFE_INTEGER}),B=$;if(O)try{B=Buffer.from($r($.toString("utf8")),"utf8")}catch{B=$}i?s.update(B):R=zc("sha256").update(B).digest("hex")}R!==void 0&&(c.set(P,R),i||s.update(R)),a.push({p:k,h:R,s:Number(_.size),m:_.mtimeNs.toString()})}async function x(w){let k=w===t||await ze.lstat(F.join(w,".git")).then(()=>!0,()=>!1)?mt(w,["ls-files","-z","--cached","--others","--exclude-standard"]):null;if(k!==null){if(o.git==="all"){let L=mt(w,["rev-parse","HEAD"])??"unborn";s.update(L),a.push({p:`\0git:${y(w)}:head`,h:L.trim(),s:null,m:null})}let _=o.git==="all"?mt(w,["ls-files","--stage","-z"]):"",P=o.git==="all"?_:mt(w,["ls-files","--stage","-z"]);if(P===null)throw new Error("Cannot inspect check input index");if(o.git==="all")for(let L of P.split("\0").filter(Boolean)){let U=L.slice(L.indexOf(" ")+1);v(F.resolve(w,U))||(s.update(L),a.push({p:`\0git:${y(w)}:index:${U}`,h:L.slice(0,L.indexOf(" ")).split(" ")[1],s:null,m:null}))}let O=[...new Set(k.split("\0").filter(Boolean))].sort(),R=new Map(P.split("\0").filter(Boolean).map(L=>{let U=L.indexOf(" "),Z=L.slice(0,U).split(" ");return[L.slice(U+1),Z[1]??""]})),$=mt(w,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none"]),B=new Set;if($!==null){let L=$.split("\0");for(let U=0;U<L.length;U+=1){let Z=L[U];if(!(Z.length<4)&&(B.add(Z.slice(3)),/^[RC]/u.test(Z.slice(0,1))||/[RC]$/u.test(Z.slice(1,2)))){let ne=L[U+1];ne&&(B.add(ne),U+=1)}}}for(let L of O){let U=R.get(L),Z=U&&!B.has(L)?U:mt(w,["hash-object","--no-filters","--",L])?.trim()??void 0;await b(F.resolve(w,L),Z?`git:${Z}`:void 0)}return}for(let _ of(await ze.readdir(w,{withFileTypes:!0})).sort((P,O)=>P.name.localeCompare(O.name)))_.name===".git"||_.name==="node_modules"||await b(F.join(w,_.name))}if(o.files){if(o.git==="all"){let C=mt(t,["rev-parse","HEAD"])??"unborn";s.update(C),a.push({p:"\0git:.:head",h:C.trim(),s:null,m:null});let k=mt(t,["ls-files","--stage","-z"]);if(k!==null)for(let _ of k.split("\0").filter(Boolean))v(F.resolve(t,_.slice(_.indexOf(" ")+1)))||(s.update(_),a.push({p:`\0git:.:index:${_.slice(_.indexOf(" ")+1)}`,h:_.slice(0,_.indexOf(" ")).split(" ")[1],s:null,m:null}))}let w=o.files.filter(C=>Hn(C)).map(C=>Hc(C));if(w.length){let C=new Set(o.files.filter(P=>!Hn(P))),k=new Set,_=await S(t);for(let P of _){let O=F.resolve(t,P);v(O)||(C.has(P)||w.some(R=>R(P)))&&k.add(P)}for(let P of[...C].sort())await b(F.resolve(t,P));for(let P of[...k].sort())await b(F.resolve(t,P))}else for(let C of[...new Set(o.files)].sort())await b(F.resolve(t,C));await b(F.join(t,".comet","config.yaml"))}else await x(t);if(Xr(await tt(t,n,i),i)!==Xr(o,i))throw new Error("Classic check policy changed during snapshot");for(let w of["node_modules/.package-lock.json","node_modules/.modules.yaml","node_modules/.pnpm/lock.yaml"])await b(F.join(t,w));return{digest:s.digest("hex"),entries:a,manifest:wp(a)}}async function Jc(t,e,n){return(await Zr(t,e,n,{legacy:!0})).digest}import{promises as IS}from"node:fs";le();var kn=new Map,$S=16;async function Sp(t,e){let n=await J(t,e,{label:"Classic check trajectory",expected:"file"});if(!n.exists)return{target:n.target,stamp:"missing",cacheable:!1};let r=await IS.lstat(n.target,{bigint:!0});if(!r.isFile()||r.isSymbolicLink())throw new Error("Classic check trajectory changed");return{target:n.target,cacheable:r.ino!==0n&&r.ctimeNs>0n,stamp:[r.dev,r.ino,r.birthtimeNs,r.ctimeNs,r.mtimeNs,r.size].join(":")}}async function zn(t,e){for(let n=0;n<3;n++){let r=await Sp(t,e),i=kn.get(r.target),s;if(r.cacheable&&i?.stamp===r.stamp)s=i.index;else{let a=await gn(t,e);if(a.some(c=>!c||typeof c.type!="string"||!Number.isSafeInteger(c.sequence)||c.sequence<0))throw new Error("Invalid Trajectory event in Classic check index");s={maximumSequence:a.reduce((c,l)=>Math.max(c,l.sequence),0),events:a.filter(c=>c.type.startsWith("command_check"))}}let o=await Sp(t,e);if(r.stamp!==o.stamp){kn.delete(r.target);continue}return kn.delete(r.target),kn.size>=$S&&kn.delete(kn.keys().next().value),kn.set(r.target,{stamp:r.stamp,index:s}),structuredClone(s)}throw new Error("Classic check trajectory changed during index read")}var TS=new Set([".md",".markdown"]),LS=new Set([".md",".markdown",".rst",".txt"]),qS=new Set(["docs","doc","documentation",".github"]),MS=[/^LICENSE(?:[.-]|$)/u,/^NOTICE$/u,/^AUTHORS$/u];function Ep(t){return t.replaceAll("\\","/").replace(/^\.\//u,"")}function FS(t,e){for(let n of e){let r=Ep(n).replace(/\/+$/u,"");if(r&&(t===r||t.startsWith(`${r}/`)))return!0}return!1}function xp(t,e=[]){let n=Ep(t);if(!n||n.endsWith("/")||FS(n,e))return!1;let r=n.split("/"),i=r[r.length-1],s=i.lastIndexOf("."),o=s===-1?"":i.slice(s).toLowerCase();return r.length===1?TS.has(o)||MS.some(a=>a.test(i)):qS.has(r[0])&&LS.has(o)}kc();$t();import DS from"os";import Xs from"path";function WS(t={}){let e=t.cwd??process.cwd(),n=t.homeDir??DS.homedir(),r=[{file:Xs.resolve(e,".comet","config.yaml"),source:".comet/config.yaml",scope:"project"},{file:Xs.resolve(n,".comet","config.yaml"),source:"~/.comet/config.yaml",scope:"global"}];return r.filter((i,s)=>r.findIndex(o=>o.file===i.file)===s)}async function Qs(t,e={}){for(let n of WS(e)){let r=Xs.dirname(Xs.dirname(n.file)),i=n.scope==="global"?(await vc(r))?.classic:(await ct(r,{allowPartialProject:!0}))?.value.classic;if(!i||typeof i!="object"||Array.isArray(i))continue;let s=i[t];if(s!=null)return{value:String(s),source:n.source}}return null}async function _p(t){let e=await Qs("document_evidence",{cwd:t});if(!e)return"neutral";if(e.value==="neutral"||e.value==="strict")return e.value;throw new Error(`classic.document_evidence must be neutral or strict, got '${e.value}' (${e.source})`)}function BS(t,e){return[K(t,e.openSpecRoot),K(t,e.superpowersRoot)]}async function Rp(t,e){let n;try{let s=await ic(t);n=BS(t,s)}catch{n=["openspec","docs/openspec","docs/superpowers"]}let r=[],i=[];for(let s of e)xp(s,n)?i.push(s):r.push(s);return{material:r,neutral:i}}function Yc(t){if(t!=="build"&&t!=="verify")throw new Error(`Invalid command check scope: '${String(t)}'`)}function eo(t,e="."){if(e.trim().length===0)throw new Error("Command check cwd cannot be blank");let n=ke.resolve(t),r=ke.resolve(n,e);if(r!==n&&!r.startsWith(n+ke.sep))throw new Error(`Command check cwd must resolve within the project root: '${e}'`);return ke.relative(n,r).replaceAll("\\","/")||"."}function Np(t,e){if(e.type!=="command_check_recorded"&&e.type!=="command_check_executed")return null;let n=e.data;if(typeof n!="object"||n===null||Array.isArray(n))return null;let{scope:r,command:i,exitCode:s,cwd:o}=n;if(r!=="build"&&r!=="verify"||typeof i!="string"||i.trim().length===0||!Number.isInteger(s)||typeof o!="string")return null;let a;try{a=eo(t,o)}catch{return null}return{sequence:e.sequence,timestamp:e.timestamp,runId:e.runId,scope:r,command:i,exitCode:s,cwd:a,...e.type==="command_check_executed"?{provenance:"runtime",argv:n.argv,timeoutMs:typeof n.timeoutMs=="number"?n.timeoutMs:void 0,inputBefore:n.inputBefore,inputAfter:n.inputAfter,changedDuringExecution:Array.isArray(n.changedDuringExecution)?n.changedDuringExecution?.filter(c=>typeof c=="string"):void 0,environment:n.environment,logRef:n.logRef,logHash:n.logHash,logSize:typeof n.logSize=="number"?n.logSize:void 0,logMtimeNs:typeof n.logMtimeNs=="string"?n.logMtimeNs:void 0,manifestRef:typeof n.manifestRef=="string"?n.manifestRef:void 0,manifestHash:typeof n.manifestHash=="string"?n.manifestHash:void 0,tier:n.tier==="incremental"?"incremental":void 0,reusable:n.reusable,checkEpoch:n.checkEpoch}:{}}}async function ei(t,e,n,r){Yc(r);let i=(await zn(e,n.trajectoryRef)).events;for(let s=i.length-1;s>=0;s-=1){let o=i[s];if(o.runId!==n.runId)continue;if(o.type==="command_checks_invalidated"&&(!Array.isArray(o.data?.scopes)||o.data.scopes.includes(r))||o.type==="command_check_started"&&o.data?.scope===r||o.type==="command_check_consumed"&&o.data?.scope===r)return null;let a=Np(t,o);if(a?.scope===r)return a}return null}function US(t,e){if(e.type!=="command_check_started")return null;let n=e.data;if(typeof n!="object"||n===null||Array.isArray(n))return null;let{scope:r,argv:i,cwd:s,timeoutMs:o,reusable:a,tier:c}=n;if(r!=="build"&&r!=="verify"||!Array.isArray(i)||i.length===0||i.some(u=>typeof u!="string"||u.includes("\0"))||typeof s!="string"||!Number.isInteger(o)||Number(o)<1||typeof a!="boolean"||c!=="full"&&c!=="incremental")return null;let l;try{l=eo(t,s)}catch{return null}return{sequence:e.sequence,timestamp:e.timestamp,runId:e.runId,scope:r,argv:[...i],cwd:l,timeoutMs:Number(o),reusable:a,tier:c}}async function jp(t,e,n,r){Yc(r);let i=(await zn(e,n.trajectoryRef)).events;for(let s=i.length-1;s>=0;s-=1){let o=i[s];if(o.runId!==n.runId||!(o.data?.scope===r||Array.isArray(o.data?.scopes)&&o.data.scopes.includes(r)))continue;if(o.type==="command_check_started")return US(t,o);let c=Np(t,o);if(c?.scope===r&&c.provenance==="runtime"&&c.argv?.length)return{sequence:c.sequence,timestamp:c.timestamp,runId:c.runId,scope:c.scope,argv:[...c.argv],cwd:c.cwd,timeoutMs:c.timeoutMs??3e5,reusable:c.reusable===!0,tier:c.tier??"full"};if(o.type!=="command_checks_invalidated")return null}return null}async function KS(t,e,n){let r=(await zn(t,e.trajectoryRef)).events;for(let i=r.length-1;i>=0;i-=1){let s=r[i];if(!(s.runId!==e.runId||!(s.data?.scope===n||Array.isArray(s.data?.scopes)&&s.data.scopes.includes(n))))return s.type==="command_check_started"?`a previous ${n} check attempt started at ${s.timestamp} never completed (interrupted or failed during launch); rerun the check`:null}return null}async function Gc(t,e,n,r){return me(t,async()=>{let s={sequence:(await zn(t,e.trajectoryRef)).maximumSequence+1,timestamp:new Date().toISOString(),runId:e.runId,type:n,data:r};return await Bt(t,e.trajectoryRef,s),s})}async function Ip(t,e,n,r){if(Yc(r.scope),!r.argv.length||r.argv.some(P=>typeof P!="string"||P.includes("\0")))throw new Error("Check requires literal program arguments");let i=eo(t,r.cwd),s=await Zs.realpath(t);eo(s,await Zs.realpath(ke.resolve(t,i)));let o=r.tier==="incremental"?"incremental":"full",a=await ei(t,e,n,r.scope);if(r.reusable){if(a&&a.reusable&&(a.tier??"full")===o&&a.cwd===i&&JSON.stringify(a.argv)===JSON.stringify(r.argv)){let P=await Ap(t,e,n,r.scope);if(P?.sequence===a.sequence&&P.timestamp===a.timestamp)return{...P,reused:!0}}if(!a){let P=r.scope==="build"?"verify":"build",O=await Ap(t,e,n,P);if(O?.reusable&&(O.tier??"full")===o&&O.cwd===i&&JSON.stringify(O.argv)===JSON.stringify(r.argv)){let{sequence:R,timestamp:$,runId:B,scope:L,reused:U,...Z}=O,ne=(await V(e,{migrate:!1})).classic?.checkEpoch??0,Vt=await Gc(e,n,"command_check_executed",{...Z,scope:r.scope,checkEpoch:ne});return{...Z,scope:r.scope,checkEpoch:ne,sequence:Vt.sequence,timestamp:Vt.timestamp,runId:n.runId,reused:!0}}}}let c=r.timeoutMs??3e5,l=await Gc(e,n,"command_check_started",{scope:r.scope,argv:[...r.argv],cwd:i,timeoutMs:c,reusable:r.reusable===!0,tier:o}),u=(await V(e,{migrate:!1})).classic?.checkEpoch??0,d={argv:r.argv,cwd:i},f=a?.manifestRef?await $p(t,a).catch(()=>null):null,p=await Zr(t,e,d,f?{baseline:f}:{}),g=p.digest,m=await Qr(r.argv,ke.resolve(t,i),await tt(t,d)),h=ke.join(e,".comet","checks",`${Pp()}.log`),v=await new Promise(P=>{let O=Ef(r.argv[0],r.argv.slice(1),{cwd:ke.resolve(t,i)}),R="",$=!1,B=U=>{R=(R+U.toString()).slice(-2*1024*1024)};O.stdout.on("data",B),O.stderr.on("data",B),O.on("error",U=>{R+=`
|
|
170
|
-
${
|
|
171
|
-
`:"")+R})})}),y=await Zr(t,e,d,{baseline:p.entries}).catch(()=>null),S=y?y.digest:"unavailable",b=y?(()=>{let P=Kc(p.entries,y.entries);return[...P.added,...P.removed,...P.changed].slice(0,100)})():void 0,x,w;if(y){let P=
|
|
172
|
-
`,
|
|
169
|
+
`)){if(!n)continue;let r=JSON.parse(n);if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid check manifest entry");let{p:i,h:s,s:o,m:a}=r;if(typeof i!="string"||!i||typeof s!="string"||!s)throw new Error("Invalid check manifest entry");if(o!==null&&typeof o!="number")throw new Error("Invalid check manifest entry");if(a!==null&&typeof a!="string")throw new Error("Invalid check manifest entry");e.push({p:i,h:s,s:o,m:a})}return e}function Kc(t,e){let n=new Map(t.map(s=>[s.p,s])),r=new Map(e.map(s=>[s.p,s])),i=s=>[...s].sort();return{added:i([...r.keys()].filter(s=>!n.has(s))),removed:i([...n.keys()].filter(s=>!r.has(s))),changed:i([...n.keys()].filter(s=>r.has(s)&&n.get(s).h!==r.get(s).h))}}function Hn(t){return/[*?]/u.test(t)}function Hc(t){let e=[];for(let r=0;r<t.length;r+=1){let i=t[r];i==="*"&&t[r+1]==="*"?(r+=1,t[r+1]==="/"?(r+=1,e.push({kind:"globstar-slash"})):e.push({kind:"globstar"})):i==="*"?e.push({kind:"star"}):i==="?"?e.push({kind:"question"}):e.push({kind:"literal",value:i})}let n=r=>{let i=new Set(r),s=[...r];for(;s.length>0;){let o=s.pop(),a=e[o];a&&(a.kind==="star"||a.kind==="globstar"||a.kind==="globstar-slash")&&!i.has(o+1)&&(i.add(o+1),s.push(o+1))}return i};return r=>{let i=n(new Set([0]));for(let s of r){let o=new Set;for(let a of i){let c=e[a];c&&(c.kind==="literal"&&c.value===s||c.kind==="question"&&s!=="/"?o.add(a+1):c.kind==="star"&&s!=="/"||c.kind==="globstar"?o.add(a):c.kind==="globstar-slash"&&(o.add(a),s==="/"&&o.add(a+1)))}if(i=n(o),i.size===0)return!1}return n(i).has(e.length)}}var vp=".comet/check-policy.json",PS=["argv","cwd","files","outputs","env","git","taskCheckboxes"];function AS(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);let n=t;if(Object.keys(n).some(s=>!PS.includes(s)))throw new Error(`${e} has unknown fields`);if(!Array.isArray(n.argv)||!n.argv.length||!n.argv[0]||n.argv.some(s=>typeof s!="string"||s.includes("\0")))throw new Error(`${e} argv must bind literal command arguments`);if(typeof n.cwd!="string"||!n.cwd)throw new Error(`${e} cwd must bind a project-relative directory`);let r=n.cwd==="."?".":fe(n.cwd,`${e} cwd`),i={argv:[...n.argv],cwd:r,git:"none",taskCheckboxes:"ignore"};for(let s of["files","outputs","env"])if(n[s]!==void 0&&(!Array.isArray(n[s])||n[s].some(o=>typeof o!="string"||!o)))throw new Error(`${e} ${s} must be an array of nonempty strings`);if(n.files!==void 0&&(i.files=[...new Set(n.files.map(s=>Hn(s)?xr(s,`${e} file`):fe(s,`${e} file`)))].sort((s,o)=>s.localeCompare(o,"en"))),n.outputs!==void 0&&(i.outputs=[...new Set(n.outputs.map(s=>Hn(s)?xr(s,`${e} output`):fe(s,`${e} output`)))].sort((s,o)=>s.localeCompare(o,"en"))),n.env!==void 0){if(n.env.some(s=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s)))throw new Error(`${e} has an invalid environment variable name`);i.env=[...new Set(n.env)].sort((s,o)=>s.localeCompare(o,"en"))}if(n.git!==void 0){if(!["all","none"].includes(n.git))throw new Error(`${e} has an invalid git binding`);i.git=n.git}if(n.taskCheckboxes!==void 0){if(!["include","ignore"].includes(n.taskCheckboxes))throw new Error(`${e} has an invalid taskCheckboxes mode`);i.taskCheckboxes=n.taskCheckboxes}return i}function OS(t){return bp("sha256").update(JSON.stringify({argv:t.argv,cwd:t.cwd,files:t.files??null,outputs:t.outputs??null,env:t.env??null,git:t.git,taskCheckboxes:t.taskCheckboxes})).digest("hex")}function kp(t,e){return e.cwd===t.cwd&&JSON.stringify(e.argv)===JSON.stringify(t.argv)}async function nt(t,e,n=!1){let r=n?{digest:"",git:"all",taskCheckboxes:"include"}:{digest:"",git:"none",taskCheckboxes:"ignore"};if(!await G(t,vp,{label:"Classic check policy",expected:"file"}))return r;let i=await I(t,vp,{label:"Classic check policy"});try{let s=JSON.parse(i);if(!s||Array.isArray(s))throw new Error("Expected a policy object");let o=bp("sha256").update(i).digest("hex");if(s.version===2){if(Object.keys(s).some(p=>p!=="version"&&p!=="commands"))throw new Error("version 2 allows only version and commands");if(!Array.isArray(s.commands)||!s.commands.length)throw new Error("commands must be a nonempty array");let u=s.commands.map((p,g)=>AS(p,`Classic check policy commands[${g}]`));if(new Set(u.map(p=>JSON.stringify([p.argv,p.cwd]))).size!==u.length)throw new Error("commands must not repeat an argv and cwd pair");if(!e||!u.some(p=>kp(p,e)))return{...r,digest:o};let f=u.find(p=>kp(p,e));return{digest:o,entryDigest:OS(f),declaredCwd:f.cwd,files:f.files,outputs:f.outputs,env:f.env,git:f.git,taskCheckboxes:f.taskCheckboxes}}if(s.version!==1||Object.keys(s).some(u=>!["version","argv","cwd","files","outputs","env","git","taskCheckboxes"].includes(u)))throw new Error("Expected version 1 or 2 with known fields");if(!Array.isArray(s.argv)||!s.argv.length||!s.argv[0]||s.argv.some(u=>typeof u!="string"||u.includes("\0")))throw new Error("argv must bind literal command arguments");if(typeof s.cwd!="string"||!s.cwd)throw new Error("cwd must bind a project-relative directory");let a=s.cwd==="."?".":fe(s.cwd,"Classic check policy cwd");for(let u of["files","outputs","env"])if(s[u]!==void 0&&(!Array.isArray(s[u])||s[u].some(d=>typeof d!="string"||!d)))throw new Error(`${u} must be an array of nonempty strings`);let c=s.files?.map(u=>{if(/[?*[\]{}]/.test(u))throw new Error("files accepts literal paths, not globs");return fe(u,"Classic check policy file")}),l=s.outputs?.map(u=>{if(/[?*[\]{}]/u.test(u))throw new Error("outputs accepts literal paths, not globs");return fe(u,"Classic check policy output")});if(s.env?.some(u=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(u)))throw new Error("Invalid environment variable name");if(s.git!==void 0&&!["all","none"].includes(s.git))throw new Error("Invalid git binding");if(s.taskCheckboxes!==void 0&&!["include","ignore"].includes(s.taskCheckboxes))throw new Error("Invalid taskCheckboxes mode");return!e||e.cwd!==a||JSON.stringify(e.argv)!==JSON.stringify(s.argv)?{...r,digest:o}:{digest:o,files:c,outputs:l,env:s.env,git:s.git??r.git,taskCheckboxes:s.taskCheckboxes??r.taskCheckboxes}}catch(s){throw new Error(`Invalid Classic check policy: ${s instanceof Error?s.message:String(s)}`,{cause:s})}}function rt(t,e){let n=NS("git",["-C",t,...e],{encoding:"utf8",windowsHide:!0,timeout:3e4,maxBuffer:268435456});return n.status===0?n.stdout:null}function jS(t,e){let n=new Map,r=32;for(let i=0;i<e.length;i+=r){let s=e.slice(i,i+r),o=rt(t,["hash-object","--no-filters","--",...s]);if(o===null)return null;let a=o.trimEnd().split(/\r?\n/u);if(a.length!==s.length||a.some(c=>!/^[0-9a-f]+$/iu.test(c)))return null;s.forEach((c,l)=>n.set(c,a[l]))}return n}function Xr(t,e){return e?t?.digest??"":t?.entryDigest??t?.digest??""}var Cp=new Map;async function IS(t,e){let n=`${t}\0${e}`,r=Cp.get(n);if(r!==void 0)return r;let i=process.platform==="win32"?ln(t,process.env,e):t.includes("/")?F.resolve(e,t):(await Promise.all((process.env.PATH??"").split(F.delimiter).map(async s=>{let o=F.resolve(e,s,t);return await Je.access(o,Je.constants.X_OK).then(()=>o,()=>null)}))).find(s=>s!==null)??null;return Cp.set(n,i),i}async function Qr(t,e,n,r=!1){let i=await IS(t[0],e),s=i?await Je.realpath(i).catch(()=>null):null,o=s?await Je.stat(s):null,a=n?.env;return zc("sha256").update(JSON.stringify([process.platform,process.arch,process.execPath,process.version,t,e,s,o&&[o.size,o.mtimeMs,o.ctimeMs,o.ino],Object.entries(process.env).filter(([c])=>a?a.some(l=>process.platform==="win32"?l.toLowerCase()===c.toLowerCase():l===c):r).sort(([c],[l])=>c.localeCompare(l)),...Xr(n,r)?[Xr(n,r)]:[]])).digest("hex")}async function Zr(t,e,n,r={}){t=F.resolve(t),e=F.resolve(e);let i=r.legacy===!0,s=zc("sha256"),o=await nt(t,n,i);s.update(Xr(o,i));let a=[],c=r.contentCache??new Map,u=(await V(e,{migrate:!1})).classic?.verificationReport,d=u&&u.endsWith(".md")?F.resolve(t,u):null,f=(o.outputs??[]).map(w=>Hc(w)),p=[t,await Je.realpath(t).catch(()=>t)],g=(w,C=t)=>{let k=F.relative(C,w);return k===""||k!==".."&&!k.startsWith(`..${F.sep}`)&&!F.isAbsolute(k)},m=[process.env.HOME,process.env.USERPROFILE].filter(w=>!!w),h=[...new Set((await Promise.all(m.map(async w=>{let C=F.resolve(w);return[C,await Je.realpath(C).catch(()=>C)]}))).flat())].filter(w=>p.some(C=>w!==C&&g(w,C))),v=w=>f.some(C=>C(F.relative(t,w).replaceAll("\\","/")))||h.some(C=>w===C||w.startsWith(C+F.sep))||w===F.join(e,".comet.yaml")||w===F.join(e,".comet-state.lock")||w===F.join(e,".comet-state-transaction.json")||w.startsWith(F.join(e,".comet")+F.sep)||w===d||w===F.join(t,".comet","current-change.json"),y=w=>F.relative(t,w).replaceAll("\\","/")||".";async function S(w){let C=[];async function k(_){let O=_===w||await Je.lstat(F.join(_,".git")).then(()=>!0,()=>!1)?rt(_,["ls-files","-z","--cached","--others","--exclude-standard"]):null,R=F.relative(w,_).replaceAll("\\","/");if(O!==null){for(let $ of[...new Set(O.split("\0").filter(Boolean))].sort())C.push(R?`${R}/${$}`:$);return}for(let $ of(await Je.readdir(_,{withFileTypes:!0})).sort((U,se)=>U.name.localeCompare(se.name))){if($.name===".git"||$.name==="node_modules")continue;let U=R?`${R}/${$.name}`:$.name;$.isDirectory()?await k(F.join(_,$.name)):C.push(U)}}return await k(w),C}async function b(w,C){if(v(w))return;let k=F.relative(t,w).replaceAll("\\","/"),_=await Je.lstat(w,{bigint:!0}).catch($=>{if($.code==="ENOENT")return null;throw $});if(s.update(JSON.stringify([k,_?_.isFile()?Number(_.size):null:"missing"])),!_){a.push({p:k,h:"missing",s:null,m:null}),await me(t,w,{label:"Classic check input",expected:"any"});return}if(_.isSymbolicLink())throw new Error(`Check input is a symbolic link: ${k}. Symbolic links cannot be check inputs; either remove the link, or bind this command's inputs in .comet/check-policy.json (version 2) with a files list that excludes it`);if(_.isDirectory()){await me(t,w,{label:"Classic check input",expected:"directory"}),await x(w);return}let P=`${k}|${_.size}|${_.mtimeNs}|${_.mode}`,O=o.taskCheckboxes==="ignore"&&w===F.join(e,"tasks.md"),R=i?void 0:O?c.get(P):C??c.get(P);if(R===void 0)if(!i&&!O)R=(await df(t,k,{label:"Classic check input"})).digest;else{let $=await ps(t,w,{label:"Classic check input",maxBytes:Number.MAX_SAFE_INTEGER}),U=$;if(O)try{U=Buffer.from($r($.toString("utf8")),"utf8")}catch{U=$}i?s.update(U):R=zc("sha256").update(U).digest("hex")}R!==void 0&&(c.set(P,R),i||s.update(R)),a.push({p:k,h:R,s:Number(_.size),m:_.mtimeNs.toString()})}async function x(w){let k=w===t||await Je.lstat(F.join(w,".git")).then(()=>!0,()=>!1)?rt(w,["ls-files","-z","--cached","--others","--exclude-standard"]):null;if(k!==null){if(o.git==="all"){let q=rt(w,["rev-parse","HEAD"])??"unborn";s.update(q),a.push({p:`\0git:${y(w)}:head`,h:q.trim(),s:null,m:null})}let _=o.git==="all"?rt(w,["ls-files","--stage","-z"]):"",P=o.git==="all"?_:rt(w,["ls-files","--stage","-z"]);if(P===null)throw new Error("Cannot inspect check input index");if(o.git==="all")for(let q of P.split("\0").filter(Boolean)){let W=q.slice(q.indexOf(" ")+1);v(F.resolve(w,W))||(s.update(q),a.push({p:`\0git:${y(w)}:index:${W}`,h:q.slice(0,q.indexOf(" ")).split(" ")[1],s:null,m:null}))}let O=[...new Set(k.split("\0").filter(Boolean))].sort(),R=new Map(P.split("\0").filter(Boolean).map(q=>{let W=q.indexOf(" "),oe=q.slice(0,W).split(" ");return[q.slice(W+1),oe[1]??""]})),$=rt(w,["status","--porcelain=v1","-z","--untracked-files=all","--ignore-submodules=none"]),U=new Set;if($!==null){let q=$.split("\0");for(let W=0;W<q.length;W+=1){let oe=q[W];if(!(oe.length<4)&&(U.add(oe.slice(3)),/^[RC]/u.test(oe.slice(0,1))||/[RC]$/u.test(oe.slice(1,2)))){let Ce=q[W+1];Ce&&(U.add(Ce),W+=1)}}}let se=O.filter(q=>!R.has(q)||U.has(q)),de=jS(w,se);for(let q of O){let W=R.get(q),oe=W&&!U.has(q)?W:de?.get(q)??(de===null?rt(w,["hash-object","--no-filters","--",q])?.trim()??void 0:void 0);await b(F.resolve(w,q),oe?`git:${oe}`:void 0)}return}for(let _ of(await Je.readdir(w,{withFileTypes:!0})).sort((P,O)=>P.name.localeCompare(O.name)))_.name===".git"||_.name==="node_modules"||await b(F.join(w,_.name))}if(o.files){if(o.git==="all"){let C=rt(t,["rev-parse","HEAD"])??"unborn";s.update(C),a.push({p:"\0git:.:head",h:C.trim(),s:null,m:null});let k=rt(t,["ls-files","--stage","-z"]);if(k!==null)for(let _ of k.split("\0").filter(Boolean))v(F.resolve(t,_.slice(_.indexOf(" ")+1)))||(s.update(_),a.push({p:`\0git:.:index:${_.slice(_.indexOf(" ")+1)}`,h:_.slice(0,_.indexOf(" ")).split(" ")[1],s:null,m:null}))}let w=o.files.filter(C=>Hn(C)).map(C=>Hc(C));if(w.length){let C=new Set(o.files.filter(P=>!Hn(P))),k=new Set,_=await S(t);for(let P of _){let O=F.resolve(t,P);v(O)||(C.has(P)||w.some(R=>R(P)))&&k.add(P)}for(let P of[...C].sort())await b(F.resolve(t,P));for(let P of[...k].sort())await b(F.resolve(t,P))}else for(let C of[...new Set(o.files)].sort())await b(F.resolve(t,C));await b(F.join(t,".comet","config.yaml"))}else await x(t);if(Xr(await nt(t,n,i),i)!==Xr(o,i))throw new Error("Classic check policy changed during snapshot");for(let w of["node_modules/.package-lock.json","node_modules/.modules.yaml","node_modules/.pnpm/lock.yaml"])await b(F.join(t,w));return{digest:s.digest("hex"),entries:a,manifest:wp(a)}}async function Jc(t,e,n){return(await Zr(t,e,n,{legacy:!0})).digest}import{promises as $S}from"node:fs";le();var kn=new Map,TS=16;async function Sp(t,e){let n=await J(t,e,{label:"Classic check trajectory",expected:"file"});if(!n.exists)return{target:n.target,stamp:"missing",cacheable:!1};let r=await $S.lstat(n.target,{bigint:!0});if(!r.isFile()||r.isSymbolicLink())throw new Error("Classic check trajectory changed");return{target:n.target,cacheable:r.ino!==0n&&r.ctimeNs>0n,stamp:[r.dev,r.ino,r.birthtimeNs,r.ctimeNs,r.mtimeNs,r.size].join(":")}}async function zn(t,e){for(let n=0;n<3;n++){let r=await Sp(t,e),i=kn.get(r.target),s;if(r.cacheable&&i?.stamp===r.stamp)s=i.index;else{let a=await gn(t,e);if(a.some(c=>!c||typeof c.type!="string"||!Number.isSafeInteger(c.sequence)||c.sequence<0))throw new Error("Invalid Trajectory event in Classic check index");s={maximumSequence:a.reduce((c,l)=>Math.max(c,l.sequence),0),events:a.filter(c=>c.type.startsWith("command_check"))}}let o=await Sp(t,e);if(r.stamp!==o.stamp){kn.delete(r.target);continue}return kn.delete(r.target),kn.size>=TS&&kn.delete(kn.keys().next().value),kn.set(r.target,{stamp:r.stamp,index:s}),structuredClone(s)}throw new Error("Classic check trajectory changed during index read")}var LS=new Set([".md",".markdown"]),qS=new Set([".md",".markdown",".rst",".txt"]),MS=new Set(["docs","doc","documentation",".github"]),FS=[/^LICENSE(?:[.-]|$)/u,/^NOTICE$/u,/^AUTHORS$/u];function Ep(t){return t.replaceAll("\\","/").replace(/^\.\//u,"")}function DS(t,e){for(let n of e){let r=Ep(n).replace(/\/+$/u,"");if(r&&(t===r||t.startsWith(`${r}/`)))return!0}return!1}function xp(t,e=[]){let n=Ep(t);if(!n||n.endsWith("/")||DS(n,e))return!1;let r=n.split("/"),i=r[r.length-1],s=i.lastIndexOf("."),o=s===-1?"":i.slice(s).toLowerCase();return r.length===1?LS.has(o)||FS.some(a=>a.test(i)):MS.has(r[0])&&qS.has(o)}kc();Tt();import WS from"os";import Xs from"path";function BS(t={}){let e=t.cwd??process.cwd(),n=t.homeDir??WS.homedir(),r=[{file:Xs.resolve(e,".comet","config.yaml"),source:".comet/config.yaml",scope:"project"},{file:Xs.resolve(n,".comet","config.yaml"),source:"~/.comet/config.yaml",scope:"global"}];return r.filter((i,s)=>r.findIndex(o=>o.file===i.file)===s)}async function Qs(t,e={}){for(let n of BS(e)){let r=Xs.dirname(Xs.dirname(n.file)),i=n.scope==="global"?(await vc(r))?.classic:(await ut(r,{allowPartialProject:!0}))?.value.classic;if(!i||typeof i!="object"||Array.isArray(i))continue;let s=i[t];if(s!=null)return{value:String(s),source:n.source}}return null}async function _p(t){let e=await Qs("document_evidence",{cwd:t});if(!e)return"neutral";if(e.value==="neutral"||e.value==="strict")return e.value;throw new Error(`classic.document_evidence must be neutral or strict, got '${e.value}' (${e.source})`)}function US(t,e){return[K(t,e.openSpecRoot),K(t,e.superpowersRoot)]}async function Rp(t,e){let n;try{let s=await ic(t);n=US(t,s)}catch{n=["openspec","docs/openspec","docs/superpowers"]}let r=[],i=[];for(let s of e)xp(s,n)?i.push(s):r.push(s);return{material:r,neutral:i}}function Yc(t){if(t!=="build"&&t!=="verify")throw new Error(`Invalid command check scope: '${String(t)}'`)}function eo(t,e="."){if(e.trim().length===0)throw new Error("Command check cwd cannot be blank");let n=be.resolve(t),r=be.resolve(n,e);if(r!==n&&!r.startsWith(n+be.sep))throw new Error(`Command check cwd must resolve within the project root: '${e}'`);return be.relative(n,r).replaceAll("\\","/")||"."}function Np(t,e){if(e.type!=="command_check_recorded"&&e.type!=="command_check_executed")return null;let n=e.data;if(typeof n!="object"||n===null||Array.isArray(n))return null;let{scope:r,command:i,exitCode:s,cwd:o}=n;if(r!=="build"&&r!=="verify"||typeof i!="string"||i.trim().length===0||!Number.isInteger(s)||typeof o!="string")return null;let a;try{a=eo(t,o)}catch{return null}return{sequence:e.sequence,timestamp:e.timestamp,runId:e.runId,scope:r,command:i,exitCode:s,cwd:a,...e.type==="command_check_executed"?{provenance:"runtime",argv:n.argv,timeoutMs:typeof n.timeoutMs=="number"?n.timeoutMs:void 0,inputBefore:n.inputBefore,inputAfter:n.inputAfter,changedDuringExecution:Array.isArray(n.changedDuringExecution)?n.changedDuringExecution?.filter(c=>typeof c=="string"):void 0,environment:n.environment,logRef:n.logRef,logHash:n.logHash,logSize:typeof n.logSize=="number"?n.logSize:void 0,logMtimeNs:typeof n.logMtimeNs=="string"?n.logMtimeNs:void 0,manifestRef:typeof n.manifestRef=="string"?n.manifestRef:void 0,manifestHash:typeof n.manifestHash=="string"?n.manifestHash:void 0,tier:n.tier==="incremental"?"incremental":void 0,reusable:n.reusable,checkEpoch:n.checkEpoch}:{}}}async function ei(t,e,n,r){Yc(r);let i=(await zn(e,n.trajectoryRef)).events;for(let s=i.length-1;s>=0;s-=1){let o=i[s];if(o.runId!==n.runId)continue;if(o.type==="command_checks_invalidated"&&(!Array.isArray(o.data?.scopes)||o.data.scopes.includes(r))||o.type==="command_check_started"&&o.data?.scope===r||o.type==="command_check_consumed"&&o.data?.scope===r)return null;let a=Np(t,o);if(a?.scope===r)return a}return null}function KS(t,e){if(e.type!=="command_check_started")return null;let n=e.data;if(typeof n!="object"||n===null||Array.isArray(n))return null;let{scope:r,argv:i,cwd:s,timeoutMs:o,reusable:a,tier:c}=n;if(r!=="build"&&r!=="verify"||!Array.isArray(i)||i.length===0||i.some(u=>typeof u!="string"||u.includes("\0"))||typeof s!="string"||!Number.isInteger(o)||Number(o)<1||typeof a!="boolean"||c!=="full"&&c!=="incremental")return null;let l;try{l=eo(t,s)}catch{return null}return{sequence:e.sequence,timestamp:e.timestamp,runId:e.runId,scope:r,argv:[...i],cwd:l,timeoutMs:Number(o),reusable:a,tier:c}}async function jp(t,e,n,r){Yc(r);let i=(await zn(e,n.trajectoryRef)).events;for(let s=i.length-1;s>=0;s-=1){let o=i[s];if(o.runId!==n.runId||!(o.data?.scope===r||Array.isArray(o.data?.scopes)&&o.data.scopes.includes(r)))continue;if(o.type==="command_check_started")return KS(t,o);let c=Np(t,o);if(c?.scope===r&&c.provenance==="runtime"&&c.argv?.length)return{sequence:c.sequence,timestamp:c.timestamp,runId:c.runId,scope:c.scope,argv:[...c.argv],cwd:c.cwd,timeoutMs:c.timeoutMs??3e5,reusable:c.reusable===!0,tier:c.tier??"full"};if(o.type!=="command_checks_invalidated")return null}return null}async function HS(t,e,n){let r=(await zn(t,e.trajectoryRef)).events;for(let i=r.length-1;i>=0;i-=1){let s=r[i];if(!(s.runId!==e.runId||!(s.data?.scope===n||Array.isArray(s.data?.scopes)&&s.data.scopes.includes(n))))return s.type==="command_check_started"?`a previous ${n} check attempt started at ${s.timestamp} never completed (interrupted or failed during launch); rerun the check`:null}return null}async function Gc(t,e,n,r){return pe(t,async()=>{let s={sequence:(await zn(t,e.trajectoryRef)).maximumSequence+1,timestamp:new Date().toISOString(),runId:e.runId,type:n,data:r};return await Ut(t,e.trajectoryRef,s),s})}async function Ip(t,e,n,r){if(Yc(r.scope),!r.argv.length||r.argv.some(P=>typeof P!="string"||P.includes("\0")))throw new Error("Check requires literal program arguments");let i=eo(t,r.cwd),s=await Zs.realpath(t);eo(s,await Zs.realpath(be.resolve(t,i)));let o=r.tier==="incremental"?"incremental":"full",a=await ei(t,e,n,r.scope);if(r.reusable){if(a&&a.reusable&&(a.tier??"full")===o&&a.cwd===i&&JSON.stringify(a.argv)===JSON.stringify(r.argv)){let P=await Ap(t,e,n,r.scope);if(P?.sequence===a.sequence&&P.timestamp===a.timestamp)return{...P,reused:!0}}if(!a){let P=r.scope==="build"?"verify":"build",O=await Ap(t,e,n,P);if(O?.reusable&&(O.tier??"full")===o&&O.cwd===i&&JSON.stringify(O.argv)===JSON.stringify(r.argv)){let{sequence:R,timestamp:$,runId:U,scope:se,reused:de,...q}=O,W=(await V(e,{migrate:!1})).classic?.checkEpoch??0,oe=await Gc(e,n,"command_check_executed",{...q,scope:r.scope,checkEpoch:W});return{...q,scope:r.scope,checkEpoch:W,sequence:oe.sequence,timestamp:oe.timestamp,runId:n.runId,reused:!0}}}}let c=r.timeoutMs??3e5,l=await Gc(e,n,"command_check_started",{scope:r.scope,argv:[...r.argv],cwd:i,timeoutMs:c,reusable:r.reusable===!0,tier:o}),u=(await V(e,{migrate:!1})).classic?.checkEpoch??0,d={argv:r.argv,cwd:i},f=a?.manifestRef?await $p(t,a).catch(()=>null):null,p=await Zr(t,e,d,f?{baseline:f}:{}),g=p.digest,m=await Qr(r.argv,be.resolve(t,i),await nt(t,d)),h=be.join(e,".comet","checks",`${Pp()}.log`),v=await new Promise(P=>{let O=Ef(r.argv[0],r.argv.slice(1),{cwd:be.resolve(t,i)}),R="",$=!1,U=de=>{R=(R+de.toString()).slice(-2*1024*1024)};O.stdout.on("data",U),O.stderr.on("data",U),O.on("error",de=>{R+=`
|
|
170
|
+
${de.message}`});let se=setTimeout(()=>{$=!0,hp(O).catch(()=>O.kill("SIGKILL"))},c);O.on("close",de=>{clearTimeout(se),P({exitCode:$?124:de??1,output:($?`Check timed out.
|
|
171
|
+
`:"")+R})})}),y=await Zr(t,e,d,{baseline:p.entries}).catch(()=>null),S=y?y.digest:"unavailable",b=y?(()=>{let P=Kc(p.entries,y.entries);return[...P.added,...P.removed,...P.changed].slice(0,100)})():void 0,x,w;if(y){let P=be.join(e,".comet","checks",`${Pp()}.manifest`);await $t(t,P,y.manifest,{label:"Classic check manifest"}),x=be.relative(t,P).replaceAll("\\","/"),w=Uc(y.manifest)}u!==((await V(e,{migrate:!1})).classic?.checkEpoch??0)&&(S="phase-changed"),m!==await Qr(r.argv,be.resolve(t,i),await nt(t,d))&&(S="environment-changed"),await $t(t,h,v.output,{label:"Classic check log"});let C=await Zs.stat(h,{bigint:!0}).catch(()=>null),k={scope:r.scope,command:JSON.stringify(r.argv),checkEpoch:u,argv:r.argv,timeoutMs:c,exitCode:v.exitCode,cwd:i,provenance:"runtime",inputBefore:g,inputAfter:S,changedDuringExecution:b,environment:m,logRef:be.relative(t,h).replaceAll("\\","/"),logHash:Op("sha256").update(v.output).digest("hex"),...C?{logSize:Number(C.size),logMtimeNs:C.mtimeNs.toString()}:{},manifestRef:x,manifestHash:w,tier:o,reusable:r.reusable===!0&&g===S},_=await pe(e,async()=>{if((await zn(e,n.trajectoryRef)).events.some(R=>R.runId===n.runId&&R.sequence>l.sequence&&(R.type==="command_checks_invalidated"&&(!Array.isArray(R.data?.scopes)||R.data.scopes.includes(r.scope))||R.data?.scope===r.scope)))throw new Error("Check superseded by a newer check or invalidation; rerun required");return Gc(e,n,"command_check_executed",k)});return{...k,sequence:_.sequence,timestamp:_.timestamp,runId:n.runId}}async function $p(t,e){if(typeof e.manifestHash!="string"||typeof e.manifestRef!="string")return null;let n=await I(t,e.manifestRef,{label:"Classic check manifest",maxBytes:Number.MAX_SAFE_INTEGER});return Uc(n)!==e.manifestHash?null:yp(n)}async function to(t,e,n,r,i=(s,o)=>Jc(t,e,{argv:s,cwd:o})){let s=await ei(t,e,n,r),o=u=>({record:null,reason:u});if(s&&!s.reusable&&(s.checkEpoch??0)!==((await V(e,{migrate:!1})).classic?.checkEpoch??0))return o("check evidence crossed a phase boundary");if(!s)return{record:null,reason:await HS(e,n,r)??void 0};if(s.provenance!=="runtime")return o(`the latest record is a manual record-check declaration from ${s.timestamp}; manual declarations never satisfy the guard and shadow any earlier runtime record`);if(s.exitCode!==0)return o(`the last check failed with exit code ${s.exitCode}`);if(!Array.isArray(s.argv)||!s.argv.length||!s.inputBefore)return o("the latest record is incomplete");if(s.inputBefore!==s.inputAfter)return{record:null,reason:s.changedDuringExecution?.length?"inputs changed while the check ran; if these paths are generated artifacts, declare them in the matching command outputs in .comet/check-policy.json":"inputs changed while the check ran",...s.changedDuringExecution?.length?{changedPaths:s.changedDuringExecution,relevance:"execution-time command inputs"}:{}};let a={argv:s.argv,cwd:s.cwd},c;if(s.manifestRef){let u=await nt(t,a);if(s.environment!==await Qr(s.argv,be.resolve(t,s.cwd),u))return o("the environment changed since execution (checks bind the resolved executable path and its file identity, the Node version, and declared policy environment variables; switching Node versions, package-manager shims, or PATH order invalidates evidence)");let d=await $p(t,s).catch(()=>null);if(!d)return o("the recorded input manifest is damaged or missing");let f=await Zr(t,e,a,{baseline:d}),p=Kc(d,f.entries),g=[...p.added,...p.removed,...p.changed];if(g.length){let m=u.files?`declared inputs (${u.files.join(", ")})`:"default whole-tree inputs",h=u.files||await _p(t)==="strict"?g:(await Rp(t,g)).material;if(h.length)return{record:null,reason:"check inputs changed since execution",changedPaths:h,relevance:m};c=g}}else if(s.environment!==await Qr(s.argv,be.resolve(t,s.cwd),await nt(t,a,!0),!0)||s.inputAfter!==await i(s.argv,s.cwd))return o("check inputs changed since execution");if(typeof s.logRef!="string"||typeof s.logHash!="string")return o("the evidence log record is incomplete");try{let u=await Zs.stat(be.resolve(t,s.logRef),{bigint:!0}).catch(()=>null);if(!(typeof s.logSize=="number"&&typeof s.logMtimeNs=="string"&&u!==null&&Number(u.size)===s.logSize&&u.mtimeNs.toString()===s.logMtimeNs)){let f=await I(t,s.logRef,{label:"Classic check evidence log"});if(Op("sha256").update(f).digest("hex")!==s.logHash)return o("the evidence log is damaged")}}catch{return o("the evidence log is missing")}let l=await ei(t,e,n,r);return l?.sequence!==s.sequence||l.timestamp!==s.timestamp||JSON.stringify(l)!==JSON.stringify(s)?o("the evidence was superseded by a newer check"):{record:s,...c?{documentChangesIgnored:c}:{}}}async function Ap(t,e,n,r,i=(s,o)=>Jc(t,e,{argv:s,cwd:o})){return(await to(t,e,n,r,i)).record}var Tp={"full.open":["openspec.proposal","openspec.tasks"],"full.design.handoff":["openspec.proposal","openspec.design","openspec.tasks"],"full.design.document":["design.handoff"],"full.build.plan":["openspec.tasks"],"full.build.plan-ready":["build.plan"],"full.build.configure":["build.plan"],"full.build.execute":["build.plan"],"full.build.complete":["build.tasks-complete"],"full.verify.run":["build.tasks-complete"],"full.verify.branch":["verification.report"],"full.archive.confirm":["verification.report"],"full.archive.execute":["archive.confirmed"]};function zS(t){return Tp[t]?Tp[t]:t.endsWith(".open")?["openspec.proposal","openspec.tasks"]:t.endsWith(".build.execute")?[]:t.endsWith(".build.complete")?["build.tasks-complete"]:t.endsWith(".verify.run")?["build.tasks-complete"]:t.endsWith(".verify.branch")?["verification.report"]:t.endsWith(".archive.confirm")?["verification.report"]:t.endsWith(".archive.execute")?["archive.confirmed"]:[]}function Lp(t,e){let n=zS(t),r=n.filter(i=>!Ft(e,i));return{stepId:t,passed:r.length===0,requiredEvidence:n,missingEvidence:r}}function JS(t){switch(t){case"open":return"/comet-open";case"design":return"/comet-design";case"build":return"/comet-build";case"verify":return"/comet-verify";case"archive":return"/comet-archive";default:return null}}async function qp(t,e){try{let n=await ip(t),r=await Dt(t,{classic:n.classic,run:n.run,unknownKeys:[]}),i=Fn(n.classic,r);return{name:e,valid:!0,workflow:n.classic.workflow,phase:n.classic.phase,currentStep:i,nextCommand:JS(n.classic.phase),runtimeMode:"engine-projection",runtimeEval:Lp(i,r),evidence:r}}catch(n){return{name:e,valid:!1,workflow:"unknown",phase:"invalid",currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:n instanceof Error?n.message:String(n)}}}Ns();import GS from"path";var YS=GS.join(".comet","state-events.jsonl"),VS=Number.MAX_SAFE_INTEGER;async function Mp(t,e){let n={schemaVersion:1,timestamp:new Date().toISOString(),...e};return await As(t,YS,`${JSON.stringify(n)}
|
|
172
|
+
`,VS,"Classic state event log"),n}var Fp=["open-complete","design-complete","build-complete","verify-pass","verify-fail","archive-confirm","archive-reopen","archived","preset-escalate"],XS={"open-complete":{event:"open-complete",from:"open",guardRefs:["open-artifacts-present"]},"design-complete":{event:"design-complete",from:"design",guardRefs:["design-evidence-present"]},"build-complete":{event:"build-complete",from:"build",guardRefs:["build-decisions-selected"]},"verify-pass":{event:"verify-pass",from:"verify",guardRefs:["verification-report-present"]},"verify-fail":{event:"verify-fail",from:"verify",guardRefs:["verification-failed"]},"archive-confirm":{event:"archive-confirm",from:"archive",guardRefs:["archive-final-confirmation"]},"archive-reopen":{event:"archive-reopen",from:"archive",guardRefs:["archive-not-finalized"]},archived:{event:"archived",from:"archive",guardRefs:["verify-result-pass","archive-confirmed"]},"preset-escalate":{event:"preset-escalate",from:"build",guardRefs:["preset-workflow"]}},Dp={open:"open-complete",design:"design-complete",build:"build-complete",verify:"verify-pass"};function QS(t){return t.toISOString().slice(0,10)}function L(t,e,n,r){let i=t[n];t[n]=r,i!==r&&e.push({field:n,from:i,to:r})}function Wp(t,e,n={}){let r=XS[e];if(t.phase!==r.from)throw new Error(`Cannot apply ${e}: phase is '${t.phase}', expected '${r.from}'`);let i={...t},s=[],o=t.checkEpoch??0;if(!Number.isSafeInteger(o)||o<0||o===Number.MAX_SAFE_INTEGER)throw new Error("Invalid Classic check epoch");L(i,s,"checkEpoch",o+1);let a=n.now??new Date;if(e==="open-complete")L(i,s,"phase",i.workflow==="full"?"design":"build");else if(e==="design-complete")L(i,s,"phase","build");else if(e==="build-complete"){let c=i.verifyResult==="fail";L(i,s,"phase","verify"),L(i,s,"verifyResult","pending"),L(i,s,"branchStatus","pending"),c||L(i,s,"verificationReport",null)}else if(e==="verify-pass")L(i,s,"verifyResult","pass"),L(i,s,"verifyFailures",0),L(i,s,"phase","archive"),L(i,s,"verifiedAt",QS(a)),L(i,s,"archiveConfirmation","pending"),L(i,s,"branchStatus","pending");else if(e==="verify-fail")L(i,s,"verifyResult","fail"),L(i,s,"verifyFailures",i.verifyFailures+1),L(i,s,"phase","build"),L(i,s,"branchStatus","pending");else if(e==="preset-escalate"){if(i.workflow!=="hotfix"&&i.workflow!=="tweak")throw new Error(`Cannot apply ${e}: workflow must be hotfix or tweak, got '${i.workflow}'`);L(i,s,"workflow","full"),L(i,s,"classicProfile","full"),L(i,s,"phase","design"),L(i,s,"designDoc",null),L(i,s,"buildPause",null),L(i,s,"buildMode",null),L(i,s,"subagentDispatch",null),L(i,s,"tddMode",null),L(i,s,"reviewMode",null),L(i,s,"isolation",null),L(i,s,"boundBranch",null),L(i,s,"verifyMode",null),L(i,s,"directOverride",null)}else if(e==="archive-confirm"){if(i.verifyResult!=="pass")throw new Error(`Cannot apply ${e}: verifyResult must be pass`);if(i.archived)throw new Error(`Cannot apply ${e}: already archived`);L(i,s,"archiveConfirmation","confirmed")}else if(e==="archive-reopen"){if(i.archived)throw new Error(`Cannot apply ${e}: already archived`);L(i,s,"verifyResult","pending"),L(i,s,"verifyFailures",0),L(i,s,"phase","verify"),L(i,s,"verifiedAt",null),L(i,s,"archiveConfirmation",null),L(i,s,"branchStatus","pending")}else{if(i.verifyResult!=="pass")throw new Error(`Cannot apply ${e}: verifyResult must be pass`);if(i.archiveConfirmation!=="confirmed")throw new Error(`Cannot apply ${e}: archiveConfirmation must be confirmed`);L(i,s,"archived",!0)}return{classic:i,effects:s,definition:r}}var ri=Pe(xe(),1);import Bp from"path";var ZS="\x1B[32m",ti="\x1B[31m",eE="\x1B[33m",tE="\x1B[0m",nE=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"],rE={workflow:["full","hotfix","tweak"],language:["en","zh-CN"],phase:["open","design","build","verify","archive"],context_compression:["off","beta"],build_mode:["subagent-driven-development","executing-plans","direct","autonomous"],build_pause:["plan-ready"],subagent_dispatch:["confirmed"],tdd_mode:["tdd","direct"],review_mode:["off","standard","thorough"],isolation:["current","branch","worktree"],verify_mode:["light","full"],auto_transition:["true","false"],verify_result:["pending","pass","fail"],branch_status:["pending","handled"],archive_confirmation:["pending","confirmed"],archived:["true","false"],direct_override:["true","false"],classic_profile:["full","hotfix","tweak"],classic_migration:["1"]},iE=new Set([...Ze,...pn,"classic_profile","classic_migration"]);function bn(t,e){return`${t}${e}${tE}`}function ni(t){return t==null?"":typeof t=="object"?JSON.stringify(t):String(t)}var Up=qn(async t=>{if(t.length!==1)return{exitCode:64,stderr:"Usage: comet classic validate <change-name>"};let e=t[0],n=dn(e);if(n)return{exitCode:1,stderr:bn(ti,`ERROR: ${n}`)};let r=T(),{directory:i,label:s}=await xs(e,r),o=Bp.join(i,".comet.yaml"),a=[`[VALIDATE] ${s}/.comet.yaml`],c=0,l=0,u=m=>{c+=1,a.push(bn(ti,` FAIL: ${m}`))},d=m=>{l+=1,a.push(bn(eE,` WARN: ${m}`))},f;try{f=await I(r,o,{label:`Classic state ${s}/.comet.yaml`})}catch(m){if(m.code==="ENOENT")return u(".comet.yaml does not exist"),a.push("",bn(ti,`${c} error(s), ${l} warning(s) — validation FAILED`)),{exitCode:1,stderr:a.join(`
|
|
173
173
|
`)};throw m}let p=(0,ri.parseDocument)(f);if(p.errors.length>0||!(0,ri.isMap)(p.contents)){for(let m of p.errors)u(m.message);return(0,ri.isMap)(p.contents)||u("document root must be a mapping"),a.push("",bn(ti,`${c} error(s), ${l} warning(s) — validation FAILED`)),{exitCode:1,stderr:a.join(`
|
|
174
|
-
`)}}let g=p.toJS();for(let m of
|
|
175
|
-
`)}):(a.push(bn(
|
|
176
|
-
`)})})
|
|
177
|
-
Next: ask the user to confirm — switch back to '${e}', or run \`comet state rebind ${t}\` after explicit confirmation.`}function Vp(t){return`change '${t}' uses a branch-bound workspace mode but has no bound branch and HEAD is detached; checkout a branch first before continuing.`}var
|
|
174
|
+
`)}}let g=p.toJS();for(let m of nE)Object.prototype.hasOwnProperty.call(g,m)||u(`missing required field '${m}'`);for(let[m,h]of Object.entries(rE)){if(!Object.prototype.hasOwnProperty.call(g,m))continue;let v=ni(g[m]);if(!v){m==="auto_transition"&&u(`${m}='' is not valid. Expected: ${h.join(" ")}`);continue}h.includes(v)||u(`${m}='${v}' is not valid. Expected: ${h.join(" ")}`)}if(Object.prototype.hasOwnProperty.call(g,"bound_branch")){let m=g.bound_branch;m!==null&&typeof m!="string"&&u(`bound_branch='${ni(m)}' is not a string or null`)}for(let m of["verify_failures","check_epoch"]){if(!Object.prototype.hasOwnProperty.call(g,m))continue;let h=g[m];(typeof h!="number"||!Number.isSafeInteger(h)||h<0)&&u(`${m}='${ni(h)}' is not a non-negative safe integer`)}for(let m of["design_doc","plan","handoff_context","verification_report"]){let h=ni(g[m]);if(h){if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(h)||h.split(/[\\/]/u).includes("..")){u(`${m}='${h}' must be a relative repository path`);continue}try{await G(r,Bp.resolve(r,h),{label:`${m} artifact pointer`,expected:"file"})||u(`${m}='${h}' does not exist on disk`)}catch(v){u(`${m}='${h}' is unsafe: ${v instanceof Error?v.message:String(v)}`)}}}for(let m of["handoff_hash"]){let h=ni(g[m]);h&&!/^[a-f0-9]{64}$/u.test(h)&&u(`${m}='${h}' is not a sha256 hex digest`)}for(let m of Object.keys(g))iE.has(m)||d(`unknown field '${m}' found; guard treats unknown fields as fatal — remove the field or realign it with this Comet version before advancing the phase`);return a.push(""),c>0?(a.push(bn(ti,`${c} error(s), ${l} warning(s) — validation FAILED`)),{exitCode:1,stderr:a.join(`
|
|
175
|
+
`)}):(a.push(bn(ZS,`0 errors, ${l} warning(s) — validation PASSED`)),{exitCode:0,stderr:a.join(`
|
|
176
|
+
`)})});Tt();var Vc=Pe(xe(),1);Cc();import{execFileSync as Hp}from"child_process";import{promises as sE}from"fs";import zp from"path";ot();le();function oE(t){try{let e=Hp("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim();return e&&e!=="HEAD"?e:null}catch{return null}}var aE=bc("liveGitBranch",t=>oE(t));function cE(t){try{return Hp("git",["rev-parse","--is-inside-work-tree"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()==="true"}catch{return!1}}var lE=bc("isGitWorkTree",t=>cE(t)),uE=["current","branch","worktree"];function Jp(t){return uE.includes(t)}function dE(t){return Jp(t.isolation)?t.boundBranch===null&&t.currentBranch===null&&t.gitWorkTree===!1?{status:"not-applicable"}:t.boundBranch===null?t.currentBranch===null?{status:"unbound-detached"}:{status:"needs-heal",branch:t.currentBranch}:t.currentBranch===t.boundBranch?{status:"ok"}:{status:"drift",boundBranch:t.boundBranch,currentBranch:t.currentBranch}:{status:"not-applicable"}}async function Gp(t,e){return e.heal?pe(t,()=>Kp(t,e)):Kp(t,e)}async function Kp(t,e){let n=zp.join(t,".comet.yaml"),r=(0,Vc.parseDocument)(await sE.readFile(n,"utf8"),{uniqueKeys:!1});if(r.errors.length>0)throw new Error(`Invalid .comet.yaml: ${r.errors[0].message}`);let i=r.toJS()??{},s=typeof i.isolation=="string"?i.isolation:null,o=typeof i.bound_branch=="string"&&i.bound_branch!==""?i.bound_branch:null,a=Jp(s),c=aE(e.cwd),l=a&&o===null&&c===null?lE(e.cwd):!0,u=dE({isolation:s,boundBranch:o,currentBranch:c,gitWorkTree:l});return u.status==="needs-heal"&&e.heal?(await fE(t,u.branch),{status:"healed",branch:u.branch,bindingRequired:a,currentBranch:c}):{...u,bindingRequired:a,currentBranch:c}}async function fE(t,e){return pe(t,()=>mE(t,e))}async function mE(t,e){let n=zp.join(t,".comet.yaml"),r=(await Y(t,".comet.yaml",Za,{label:"Classic branch binding"})).bytes.toString("utf8"),i=(0,Vc.parseDocument)(r,{uniqueKeys:!1});if(i.errors.length)throw new Error(`Invalid .comet.yaml: ${i.errors[0].message}`);i.set("bound_branch",e),await ye(n,i.toString(),{containedRoot:t})}function pE(t){return t??"detached HEAD"}function Yp(t,e,n){return`change '${t}' is bound to branch '${e}', but current branch is '${pE(n)}'.
|
|
177
|
+
Next: ask the user to confirm — switch back to '${e}', or run \`comet state rebind ${t}\` after explicit confirmation.`}function Vp(t){return`change '${t}' uses a branch-bound workspace mode but has no bound branch and HEAD is detached; checkout a branch first before continuing.`}var wE="\x1B[32m",yE="\x1B[31m",vE="\x1B[33m",el="\x1B[0m",kE=["open","design","build","verify","archive"],bE={open:"=== Guard: open → next ===",design:"=== Guard: design → build ===",build:"=== Guard: build → verify ===",verify:"=== Guard: verify → archive ===",archive:"=== Guard: archive completeness ==="},CE={open:" [APPLY] .comet.yaml updated: phase=PLACEHOLDER",design:" [APPLY] .comet.yaml updated: phase=build",build:" [APPLY] .comet.yaml updated: phase=verify, verify_result=pending",verify:" [APPLY] .comet.yaml updated: phase=archive, verify_result=pass"},SE={branchStatus:"branch_status",checkEpoch:"check_epoch",phase:"phase",verificationReport:"verification_report",verifiedAt:"verified_at",verifyResult:"verify_result"};function Yt(t){return`${wE}${t}${el}`}function ht(t){return`${yE}${t}${el}`}function EE(t){return`${vE}${t}${el}`}function xE(t){return SE[t]??String(t)}function _E(t){return t===null?"null":t===void 0?"":typeof t=="object"?JSON.stringify(t):String(t)}var Te=class extends Error{constructor(n,r=1){super(n);this.exitCode=r}exitCode},Qc=class{stderr=[];diagnostics;envelope;checksPassed=0;checksFailed=0;issues=[];data;toResult(e=0){return{exitCode:e,data:{...this.data,checks:{passed:this.checksPassed,total:this.checksPassed+this.checksFailed,blocked:e!==0},issues:this.issues,...this.diagnostics?{diagnostics:this.diagnostics}:{}},...this.diagnostics?{stdout:JSON.stringify({diagnostics:this.diagnostics})+`
|
|
178
178
|
`}:{},...this.stderr.length>0?{stderr:this.stderr.join(`
|
|
179
179
|
`)+`
|
|
180
|
-
`}:{},...this.envelope===void 0?{}:{envelope:this.envelope}}}};async function Q(t){let e=T();return G(e,t,{label:`Classic guard path ${M.relative(e,M.resolve(e,t)).replaceAll("\\","/")}`})}async function
|
|
181
|
-
`)}function
|
|
180
|
+
`}:{},...this.envelope===void 0?{}:{envelope:this.envelope}}}};async function Q(t){let e=T();return G(e,t,{label:`Classic guard path ${M.relative(e,M.resolve(e,t)).replaceAll("\\","/")}`})}async function ge(t){let e=T();return Oe(e,t,`Classic guard file ${M.relative(e,M.resolve(e,t)).replaceAll("\\","/")}`)}function RE(t){let e=dn(t);if(e)throw new Te(ht(`ERROR: ${e}`))}async function PE(t){return(await xs(t,T())).directory}async function H(t,e){let n=M.join(t,".comet.yaml"),r=(0,Zc.parseDocument)(await I(T(),n,{label:`Classic state ${t}/.comet.yaml`}),{uniqueKeys:!1});if(r.errors.length>0)throw new Te(`ERROR: Invalid .comet.yaml: ${r.errors[0].message}`);let s=r.toJS()[e];return s==null?"":typeof s=="object"?JSON.stringify(s):String(s)}async function AE(t,e){let n=await H(e,t);return n&&n!=="null"?n:(await Qs(t,{cwd:T()}))?.value??""}async function OE(t){let e=await AE("language",t);if(!e)return"en";if(e==="en"||e==="zh-CN")return e;throw new Error(`configured language '${e}' is invalid; expected en or zh-CN.`)}function NE(t){let e=[],n=!1;for(let r of t.split(/\r?\n/u)){if(/^\s*```/u.test(r)){n=!n;continue}n||e.push(r)}return e.join(`
|
|
181
|
+
`)}function jE(t){return t.match(/[\u4e00-\u9fff]/gu)?.length??0}function IE(t){return t.match(/[A-Za-z][A-Za-z0-9_-]{2,}/gu)?.length??0}async function it(t,e){let n=await OE(t),r=NE(await I(T(),e,{label:`Classic language-check artifact ${e}`})),i=jE(r),s=IE(r);return n==="zh-CN"&&i<20&&s>=20?A(`configured language is zh-CN, but ${e} appears to be English-dominant (cjk_chars=${i}, english_words=${s}).
|
|
182
182
|
Next: regenerate or rewrite this artifact in Chinese while preserving necessary technical terms.`):n==="en"&&i>20&&i>s?A(`configured language is en, but ${e} appears to be Chinese-dominant (cjk_chars=${i}, english_words=${s}).
|
|
183
|
-
Next: regenerate or rewrite this artifact in English while preserving necessary technical terms.`):j()}async function Qp(t){return
|
|
184
|
-
`)).digest("hex")}async function
|
|
183
|
+
Next: regenerate or rewrite this artifact in English while preserving necessary technical terms.`):j()}async function Qp(t){return Qe(t,await I(T(),t,{label:`Classic handoff source ${t}`}))}async function tl(t){let e=K(T(),t),n=[`${e}/proposal.md`,`${e}/design.md`,`${e}/tasks.md`];return await Q(`${e}/.openspec.yaml`)&&n.push(`${e}/.openspec.yaml`),n.push(...await ft(T(),`${e}/specs`)),n}async function $E(t){let e=[];for(let n of await tl(t))await Q(n)&&e.push(`path:${n}`,`sha256:${await Qp(n)}`);return hE("sha256").update(e.join(`
|
|
184
|
+
`)).digest("hex")}async function TE(t,e){if(!await Q(t))throw new Te(ht(`FATAL: change directory not found: ${t}`));if(!await Q(M.join(t,".comet.yaml")))throw new Te(ht(`FATAL: .comet.yaml not found in ${t}`));await me(T(),M.join(t,".comet"),{label:`Classic runtime directory for ${e}`,expected:"directory"});let n=await Up([e],{json:!1});if(n.exitCode!==0)throw n.stderr&&process.stderr.write(n.stderr.endsWith(`
|
|
185
185
|
`)?n.stderr:`${n.stderr}
|
|
186
|
-
`),new
|
|
187
|
-
`))t.stderr.push(
|
|
188
|
-
`))t.stderr.push(
|
|
186
|
+
`),new Te(ht("FATAL: .comet.yaml schema validation failed"));let r=await V(t),i=Array.from(new Set(r.unknownKeys)).sort();if(i.length>0)throw new Te(ht(`FATAL: .comet.yaml has unknown field(s): ${i.join(", ")}. Remove them (or realign them with this Comet version, e.g. after a version rollback), then rerun comet classic validate`))}function LE(t,e){if(e.passed){if(t.checksPassed+=1,t.stderr.push(Yt(` [PASS] ${e.description}`)),e.detail)for(let n of e.detail.split(`
|
|
187
|
+
`))t.stderr.push(Yt(` ${n}`))}else if(t.checksFailed+=1,t.issues.push(Lt(e.detail||e.description,{code:"CLASSIC_GUARD_CHECK_FAILED",path:`checks.${e.description}`,expected:"pass",actual:"fail",remediation:"Repair this prerequisite using the reported detail, then retry the same guard. Preserve valid artifacts and evidence."})),t.stderr.push(ht(` [FAIL] ${e.description}`)),e.detail)for(let n of e.detail.split(`
|
|
188
|
+
`))t.stderr.push(ht(` ${n}`))}function N(t,e){return async()=>{try{let n=await e();return{description:t,passed:n.passed,detail:("detail"in n?n.detail:"")??""}}catch(n){return{description:t,passed:!1,detail:n instanceof Error?n.message:String(n)}}}}function j(t){return{passed:!0,...t?{detail:t}:{}}}function A(t){return{passed:!1,detail:t}}async function Vt(t,e){let n=!1;for(let r of e){let i=await r();LE(t,i),i.passed||(n=!0)}return n}var qE=["package.json with a build script (invocation root, or a single workspace package when the root has none)","pom.xml","Cargo.toml"];async function ME(t){try{let e=await ut(T(),{allowPartialProject:!0});return e?Object.prototype.hasOwnProperty.call(e.value,t):!1}catch(e){throw new Error(`.comet/config.yaml is invalid YAML (${e instanceof Error?e.message:String(e)}); cannot check for removed "${t}" field. Fix the config and retry.`,{cause:e})}}function FE(t){return{status:1,output:`${t} has been removed from .comet/config.yaml. Delete this field and run any required ${t==="build_command"?"build":"verification"} command manually before retrying.`}}function Gt(t){return M.resolve(un(),t)}function DE(t){let e=t.replaceAll("\\","/").replace(/\/+$/u,""),n=/^(.+\/)?\*(?:\/\*\*)?$/u.exec(e);return n?{prefix:n[1]??"",wildcard:!0}:e.includes("*")?null:{prefix:e,wildcard:!1}}var Xp=32;async function WE(t){let n=(Array.isArray(t)?t:t&&typeof t=="object"&&Array.isArray(t.packages)?t.packages:[]).filter(s=>typeof s=="string"),r=Gt("pnpm-workspace.yaml");if(await Q(r))try{let o=(0,Zc.parseDocument)(await I(T(),r,{label:"pnpm-workspace.yaml"})).get("packages");if(Array.isArray(o))for(let a of o)typeof a=="string"&&n.push(a)}catch{}let i=new Set;for(let s of n){let o=DE(s);if(!o)continue;if(!o.wildcard){i.add(o.prefix);continue}let a=o.prefix?Gt(o.prefix):un(),c;try{c=await gE.readdir(a,{withFileTypes:!0})}catch{continue}for(let l of c.slice(0,Xp))l.isDirectory()&&i.add(`${o.prefix}${l.name}`);if(i.size>=Xp)break}return[...i].sort()}async function BE(){let t=Gt("package.json");if(await Q(t)){let e=JSON.parse(await I(T(),t,{label:"package.json"}));if(typeof e.scripts?.build=="string")return"npm run build";let n=[];for(let r of await WE(e.workspaces)){let i=Gt(M.posix.join(r,"package.json"));if(await Q(i))try{typeof JSON.parse(await I(T(),i,{label:`package.json (${r})`})).scripts?.build=="string"&&n.push(r)}catch{continue}}if(n.length===1)return`npm --prefix ${n[0].includes(" ")?`"${n[0]}"`:n[0]} run build`;if(n.length>1)return{ambiguous:n}}return await Q(Gt("pom.xml"))?process.platform==="win32"?await Q(Gt("mvnw.cmd"))?"mvnw.cmd compile -q":"mvn.cmd compile -q":await Q(Gt("mvnw"))?"./mvnw compile -q":"mvn compile -q":await Q(Gt("Cargo.toml"))?"cargo build":null}function ii(t){return`Evidence: recorded command-check at ${t.timestamp}; command: ${t.command}; cwd: ${t.cwd}`}function Jt(t,e,n){let r=typeof n!="string"||UE(n)!==null?null:n;return r===null?`comet check rerun ${t} ${e}`:`comet check run ${t} ${e} --local -- ${r}`}function UE(t){let e=t.trim();if(!e.startsWith("["))return null;try{let n=JSON.parse(e);return Array.isArray(n)&&n.every(r=>typeof r=="string")?n:null}catch{return null}}async function Zp(t,e){let n=await nt(t,{argv:e.argv??[],cwd:e.cwd});return n.declaredCwd?M.resolve(t,n.declaredCwd):un()}async function eh(t,e,n,r){if(process.env.COMET_SKIP_BUILD==="1")return{status:0,output:"SKIPPED via COMET_SKIP_BUILD=1"};let i=r==="build"?["build_command"]:["verify_command","build_command"];for(let m of i)if(await ME(m))return FE(m);let s=T(),o=M.relative(s,un())||".",a=await to(s,t,n,r),c=a.record,l=null;if(c){let m=await Zp(s,c);M.resolve(s,c.cwd)!==M.resolve(m)&&(l=c,c=null)}let u=c?null:await ei(s,t,n,r),d=!c&&!u?await jp(s,t,n,r):null,f=r==="build"&&!c&&!u&&!d?await BE():null;if(f!==null&&typeof f!="object")return c=await Ip(s,t,n,{scope:r,reusable:!0,cwd:o,argv:process.platform==="win32"?[process.env.ComSpec||"cmd.exe","/d","/s","/c",f]:["/bin/sh","-c",f]}),c.exitCode!==0?{status:c.exitCode,output:`Build failed (guard auto-ran the detected command '${f}' in '${o}'; disable with COMET_SKIP_BUILD=1). Log: ${c.logRef}`}:c.inputBefore!==c.inputAfter?{status:1,output:[`The detected build command '${f}' changed its own check inputs (for example nondeterministic build artifacts).`,...c.changedDuringExecution?.length?[`Changed inputs: ${c.changedDuringExecution.slice(0,20).join(", ")}.`]:[],"If these paths are generated artifacts, add them to the matching command outputs in .comet/check-policy.json; otherwise stabilize the inputs before rerunning.",`Next: ${Jt(e,r,"<program> [args...]")}`].join(`
|
|
189
189
|
`)}:{status:0,output:`${ii(c)} (guard auto-ran the detected command '${f}' in '${o}')`};if(f!==null&&typeof f=="object"){let m=f.ambiguous[0].includes(" ")?`"${f.ambiguous[0]}"`:f.ambiguous[0];return{status:1,output:[`The invocation root has no build script, and several workspace packages declare one: ${f.ambiguous.join(", ")}.`,"Guard auto-runs a build only when exactly one candidate exists.",`Next: record the intended build explicitly, for example:
|
|
190
|
-
${
|
|
190
|
+
${Jt(e,r,`npm --prefix ${m} run build`)}`].join(`
|
|
191
191
|
`)}}if(!c){if(d)return{status:1,output:[`The latest Runtime ${r} check started at ${d.timestamp} but did not complete.`,"Its original argv, cwd, timeout and evidence policy were preserved; automatic command discovery will not replace it.",`Next: comet check rerun ${e} ${r}`].join(`
|
|
192
192
|
`)};if(u&&u.exitCode!==0)return{status:u.exitCode,output:`Latest recorded ${r} check failed with exit code ${u.exitCode}.
|
|
193
193
|
${ii(u)}
|
|
194
|
-
Next: ${
|
|
195
|
-
`)};if(l)return{status:1,output:[`No current Runtime ${r} evidence from this directory.`,ii(l),`Why: the recorded check is valid but ran in '${l.cwd}'; check evidence is reused only when its cwd matches the guard's invocation directory '${o}' or a matching check-policy entry.`,`Rerun the command in a form that executes from '${o}' (for example npm --prefix <subdir> run build for a subdirectory build) and record it again, or declare this command with cwd '${l.cwd}' in .comet/check-policy.json (version 2) to bind subdirectory evidence.`,`Next: ${
|
|
196
|
-
`)};let m=
|
|
197
|
-
Next: ${
|
|
198
|
-
Next: ${
|
|
194
|
+
Next: ${Jt(e,r,u.argv??u.command)}`};if(u&&u.provenance!=="runtime")return{status:1,output:[`Latest ${r} record is a manual record-check declaration (recorded ${u.timestamp}, command: ${u.command}).`,"Manual declarations never satisfy the guard, and they shadow the earlier runtime evidence until a new runtime check runs.",`Next: ${Jt(e,r,"<program> [args...]")}`].join(`
|
|
195
|
+
`)};if(l)return{status:1,output:[`No current Runtime ${r} evidence from this directory.`,ii(l),`Why: the recorded check is valid but ran in '${l.cwd}'; check evidence is reused only when its cwd matches the guard's invocation directory '${o}' or a matching check-policy entry.`,`Rerun the command in a form that executes from '${o}' (for example npm --prefix <subdir> run build for a subdirectory build) and record it again, or declare this command with cwd '${l.cwd}' in .comet/check-policy.json (version 2) to bind subdirectory evidence.`,`Next: ${Jt(e,r,"<program> [args...]")}`].join(`
|
|
196
|
+
`)};let m=HE(a);return{status:1,output:r==="build"?`No current Runtime build evidence. Detection searched: ${qE.join(", ")}.${m}
|
|
197
|
+
Next: ${Jt(e,r,"<program> [args...]")}`:`No current Runtime verify evidence. Manual attestations, stale inputs and recovered checks require a new execution.${m}
|
|
198
|
+
Next: ${Jt(e,r,"<program> [args...]")}`}}if(c.exitCode!==0)return{status:c.exitCode,output:`Latest recorded ${r} check failed with exit code ${c.exitCode}.
|
|
199
199
|
${ii(c)}
|
|
200
200
|
Next: rerun the command successfully, then record it with:
|
|
201
|
-
${
|
|
202
|
-
Ignored document-only changes (neutral by default; declare inputs in .comet/check-policy.json or set classic.document_evidence: strict if this command consumes them): ${n.join(", ")}${r>0?` (+${r} more)`:""}`}function
|
|
201
|
+
${Jt(e,r,c.argv??c.command)}`};let p=c.tier==="incremental"?" (incremental evidence: rerun the full command before --apply)":"",g=KE(a);return{status:0,output:`${ii(c)}${p}${g}`}}function KE(t){let e=t.documentChangesIgnored;if(!e?.length)return"";let n=e.slice(0,10),r=e.length-n.length;return`
|
|
202
|
+
Ignored document-only changes (neutral by default; declare inputs in .comet/check-policy.json or set classic.document_evidence: strict if this command consumes them): ${n.join(", ")}${r>0?` (+${r} more)`:""}`}function HE(t){if(!t.reason)return"";let e=[`
|
|
203
203
|
Why: ${t.reason}.`];if(t.changedPaths?.length){let n=t.changedPaths.slice(0,20),r=t.changedPaths.length-n.length;e.push(`Changed inputs: ${n.join(", ")}${r>0?` (+${r} more)`:""}`),t.relevance&&e.push(`Relevance scope: ${t.relevance}.`)}return e.join(`
|
|
204
204
|
`)}async function nl(t){let e=M.join(t,"tasks.md");if(!await Q(e))return A(`tasks.md is missing at ${e}
|
|
205
|
-
Next: restore or create tasks.md for this change before leaving build.`);let n=await I(T(),e,{label:`Classic tasks ${e}`}),r=
|
|
205
|
+
Next: restore or create tasks.md for this change before leaving build.`);let n=await I(T(),e,{label:`Classic tasks ${e}`}),r=Ne(n);if(!r.some(s=>s.completed))return A(`tasks.md has no completed tasks.
|
|
206
206
|
Next: complete implementation tasks and mark them with '- [x]'.`);let i=r.filter(s=>!s.completed);return i.length>0?A(`Unfinished tasks:
|
|
207
207
|
${i.map(s=>`${s.line}:${s.text}`).join(`
|
|
208
208
|
`)}
|
|
209
|
-
Next: complete or explicitly remove unfinished tasks, then mark tasks.md with '- [x]'.`):j()}async function
|
|
210
|
-
Next: restore the implementation plan or update .comet.yaml plan before leaving build.`);let n=await I(T(),e,{label:`Classic plan ${e}`}),r=M.join(t,"tasks.md"),i=
|
|
209
|
+
Next: complete or explicitly remove unfinished tasks, then mark tasks.md with '- [x]'.`):j()}async function zE(t){let e=M.join(t,"tasks.md");return await Q(e)?Ne(await I(T(),e,{label:`Classic tasks ${e}`})).length>0:!1}async function JE(t){let e=await H(t,"plan");if(!e||e==="null")return j();if(!await Q(e))return A(`plan file is missing at ${e}
|
|
210
|
+
Next: restore the implementation plan or update .comet.yaml plan before leaving build.`);let n=await I(T(),e,{label:`Classic plan ${e}`}),r=M.join(t,"tasks.md"),i=Ne(await I(T(),r,{label:"Classic plan task authority"})),s=M.relative(T(),r).replaceAll("\\","/");if(Cf(n,s,i)==="canonical")return j();let{unmapped:o}=ys(n,i);return o.length>0?A(`Unmapped implementation plan tasks:
|
|
211
211
|
${o.map(a=>`${a.line}:${a.text}`).join(`
|
|
212
212
|
`)}
|
|
213
|
-
Next: reconcile these items against implementation and acceptance, map them to tasks.md IDs or add genuinely extra tasks. Checkbox state alone is not evidence of completion.`):j()}async function rl(t,e){let n;try{n=await Gp(t,{heal:!0,cwd:un()})}catch(r){throw new
|
|
213
|
+
Next: reconcile these items against implementation and acceptance, map them to tasks.md IDs or add genuinely extra tasks. Checkbox state alone is not evidence of completion.`):j()}async function rl(t,e){let n;try{n=await Gp(t,{heal:!0,cwd:un()})}catch(r){throw new Te(`ERROR: ${r instanceof Error?r.message:String(r)}`)}switch(n.status){case"drift":return A(Yp(e,n.boundBranch,n.currentBranch));case"unbound-detached":return A(Vp(e));case"healed":return j(`bound_branch lazily set to ${n.branch}`);case"needs-heal":case"ok":case"not-applicable":return j();default:{let r=n;throw new Error(`unhandled branch binding status: ${JSON.stringify(r)}`)}}}async function GE(t,e){let n=await H(t,"isolation");return n==="current"||n==="branch"||n==="worktree"?j():A(`isolation must be current, branch, or worktree, got '${n||"null"}'
|
|
214
214
|
Next: choose a valid workspace mode, prepare it when needed, then run:
|
|
215
|
-
comet state set ${e} isolation <current|branch|worktree>`)}async function
|
|
215
|
+
comet state set ${e} isolation <current|branch|worktree>`)}async function YE(t,e){let n=await H(t,"build_mode");return["subagent-driven-development","executing-plans","direct","autonomous"].includes(n)?j():A(`build_mode must be selected before leaving build, got '${n||"null"}'
|
|
216
216
|
Next: ask the user to choose an execution mode, then run:
|
|
217
|
-
comet state set ${e} build_mode <subagent-driven-development|executing-plans|autonomous>`)}async function
|
|
218
|
-
Next: choose executing-plans or subagent-driven-development, or stop and ask the user for an explicit direct override.`)}async function
|
|
219
|
-
Next: resume /comet-build and use the single joint decision to confirm the supported execution configuration for ${e}`)}async function
|
|
217
|
+
comet state set ${e} build_mode <subagent-driven-development|executing-plans|autonomous>`)}async function VE(t){let e=await H(t,"workflow"),n=await H(t,"build_mode"),r=await H(t,"direct_override");return n!=="direct"||e==="hotfix"||e==="tweak"||r==="true"?j():A(`build_mode=direct is only allowed for hotfix/tweak unless direct_override: true is recorded
|
|
218
|
+
Next: choose executing-plans or subagent-driven-development, or stop and ask the user for an explicit direct override.`)}async function XE(t,e){let n=await H(t,"build_mode"),r=await H(t,"subagent_dispatch");return n!=="subagent-driven-development"||r==="confirmed"?j():A(`subagent_dispatch must be confirmed after the user selects subagent-driven-development
|
|
219
|
+
Next: resume /comet-build and use the single joint decision to confirm the supported execution configuration for ${e}`)}async function QE(t,e){let n=await H(t,"workflow");if(n==="hotfix"||n==="tweak")return j();let r=await H(t,"tdd_mode");return r==="tdd"||r==="direct"?j():A(`tdd_mode must be tdd or direct for full workflow, got '${r||"null"}'
|
|
220
220
|
Next: ask the user to choose TDD enforcement level, then run:
|
|
221
|
-
comet state set ${e} tdd_mode <tdd|direct>`)}async function
|
|
221
|
+
comet state set ${e} tdd_mode <tdd|direct>`)}async function ZE(t,e){let n=await H(t,"workflow");if(n==="hotfix"||n==="tweak")return j();let r=await H(t,"review_mode");return r==="off"||r==="standard"||r==="thorough"?j():A(`review_mode must be off, standard, or thorough before leaving build, got '${r||"null"}'
|
|
222
222
|
Next: ask the user to choose review strength, then run:
|
|
223
|
-
comet state set ${e} review_mode <off|standard|thorough>`)}async function
|
|
224
|
-
Next: create the Design Doc and run: comet state set ${e} design_doc <path>`)}async function
|
|
225
|
-
Next: run comet handoff ${e} design --write before invoking Superpowers.`);if(!await
|
|
223
|
+
comet state set ${e} review_mode <off|standard|thorough>`)}async function ex(t){let e=await H(t,"verification_report");return!!e&&e!=="null"&&await Q(e)}async function tx(t){return await H(t,"branch_status")==="handled"}async function nx(t){return await H(t,"archived")==="true"}async function Xc(t,e,n){let r=(await I(T(),t,{label:`Classic Design Doc ${t}`})).replace(/^\uFEFF/u,""),i=!1;for(let s of r.split(/\r?\n/u)){if(!i){s==="---"&&(i=!0);continue}if(s==="---")break;if(new RegExp(`^${e}: ['"]?${n}['"]?\\s*$`,"u").test(s))return!0}return!1}async function rx(t,e){let n=await H(t,"design_doc");return n&&n!=="null"&&await Q(n)?j():A(`design_doc must point to an existing Superpowers Design Doc for full workflow before leaving design.
|
|
224
|
+
Next: create the Design Doc and run: comet state set ${e} design_doc <path>`)}async function ix(t,e){let n=await H(t,"handoff_context"),r=await H(t,"handoff_hash");if(!n||n==="null")return A(`handoff_context is missing from .comet.yaml
|
|
225
|
+
Next: run comet handoff ${e} design --write before invoking Superpowers.`);if(!await ge(n))return A(`handoff_context does not point to a non-empty file: ${n}
|
|
226
226
|
Next: regenerate the design handoff with comet handoff ${e} design --write.`);if(!/^[a-f0-9]{64}$/u.test(r))return A(`handoff_hash is missing or invalid: ${r||"null"}
|
|
227
|
-
Next: regenerate the design handoff with comet handoff ${e} design --write.`);let i=await
|
|
227
|
+
Next: regenerate the design handoff with comet handoff ${e} design --write.`);let i=await $E(t);if(i!==r)return A(`OpenSpec artifacts changed after handoff was generated.
|
|
228
228
|
Expected handoff_hash: ${r}
|
|
229
229
|
Actual handoff_hash: ${i}
|
|
230
|
-
Next: run comet handoff ${e} design --write so Superpowers receives the current OpenSpec context.`);let s=`${n.replace(/\.json$/u,"")}.md`;return await
|
|
231
|
-
Next: regenerate the design handoff with comet handoff ${e} design --write.`)}async function
|
|
232
|
-
`))}async function th(t){return await H(t,"context_compression")||"off"}async function
|
|
233
|
-
`))}async function
|
|
234
|
-
`)):j()),N("proposal.md exists and non-empty",async()=>await
|
|
235
|
-
`)):j()),N("proposal.md exists",async()=>await
|
|
236
|
-
`)):j()}),N("subagent dispatch confirmed",()=>
|
|
237
|
-
`)):j()}),N("tasks.md all tasks checked",()=>nl(e)),N("branch_status=handled",async()=>await
|
|
238
|
-
Valid phases: open, design, build, verify, archive`);await on(T());let o=await
|
|
239
|
-
`))n.stderr.push(a);return n.toResult(o.exitCode)}return n.stderr.push(o instanceof Error?o.message:String(o)),n.toResult(70)}});var
|
|
230
|
+
Next: run comet handoff ${e} design --write so Superpowers receives the current OpenSpec context.`);let s=`${n.replace(/\.json$/u,"")}.md`;return await ge(s)?j():A(`design handoff markdown is missing or empty: ${s}
|
|
231
|
+
Next: regenerate the design handoff with comet handoff ${e} design --write.`)}async function sx(t){let e=await H(t,"handoff_context");if(!e||e==="null")return A("handoff_context is missing from .comet.yaml");let n=`${e.replace(/\.json$/u,"")}.md`;if(!await ge(n))return A(`design handoff markdown is missing or empty: ${n}`);let r=await I(T(),n,{label:`Classic handoff markdown ${n}`}),i=new Set(r.split(/\r?\n/u)),s=[];/^Generated-by: comet-handoff\.sh$/mu.test(r)||s.push("handoff markdown is missing Generated-by marker"),/^- Mode: (compact|full|beta)$/mu.test(r)||s.push("handoff markdown is missing Mode marker");for(let o of await tl(t))await Q(o)&&(i.has(`- Source: ${o}`)||s.push(`handoff markdown is missing source reference: ${o}`),i.has(`- SHA256: ${await Qp(o)}`)||s.push(`handoff markdown is missing current sha256 for: ${o}`));return s.length===0?j():A(s.join(`
|
|
232
|
+
`))}async function th(t){return await H(t,"context_compression")||"off"}async function ox(t){if(await th(t)!=="beta")return j();let e=await H(t,"handoff_context");if(!e||e==="null")return A("handoff_context is missing from .comet.yaml");if(!await ge(e))return A(`spec-context.json is missing or empty: ${e}`);let n=await I(T(),e,{label:`Classic handoff context ${e}`}),r=[],i;try{i=JSON.parse(n)}catch(a){return A(`spec-context.json invalid JSON: ${a instanceof Error?a.message:String(a)}`)}if(!i||typeof i!="object"||Array.isArray(i))return A("spec-context.json root must be an object");let s=i;typeof s.change!="string"&&r.push("spec-context.json missing 'change' field"),typeof s.phase!="string"&&r.push("spec-context.json missing 'phase' field"),s.mode!=="beta"&&r.push("spec-context.json mode is not beta"),typeof s.context_hash!="string"&&r.push("spec-context.json missing 'context_hash' field"),Array.isArray(s.files)||r.push("spec-context.json missing 'files' field");let o=Array.isArray(s.files)?s.files.filter(a=>!!a&&typeof a=="object"&&!Array.isArray(a)):[];for(let a of await tl(t))await Q(a)&&(o.some(c=>c.path===a&&typeof c.sha256=="string")||r.push(`spec-context.json missing source file reference: ${a}`));return r.length===0?j():A(r.join(`
|
|
233
|
+
`))}async function ax(t,e){let n=await H(e,"workflow"),r=await Br(T(),e),i=[N("OpenSpec required dependency closure is ready",async()=>r.problems.length?A(r.problems.join(`
|
|
234
|
+
`)):j()),N("proposal.md exists and non-empty",async()=>await ge(M.join(e,"proposal.md"))?j():A("")),N("proposal.md matches configured language",()=>it(e,M.join(e,"proposal.md"))),N("tasks.md exists and non-empty",async()=>await ge(M.join(e,"tasks.md"))?j():A("")),N("tasks.md matches configured language",()=>it(e,M.join(e,"tasks.md"))),N("tasks.md has at least one task",async()=>await zE(e)?j():A(""))];return n==="full"&&(r.designRequired||await Q(M.join(e,"design.md")))&&i.splice(1,0,N("design.md exists and non-empty",async()=>await ge(M.join(e,"design.md"))?j():A("")),N("design.md matches configured language",()=>it(e,M.join(e,"design.md")))),Vt(t,i)}async function cx(t,e,n){let r=await H(e,"design_doc"),i=await H(e,"workflow"),s=await Br(T(),e),o=s.designRequired||await Q(M.join(e,"design.md")),a=[N("OpenSpec required dependency closure is ready",async()=>s.problems.length?A(s.problems.join(`
|
|
235
|
+
`)):j()),N("proposal.md exists",async()=>await ge(M.join(e,"proposal.md"))?j():A("")),N("proposal.md matches configured language",()=>it(e,M.join(e,"proposal.md"))),N("design.md exists",async()=>!o||await ge(M.join(e,"design.md"))?j():A("")),N("design.md matches configured language",async()=>o?it(e,M.join(e,"design.md")):j()),N("tasks.md exists",async()=>await ge(M.join(e,"tasks.md"))?j():A("")),N("tasks.md matches configured language",()=>it(e,M.join(e,"tasks.md"))),N("design handoff context exists",()=>ix(e,n)),N("design handoff markdown is traceable",()=>sx(e))];await th(e)==="beta"&&a.push(N("beta spec-context.json is structurally valid",()=>ox(e))),i==="full"&&a.push(N("design_doc is recorded for full workflow",()=>rx(e,n)));let c=await Vt(t,a);return r&&r!=="null"?c=await Vt(t,[N(`Design Doc (${r}) exists`,async()=>await ge(r)?j():A("")),N("Design Doc matches configured language",()=>it(e,r)),N("Design Doc frontmatter links current change",async()=>await ge(r)&&await Xc(r,"comet_change",n)?j():A("")),N("Design Doc declares technical design role",async()=>await ge(r)&&await Xc(r,"role","technical-design")?j():A("")),N("Design Doc declares OpenSpec as canonical spec",async()=>await ge(r)&&await Xc(r,"canonical_spec","openspec")?j():A(""))])||c:i!=="full"&&t.stderr.push(EE(" [WARN] No design_doc recorded in .comet.yaml (optional for hotfix/tweak)")),c}async function lx(t,e,n,r){return await Vt(t,[N("bound branch matches workspace mode",()=>rl(e,n)),N("isolation selected",()=>GE(e,n)),N("build_mode selected",()=>YE(e,n)),N("build_mode allowed for workflow",()=>VE(e)),N("autonomous full build prerequisites",async()=>{let s=(await V(e,{migrate:!1})).classic;if(!s)return A("Classic state is missing");let o=await bf(T(),n,s);return o.length?A(o.join(`
|
|
236
|
+
`)):j()}),N("subagent dispatch confirmed",()=>XE(e,n)),N("tdd_mode selected",()=>QE(e,n)),N("review_mode selected",()=>ZE(e,n)),N("tasks.md all tasks checked",()=>nl(e)),N("plan task mapping is valid",()=>JE(e)),N("proposal.md exists",async()=>await ge(M.join(e,"proposal.md"))?j():A("")),N("proposal.md matches configured language",()=>it(e,M.join(e,"proposal.md"))),N("Superpowers plan matches configured language",async()=>{let s=await H(e,"plan");return!s||s==="null"||!await Q(s)?j():it(e,s)})])?!0:Vt(t,[N("Build passes",async()=>{let s=await eh(e,n,r,"build");return s.status===0?j(s.output):A(s.output)})])}async function ux(t,e,n,r){return await Vt(t,[N("bound branch matches workspace mode",()=>rl(e,n)),N("tasks.md all tasks checked",()=>nl(e)),N("verification_report exists",async()=>await ex(e)?j():A("")),N("verification_report matches configured language",async()=>{let s=await H(e,"verification_report");return!s||s==="null"||!await Q(s)?j():it(e,s)})])?!0:Vt(t,[N("Verification passes",async()=>{let s=await eh(e,n,r,"verify");return s.status===0?j(s.output):A(s.output)})])}async function dx(t,e,n){return Vt(t,[N("bound branch matches workspace mode",()=>rl(e,n)),N("archived is true",async()=>await nx(e)?j():A("")),N("proposal.md exists",async()=>await ge(M.join(e,"proposal.md"))?j():A("")),N("archived required artifacts exist",async()=>{let r=await zf(T(),e);return r.length?A(r.join(`
|
|
237
|
+
`)):j()}),N("tasks.md all tasks checked",()=>nl(e)),N("branch_status=handled",async()=>await tx(e)?j():A(""))])}async function fx(t,e,n,r){return pe(n,()=>mx(t,e,n,r))}async function mx(t,e,n,r){let i=Dp[r];if(!i)return;let s=await Kn(n);if((r==="build"||r==="verify")&&process.env.COMET_SKIP_BUILD!=="1"){let u=(await to(T(),n,s.run,r)).record,d=!!(u&&M.resolve(T(),u.cwd)!==M.resolve(await Zp(T(),u)));if(!u||u.tier==="incremental"||d){let f=u?.tier==="incremental"?"Incremental check evidence cannot advance the phase; rerun the full command before --apply.":d&&u?`Check evidence ran in '${u.cwd}', not the guard's invocation directory '${M.relative(T(),un())||"."}'; rerun the check from the invocation directory, or declare its cwd in .comet/check-policy.json (version 2), before --apply.`:"Check evidence changed before transition; rerun the check.";throw new Te(f)}}let o=Wp(s.classic,i);await Hs(n,o.classic,s.run,{event:i,phase:r,source:"comet-guard"}),await Mp(n,{change:e,event:i,source:"comet-guard",from:s.classic,to:o.classic,effects:o.effects});for(let l of o.effects)t.stderr.push(Yt(`[SET] ${xE(l.field)}=${_E(l.to)}`));t.stderr.push(Yt(`[TRANSITION] ${i}`));let a=CE[r],c=r==="open"?a.replace("PLACEHOLDER",o.classic.phase):a;t.stderr.push(Yt(c))}var nh=qn(async(t,e)=>{let n=new Qc,[r,i,s]=t;try{if(t.length<2||t.length>3||s!==void 0&&s!=="--apply")throw new Te("Usage: comet guard <change-name> <open|design|build|verify|archive> [--apply]");if(RE(r),!i||!kE.includes(i))throw new Te(`${ht(`Unknown phase: ${i??""}`)}
|
|
238
|
+
Valid phases: open, design, build, verify, archive`);await on(T());let o=await PE(r);await TE(o,r);let a=await Kn(o);n.data={change:r,phase:a.classic.phase,projectRoot:T(),changeDir:o};let c=await qp(o,r);e.json&&(n.diagnostics={change:r,phase:i,currentStep:c.currentStep,runtimeEval:c.runtimeEval}),n.stderr.push(bE[i]);let l;i==="open"?l=await ax(n,o):i==="design"?l=await cx(n,o,r):i==="build"?l=await lx(n,o,r,a.run):i==="verify"?l=await ux(n,o,r,a.run):l=await dx(n,o,r);let u=sp({name:r,phase:i,failed:n.checksFailed,total:n.checksPassed+n.checksFailed,locale:Vr(a.classic.language)});if(n.envelope=u,l)return n.stderr.push(""),n.stderr.push(u.summary),u.user_message&&n.stderr.push(`RELAY TO USER: ${u.user_message}`),n.stderr.push(""),n.stderr.push(ht("BLOCKED — fix failing checks before proceeding to next phase")),n.toResult(1);if(n.stderr.push(""),n.stderr.push(u.summary),i==="archive")n.stderr.push(Yt("ALL CHECKS PASSED — archive completeness verified; no further phase transition."));else if(s==="--apply"){n.stderr.push(Yt("ALL CHECKS PASSED — ready for next phase")),await fx(n,r,o,i);let d=await V(o,{migrate:!1});d.classic&&(n.data={...await pp(T(),o,d.classic,!1,d.run??null),change:r,phase:d.classic.phase,configuration:d.classic})}else n.stderr.push(Yt("ALL CHECKS PASSED — ready for next phase")),n.stderr.push(`Check only: phase unchanged. To advance, run comet guard ${r} ${i} --apply`);return n.toResult(0)}catch(o){if(n.issues.push(Lt(o)),o instanceof Te){for(let a of o.message.split(`
|
|
239
|
+
`))n.stderr.push(a);return n.toResult(o.exitCode)}return n.stderr.push(o instanceof Error?o.message:String(o)),n.toResult(70)}});var px=new Set([...pn,"archive_confirmation","verify_failures","check_epoch","classic_profile","classic_migration","bound_branch"]),rh=new Set(Ze.filter(t=>!px.has(t))),il={workflow:["full","hotfix","tweak"],phase:["open","design","build","verify","archive"],context_compression:["off","beta"],build_mode:["subagent-driven-development","executing-plans","direct","autonomous"],build_pause:["null","plan-ready"],subagent_dispatch:["null","confirmed"],tdd_mode:["tdd","direct"],review_mode:["off","standard","thorough"],isolation:["current","branch","worktree"],verify_mode:["light","full"],auto_transition:["true","false"],verify_result:["pending","pass","fail"],branch_status:["pending","handled"],archive_confirmation:["pending","confirmed"],archived:["true","false"],direct_override:["true","false"],classic_profile:["full","hotfix","tweak"],classic_migration:["1"]};var hx=`
|
|
240
240
|
Options: --json (machine-readable output), --help
|
|
241
241
|
JSON: one object with command and exitCode; data, stdout, stderr, summary and next are optional.
|
|
242
242
|
Use exitCode for success; do not parse human-readable stdout. Help text is in stdout in JSON mode.
|
|
243
|
-
`;function ih(t,e){let n=e.indexOf("--"),r=n<0?e:e.slice(0,n);if(!r.includes("--help")&&!r.includes("-h"))return;let i={check:["comet check run <change> <build|verify> [--local] [--incremental] [--cwd <path>] [--timeout-ms <ms>] -- <program> [args...]","comet check rerun <change> <build|verify>","--local opts deterministic local checks into same-input reuse; other checks are single-use.","--incremental records phase-local evidence: guard previews accept it, --apply requires a full rerun.","Arguments after -- belong to the child. Windows batch arguments containing shell syntax are rejected.","","Executes a program for an active change and stores its log and input-bound evidence.","--local is not a location switch: all checks execute locally. It asserts deterministic inputs.","Use --local only when no network, external state or untracked ignored inputs affect the result.","Default evidence is single-use; reusable evidence requires matching inputs, environment and log.","--cwd: relative to the project root; default is the invocation directory; must stay inside the project.","Guard reuses evidence only when its cwd matches the guard invocation directory, or the command is declared with that cwd in a v2 check policy.","--timeout-ms: default 300000; integer range 1..3600000.","Place Comet options, including --json, before --. Child --help and --json after -- are forwarded.","","Result: data.scope, data.argv, data.cwd, data.exitCode, data.logRef, data.reusable; data.reused is optional.","Exit: 0 = success with stable inputs; child failures propagate; timeout = 124; invalid invocation/runtime error = 70.","A child exit of 0 with changed inputs returns exitCode 1. Use top-level exitCode, not data.exitCode.","On failure inspect data.logRef or stderr, fix the cause, then rerun. Recovery revalidates local evidence.","rerun repeats the latest Runtime-recorded argv, cwd, timeout and reuse tier without reconstructing shell syntax.","Optional .comet/check-policy.json binds declared deterministic commands by exact argv and cwd.",'A v1 single-command object stays valid; v2 {"commands":[...]} scopes each command separately.',"Editing one v2 command entry invalidates only that command's evidence; unmatched commands stay conservative.",'Default inputs are the working-tree files. Declare git: "all" for builds that read HEAD or the index,','env variable names whose values affect the result, and taskCheckboxes: "include" when completion marks matter.',"files accept literal paths and * ? ** globs; a new file matching a glob is checked without re-declaring.","Declare every real input; do not infer dependencies from the current diff.",'Policy example: {"version":2,"commands":[{"argv":["node","scripts/build.mjs"],"cwd":".","files":["src/**","package.json"],"git":"all"},{"argv":["node","--test"],"cwd":".","files":["src/**","test/**"],"taskCheckboxes":"ignore"}]}',"Build evidence does not substitute for verify evidence. A successful check does not advance the phase.","","Examples: (replace demo with your active change; these commands execute code)"," comet check run demo verify --json -- node --test"," comet check run demo build --local --cwd . -- npm run build"," comet check rerun demo build"],state:["comet state <command> [args]","init <change-name> <full|hotfix|tweak> [--isolation <current|branch|worktree>]","get <change-name> <field>","set <change-name> <field> <value> [<field> <value> ...]","complete-design <change-name> --design-doc <repo-relative-ref>","transition <change-name> <event>","check <change-name> <phase> [--recover] [--details]","scale <change-name>","artifacts <change-name>","record-check <change-name> <build|verify> --command <text> --exit-code <int> [--cwd <path>]","task-checkoff <file> <task-text>","tasks <change-name> [--assign-ids]","task-complete <change-name> <task-id> --expect <revision>","sync-plan <change-name>","checkpoint <change-name> [--file <json>]","delivery <change-name> [--file <json> | --verify]","select <change-name> | rebind <change-name> | next <change-name>","current | clear-selection","","Start with current or next <change-name> to inspect workflow guidance.","Advanced writes: init, set, transition, task-checkoff, select, rebind, clear-selection.","Use comet state <command> --help for details. --recover is for cold recovery, not normal progression.","After explicit design confirmation, complete-design registers the reference, refreshes handoff, and applies the guard; interrupted retries retain completed work.","Use data.artifactRefs for state references and task-authority markers; absolute paths are for file operations."],guard:["comet guard <change-name> <open|design|build|verify|archive> [--apply]","Validates phase requirements; --apply advances the phase after all checks pass.","Without --apply the phase stays unchanged, but this is NOT a read-only preview:","Build validation may execute a detected build and write evidence/logs.","Preview does not consume single-use evidence. Successful phase advancement consumes it atomically.","Failed or repeated previews preserve evidence; changed inputs still require a new check.","Do not poll guard for status. Use comet state next <change-name> for guidance.","On failure follow the reported next action; do not blindly retry side-effecting checks.","","Examples:"," comet guard demo build --apply --json"," comet state next demo --json"],handoff:["comet handoff <change-name> design --write [--full]","comet handoff <change-name> --hash-only"],archive:["comet archive <change-name> [--dry-run]"],validate:["comet classic validate <change-name>"],workspace:["comet classic workspace prepare <change-name> --isolation <current|branch|worktree> [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]","comet classic workspace resolve <change-name>"]},s={current:["comet state current","Reports the selected Classic change. Does not advance the phase."],next:["comet state next <change-name>","Reports the next workflow action. Does not execute build or verification checks."],select:["comet state select <change-name>","Writes the current change selection used by workflow routing."],rebind:["comet state rebind <change-name>","Updates the change branch binding to the current Git branch after validation."],"clear-selection":["comet state clear-selection","Clears the current change selection; does not delete change artifacts."],init:["comet state init <change-name> <full|hotfix|tweak> [--isolation <current|branch|worktree>]","Creates Classic workflow state. Follow the Open workflow for required user decisions."],scale:["comet state scale <change-name>","Reports a verification recommendation without changing verify_mode.","JSON: data.recommendation, data.selected and data.metrics. Scale is not a risk assessment.","Preserve an existing selection; record a new decision explicitly with state set when needed."],artifacts:["comet state artifacts <change-name>","Inspects the OpenSpec apply dependency closure, including dependencies of already-complete artifacts.","JSON: data.source, required, skipped, designRequired, files and problems. This does not execute implementation or verification.","Optional design is omitted only when the active schema excludes it from the required closure.","Skipped specs require explicit skip_specs: true, upstream support and no conflicting spec files.","Legacy changes without .openspec.yaml retain the existing Classic artifact requirements."],"task-checkoff":["comet state task-checkoff <file> <task-text>","Checks that exactly one matching task is already checked. Does not write the task file or execute the task."],tasks:["comet state tasks <change-name> [--assign-ids]","Reads tasks.md as the task completion authority. Fenced examples are excluded.","--assign-ids persists IDs for legacy/new tasks in Open, Design or Build; existing IDs remain unchanged.","Assign IDs before generating the design handoff and plan. ID assignment changes task requirements.","JSON: data.authority, data.revision, data.needsIds, data.tasks and data.progress.","Each task has id, text, completed and line. Never use line/order as task identity.","Example: comet state tasks demo --assign-ids --json"],"task-complete":["comet state task-complete <change-name> <task-id> --expect <revision>","Records accepted task completion during Build; does not execute or independently verify work.","Use the revision returned by state tasks. Changed requirements reject the write; refresh and reassess the task.","Writes tasks.md under the state lock and synchronizes explicitly ID-mapped legacy plan checkboxes. Retries repair interrupted projection writes.","Reconcile code, checks and review evidence before recording completion; unchecked does not mean unimplemented.","Unmapped legacy items are preserved and reported as mapping-required; never match tasks by position or wording."],"sync-plan":["comet state sync-plan <change-name>","Synchronizes legacy plan checkboxes from tasks.md by explicit comet-task IDs; does not execute or accept work.","Rejects missing or unknown plan IDs. Reconcile extra requirements into tasks.md before mapping.","New plans should reference task IDs without a second completion checklist."],checkpoint:["comet state checkpoint <change-name> [--file <json>]","Reads a structured coordination checkpoint, or records an explicitly bounded work package during Build.","Input: taskIds, revision, stage, sessionId, evidence, unresolved, reviewRounds.","Include schemaVersion: 1. JSON state is .comet/coordination.json, separate from the Engine checkpoint.","Stages: implementing|task-review|checkoff|done|blocked. Evidence is a coordination record, not automatic acceptance.","Runtime checks task IDs and revision and renders subagent-progress.md. Do not maintain its projection manually."],delivery:["comet state delivery <change-name> [--file <json> | --verify]","Reads delivery authorization and observed progress, or records the user-authorized local|push|pr action.","Input: action, targetBranch, optional remote, commit and prUrl. Recording never performs remote writes.","First authorization requires Archive with passing verification before archival. Missing legacy authorization is never inferred.","Resume only authorized unfinished steps; supplied commit or PR text alone does not prove delivery.","--verify performs bounded read-only remote/PR verification; normal entry never contacts the network."],get:["comet state get <change-name> <field>","Reads one stored field. The field value is returned in stdout, including in JSON mode.",`Fields: ${[...Qe,...pn].join(", ")}`,"Example: comet state get demo phase --json"],set:["comet state set <change-name> <field> <value> [<field> <value> ...]","Advanced: validates all fields, then commits one atomic state update and reconciles Runtime state.","Invalid values or duplicate fields reject the whole update. Do not bypass workflow confirmations.","JSON: data.change and data.updated contain the committed field values.","Writable fields (enum values shown where applicable):",...[...rh].map(c=>` ${c}${il[c]?`: ${il[c].join("|")}`:c==="language"?": en|zh-CN":""}`),"Other Runtime-owned fields cannot be set manually. Artifact paths must stay within the project.","Example: comet state set demo verify_mode full","Example: comet state set demo build_mode executing-plans tdd_mode direct review_mode standard --json"],check:["comet state check <change-name> <open|design|build|verify|archive> [--recover] [--details]","Checks phase entry requirements; this is not a build/test execution command.","--recover is for cold recovery after context loss, not normal phase progression.","Recovery revalidates reusable local evidence and invalidates stale, damaged or single-use evidence.","It preserves completed work; resume from the checkpoint and rerun required checks before progressing.","JSON entry data includes layout, configuration, configurationReadiness, nextAction, compact taskState, planMapping and checks.","--recover additionally revalidates evidence and includes checkpoint references; --details expands tasks and checkpoint content.","Reconcile existing implementation and acceptance before dispatching work; unchecked tasks are not proof of missing implementation.","Read fresh state after changing configuration or advancing phases; do not reuse an earlier entry snapshot.","","Examples:"," comet state check demo build --json"," comet state check demo build --recover --json"],"record-check":["comet state record-check <change> <build|verify> --command <text> --exit-code <int> [--cwd <path>]","Advanced: writes a manual attestation; does not execute the command.","A manual attestation cannot satisfy Runtime build/verify evidence requirements, even with exit code 0.","Use comet check run to execute a check and obtain evidence that guard can validate.","--cwd: relative to project root, defaults to .; must stay inside the project.","","Examples:",' comet state record-check demo verify --command "external test run" --exit-code 1'," comet check run demo verify --json -- node --test"],transition:["comet state transition <change-name> <event>",`Events: ${Fp.join(", ")}`,"Advanced: applies a state-machine event and writes workflow state. Required confirmations still apply.","This is not a substitute for the workflow Skill or phase guard. Use state next for the next action."]},o=r.find(c=>!c.startsWith("-")),a=t==="state"&&o&&s[o]||i[t];return a?`Usage: ${a.join(`
|
|
243
|
+
`;function ih(t,e){let n=e.indexOf("--"),r=n<0?e:e.slice(0,n);if(!r.includes("--help")&&!r.includes("-h"))return;let i={check:["comet check run <change> <build|verify> [--local] [--incremental] [--cwd <path>] [--timeout-ms <ms>] -- <program> [args...]","comet check rerun <change> <build|verify>","--local opts deterministic local checks into same-input reuse; other checks are single-use.","--incremental records phase-local evidence: guard previews accept it, --apply requires a full rerun.","Arguments after -- belong to the child. Windows batch arguments containing shell syntax are rejected.","","Executes a program for an active change and stores its log and input-bound evidence.","--local is not a location switch: all checks execute locally. It asserts deterministic inputs.","Use --local only when no network, external state or untracked ignored inputs affect the result.","Default evidence is single-use; reusable evidence requires matching inputs, environment and log.","--cwd: relative to the project root; default is the invocation directory; must stay inside the project.","Guard reuses evidence only when its cwd matches the guard invocation directory, or the command is declared with that cwd in a v2 check policy.","--timeout-ms: default 300000; integer range 1..3600000.","Place Comet options, including --json, before --. Child --help and --json after -- are forwarded.","","Result: data.scope, data.argv, data.cwd, data.exitCode, data.logRef, data.reusable; data.reused is optional.","Exit: 0 = success with stable inputs; child failures propagate; timeout = 124; invalid invocation/runtime error = 70.","A child exit of 0 with changed inputs returns exitCode 1. Use top-level exitCode, not data.exitCode.","On failure inspect data.logRef or stderr, fix the cause, then rerun. Recovery revalidates local evidence.","rerun repeats the latest Runtime-recorded argv, cwd, timeout and reuse tier without reconstructing shell syntax.","Optional .comet/check-policy.json binds declared deterministic commands by exact argv and cwd.",'A v1 single-command object stays valid; v2 {"commands":[...]} scopes each command separately.',"Editing one v2 command entry invalidates only that command's evidence; unmatched commands stay conservative.",'Default inputs are the working-tree files. Declare git: "all" for builds that read HEAD or the index,','env variable names whose values affect the result, and taskCheckboxes: "include" when completion marks matter.',"files accept literal paths and * ? ** globs; a new file matching a glob is checked without re-declaring.","Declare every real input; do not infer dependencies from the current diff.",'Policy example: {"version":2,"commands":[{"argv":["node","scripts/build.mjs"],"cwd":".","files":["src/**","package.json"],"git":"all"},{"argv":["node","--test"],"cwd":".","files":["src/**","test/**"],"taskCheckboxes":"ignore"}]}',"Build evidence does not substitute for verify evidence. A successful check does not advance the phase.","","Examples: (replace demo with your active change; these commands execute code)"," comet check run demo verify --json -- node --test"," comet check run demo build --local --cwd . -- npm run build"," comet check rerun demo build"],state:["comet state <command> [args]","init <change-name> <full|hotfix|tweak> [--isolation <current|branch|worktree>]","get <change-name> <field>","set <change-name> <field> <value> [<field> <value> ...]","complete-design <change-name> --design-doc <repo-relative-ref>","transition <change-name> <event>","check <change-name> <phase> [--recover] [--details]","scale <change-name>","artifacts <change-name>","record-check <change-name> <build|verify> --command <text> --exit-code <int> [--cwd <path>]","task-checkoff <file> <task-text>","tasks <change-name> [--assign-ids]","task-complete <change-name> <task-id> --expect <revision>","sync-plan <change-name>","checkpoint <change-name> [--file <json>]","delivery <change-name> [--file <json> | --verify]","select <change-name> | rebind <change-name> | next <change-name>","current | clear-selection","","Start with current or next <change-name> to inspect workflow guidance.","Advanced writes: init, set, transition, task-checkoff, select, rebind, clear-selection.","Use comet state <command> --help for details. --recover is for cold recovery, not normal progression.","After explicit design confirmation, complete-design registers the reference, refreshes handoff, and applies the guard; interrupted retries retain completed work.","Use data.artifactRefs for state references and task-authority markers; absolute paths are for file operations."],guard:["comet guard <change-name> <open|design|build|verify|archive> [--apply]","Validates phase requirements; --apply advances the phase after all checks pass.","Without --apply the phase stays unchanged, but this is NOT a read-only preview:","Build validation may execute a detected build and write evidence/logs.","Preview does not consume single-use evidence. Successful phase advancement consumes it atomically.","Failed or repeated previews preserve evidence; changed inputs still require a new check.","Do not poll guard for status. Use comet state next <change-name> for guidance.","On failure follow the reported next action; do not blindly retry side-effecting checks.","","Examples:"," comet guard demo build --apply --json"," comet state next demo --json"],handoff:["comet handoff <change-name> design --write [--full]","comet handoff <change-name> --hash-only"],archive:["comet archive <change-name> [--dry-run]"],validate:["comet classic validate <change-name>"],workspace:["comet classic workspace prepare <change-name> --isolation <current|branch|worktree> [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]","comet classic workspace resolve <change-name>"]},s={current:["comet state current","Reports the selected Classic change. Does not advance the phase."],next:["comet state next <change-name>","Reports the next workflow action. Does not execute build or verification checks."],select:["comet state select <change-name>","Writes the current change selection used by workflow routing."],rebind:["comet state rebind <change-name>","Updates the change branch binding to the current Git branch after validation."],"clear-selection":["comet state clear-selection","Clears the current change selection; does not delete change artifacts."],init:["comet state init <change-name> <full|hotfix|tweak> [--isolation <current|branch|worktree>]","Creates Classic workflow state. Follow the Open workflow for required user decisions."],scale:["comet state scale <change-name>","Reports a verification recommendation without changing verify_mode.","JSON: data.recommendation, data.selected and data.metrics. Scale is not a risk assessment.","Preserve an existing selection; record a new decision explicitly with state set when needed."],artifacts:["comet state artifacts <change-name>","Inspects the OpenSpec apply dependency closure, including dependencies of already-complete artifacts.","JSON: data.source, required, skipped, designRequired, files and problems. This does not execute implementation or verification.","Optional design is omitted only when the active schema excludes it from the required closure.","Skipped specs require explicit skip_specs: true, upstream support and no conflicting spec files.","Legacy changes without .openspec.yaml retain the existing Classic artifact requirements."],"task-checkoff":["comet state task-checkoff <file> <task-text>","Checks that exactly one matching task is already checked. Does not write the task file or execute the task."],tasks:["comet state tasks <change-name> [--assign-ids]","Reads tasks.md as the task completion authority. Fenced examples are excluded.","--assign-ids persists IDs for legacy/new tasks in Open, Design or Build; existing IDs remain unchanged.","Assign IDs before generating the design handoff and plan. ID assignment changes task requirements.","JSON: data.authority, data.revision, data.needsIds, data.tasks and data.progress.","Each task has id, text, completed and line. Never use line/order as task identity.","Example: comet state tasks demo --assign-ids --json"],"task-complete":["comet state task-complete <change-name> <task-id> --expect <revision>","Records accepted task completion during Build; does not execute or independently verify work.","Use the revision returned by state tasks. Changed requirements reject the write; refresh and reassess the task.","Writes tasks.md under the state lock and synchronizes explicitly ID-mapped legacy plan checkboxes. Retries repair interrupted projection writes.","Reconcile code, checks and review evidence before recording completion; unchecked does not mean unimplemented.","Unmapped legacy items are preserved and reported as mapping-required; never match tasks by position or wording."],"sync-plan":["comet state sync-plan <change-name>","Synchronizes legacy plan checkboxes from tasks.md by explicit comet-task IDs; does not execute or accept work.","Rejects missing or unknown plan IDs. Reconcile extra requirements into tasks.md before mapping.","New plans should reference task IDs without a second completion checklist."],checkpoint:["comet state checkpoint <change-name> [--file <json>]","Reads a structured coordination checkpoint, or records an explicitly bounded work package during Build.","Input: taskIds, revision, stage, sessionId, evidence, unresolved, reviewRounds.","Include schemaVersion: 1. JSON state is .comet/coordination.json, separate from the Engine checkpoint.","Stages: implementing|task-review|checkoff|done|blocked. Evidence is a coordination record, not automatic acceptance.","Runtime checks task IDs and revision and renders subagent-progress.md. Do not maintain its projection manually."],delivery:["comet state delivery <change-name> [--file <json> | --verify]","Reads delivery authorization and observed progress, or records the user-authorized local|push|pr action.","Input: action, targetBranch, optional remote, commit and prUrl. Recording never performs remote writes.","First authorization requires Archive with passing verification before archival. Missing legacy authorization is never inferred.","Resume only authorized unfinished steps; supplied commit or PR text alone does not prove delivery.","--verify performs bounded read-only remote/PR verification; normal entry never contacts the network."],get:["comet state get <change-name> <field>","Reads one stored field. The field value is returned in stdout, including in JSON mode.",`Fields: ${[...Ze,...pn].join(", ")}`,"Example: comet state get demo phase --json"],set:["comet state set <change-name> <field> <value> [<field> <value> ...]","Advanced: validates all fields, then commits one atomic state update and reconciles Runtime state.","Invalid values or duplicate fields reject the whole update. Do not bypass workflow confirmations.","JSON: data.change and data.updated contain the committed field values.","Writable fields (enum values shown where applicable):",...[...rh].map(c=>` ${c}${il[c]?`: ${il[c].join("|")}`:c==="language"?": en|zh-CN":""}`),"Other Runtime-owned fields cannot be set manually. Artifact paths must stay within the project.","Example: comet state set demo verify_mode full","Example: comet state set demo build_mode executing-plans tdd_mode direct review_mode standard --json"],check:["comet state check <change-name> <open|design|build|verify|archive> [--recover] [--details]","Checks phase entry requirements; this is not a build/test execution command.","--recover is for cold recovery after context loss, not normal phase progression.","Recovery revalidates reusable local evidence and invalidates stale, damaged or single-use evidence.","It preserves completed work; resume from the checkpoint and rerun required checks before progressing.","JSON entry data includes layout, configuration, configurationReadiness, nextAction, compact taskState, planMapping and checks.","--recover additionally revalidates evidence and includes checkpoint references; --details expands tasks and checkpoint content.","Reconcile existing implementation and acceptance before dispatching work; unchecked tasks are not proof of missing implementation.","Read fresh state after changing configuration or advancing phases; do not reuse an earlier entry snapshot.","","Examples:"," comet state check demo build --json"," comet state check demo build --recover --json"],"record-check":["comet state record-check <change> <build|verify> --command <text> --exit-code <int> [--cwd <path>]","Advanced: writes a manual attestation; does not execute the command.","A manual attestation cannot satisfy Runtime build/verify evidence requirements, even with exit code 0.","Use comet check run to execute a check and obtain evidence that guard can validate.","--cwd: relative to project root, defaults to .; must stay inside the project.","","Examples:",' comet state record-check demo verify --command "external test run" --exit-code 1'," comet check run demo verify --json -- node --test"],transition:["comet state transition <change-name> <event>",`Events: ${Fp.join(", ")}`,"Advanced: applies a state-machine event and writes workflow state. Required confirmations still apply.","This is not a substitute for the workflow Skill or phase guard. Use state next for the next action."]},o=r.find(c=>!c.startsWith("-")),a=t==="state"&&o&&s[o]||i[t];return a?`Usage: ${a.join(`
|
|
244
244
|
`)}
|
|
245
|
-
${
|
|
246
|
-
`:void 0}function
|
|
247
|
-
`,...e.envelope===void 0?{}:{envelope:e.envelope}}}async function sh(t,e,n=process.argv.slice(2)){let r=n.indexOf("--"),i=l=>r<0||l<r,s=n.some((l,u)=>i(u)&&l==="--json"),o=n.filter((l,u)=>!i(u)||l!=="--json"),a;try{let l=ih(t,o);a=l?{exitCode:0,stdout:l}:await e(o,{json:s})}catch(l){a={exitCode:70,stderr:l instanceof Error?l.message:String(l),data:{issues:[
|
|
245
|
+
${hx}Command placeholders must be replaced with actual values.
|
|
246
|
+
`:void 0}function gx(t,e){return{exitCode:e.exitCode,stdout:JSON.stringify({command:t,exitCode:e.exitCode,agent:fc(e.data),...e.data===void 0?{}:{data:e.data},...e.envelope===void 0?{}:{summary:e.envelope.summary,...e.envelope.next===void 0?{}:{next:e.envelope.next},...e.envelope.user_message===void 0?{}:{user_message:e.envelope.user_message}},...e.stdout===void 0?{}:{stdout:e.stdout},...e.stderr===void 0?{}:{stderr:e.stderr}})+`
|
|
247
|
+
`,...e.envelope===void 0?{}:{envelope:e.envelope}}}async function sh(t,e,n=process.argv.slice(2)){let r=n.indexOf("--"),i=l=>r<0||l<r,s=n.some((l,u)=>i(u)&&l==="--json"),o=n.filter((l,u)=>!i(u)||l!=="--json"),a;try{let l=ih(t,o);a=l?{exitCode:0,stdout:l}:await e(o,{json:s})}catch(l){a={exitCode:70,stderr:l instanceof Error?l.message:String(l),data:{issues:[Lt(l)]}}}let c=s?gx(t,a):a;return c.stdout&&process.stdout.write(c.stdout),c.stderr&&process.stderr.write(c.stderr+(c.stderr.endsWith(`
|
|
248
248
|
`)?"":`
|
|
249
249
|
`)),c.exitCode}process.exitCode=await sh("guard",nh);
|