@rpamis/comet 0.4.0-beta.13 → 0.4.0-beta.14
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/assets/manifest.json +1 -1
- package/assets/skills/comet/scripts/comet-archive.mjs +66 -66
- package/assets/skills/comet/scripts/comet-entry-runtime.mjs +1 -1
- package/assets/skills/comet/scripts/comet-guard.mjs +88 -88
- package/assets/skills/comet/scripts/comet-handoff.mjs +68 -68
- package/assets/skills/comet/scripts/comet-hook-guard.mjs +62 -62
- package/assets/skills/comet/scripts/comet-hook-router.mjs +64 -64
- package/assets/skills/comet/scripts/comet-resume-probe.mjs +55 -55
- package/assets/skills/comet/scripts/comet-runtime.mjs +134 -134
- package/assets/skills/comet/scripts/comet-state.mjs +67 -67
- package/assets/skills/comet/scripts/comet-yaml-validate.mjs +6 -6
- package/assets/skills/comet-native/scripts/comet-native-archive.mjs +39 -39
- package/assets/skills/comet-native/scripts/comet-native-check.mjs +45 -45
- package/assets/skills/comet-native/scripts/comet-native-checkpoint.mjs +35 -35
- package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +33 -33
- package/assets/skills/comet-native/scripts/comet-native-evidence.mjs +7 -7
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +7 -7
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +6 -6
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +44 -44
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +27 -27
- package/assets/skills/comet-native/scripts/comet-native-receipt.mjs +24 -24
- package/assets/skills/comet-native/scripts/comet-native-root.mjs +31 -31
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +43 -43
- package/assets/skills/comet-native/scripts/comet-native-select.mjs +41 -41
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +7 -7
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +51 -51
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +39 -39
- package/dist/app/commands/i18n.d.ts +1 -1
- package/dist/app/commands/i18n.d.ts.map +1 -1
- package/dist/app/commands/i18n.js +90 -0
- package/dist/app/commands/i18n.js.map +1 -1
- package/dist/app/commands/init.d.ts.map +1 -1
- package/dist/app/commands/init.js +2 -0
- package/dist/app/commands/init.js.map +1 -1
- package/dist/app/commands/project-scope-selection.d.ts +2 -1
- package/dist/app/commands/project-scope-selection.d.ts.map +1 -1
- package/dist/app/commands/project-scope-selection.js +5 -7
- package/dist/app/commands/project-scope-selection.js.map +1 -1
- package/dist/app/commands/uninstall.d.ts +6 -0
- package/dist/app/commands/uninstall.d.ts.map +1 -1
- package/dist/app/commands/uninstall.js +197 -110
- package/dist/app/commands/uninstall.js.map +1 -1
- package/dist/app/commands/update.d.ts.map +1 -1
- package/dist/app/commands/update.js +39 -1
- package/dist/app/commands/update.js.map +1 -1
- package/dist/domains/comet-classic/classic-layout-initialization.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-layout-initialization.js +8 -4
- package/dist/domains/comet-classic/classic-layout-initialization.js.map +1 -1
- package/dist/domains/comet-classic/classic-layout.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-layout.js +1 -0
- package/dist/domains/comet-classic/classic-layout.js.map +1 -1
- package/dist/domains/comet-entry/init-workflow.d.ts.map +1 -1
- package/dist/domains/comet-entry/init-workflow.js +2 -3
- package/dist/domains/comet-entry/init-workflow.js.map +1 -1
- package/dist/domains/integrations/openspec.d.ts.map +1 -1
- package/dist/domains/integrations/openspec.js +5 -2
- package/dist/domains/integrations/openspec.js.map +1 -1
- package/dist/domains/skill/platform-install.d.ts.map +1 -1
- package/dist/domains/skill/platform-install.js +32 -0
- package/dist/domains/skill/platform-install.js.map +1 -1
- package/dist/domains/skill/uninstall.d.ts +6 -2
- package/dist/domains/skill/uninstall.d.ts.map +1 -1
- package/dist/domains/skill/uninstall.js +142 -18
- package/dist/domains/skill/uninstall.js.map +1 -1
- package/dist/domains/workflow-contract/contained-atomic-write.d.ts +3 -0
- package/dist/domains/workflow-contract/contained-atomic-write.d.ts.map +1 -1
- package/dist/domains/workflow-contract/contained-atomic-write.js +15 -2
- package/dist/domains/workflow-contract/contained-atomic-write.js.map +1 -1
- package/dist/domains/workflow-contract/index.d.ts +1 -1
- package/dist/domains/workflow-contract/index.d.ts.map +1 -1
- package/dist/domains/workflow-contract/index.js +1 -1
- package/dist/domains/workflow-contract/index.js.map +1 -1
- package/dist/domains/workflow-contract/project-config-reader.d.ts +2 -0
- package/dist/domains/workflow-contract/project-config-reader.d.ts.map +1 -1
- package/dist/domains/workflow-contract/project-config-reader.js.map +1 -1
- package/dist/domains/workflow-contract/project-config-writer.d.ts.map +1 -1
- package/dist/domains/workflow-contract/project-config-writer.js +3 -2
- package/dist/domains/workflow-contract/project-config-writer.js.map +1 -1
- package/dist/domains/workflow-contract/project-config.d.ts +1 -0
- package/dist/domains/workflow-contract/project-config.d.ts.map +1 -1
- package/dist/domains/workflow-contract/project-config.js +9 -4
- package/dist/domains/workflow-contract/project-config.js.map +1 -1
- package/dist/platform/install/platforms.d.ts +2 -0
- package/dist/platform/install/platforms.d.ts.map +1 -1
- package/dist/platform/install/platforms.js +1 -0
- package/dist/platform/install/platforms.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,40 +1,40 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cometCreateRequire } from 'module';
|
|
3
3
|
const require = __cometCreateRequire(import.meta.url);
|
|
4
|
-
var
|
|
5
|
-
`)}};Ei.defaultYaml={explicit:!1,version:"1.2"};Ei.defaultTags={"!!":"tag:yaml.org,2002:"};xu.Directives=Ei});var Ur=v(Ri=>{"use strict";var Pu=M(),
|
|
6
|
-
`)?
|
|
4
|
+
var xg=Object.create;var ua=Object.defineProperty;var Pg=Object.getOwnPropertyDescriptor;var Og=Object.getOwnPropertyNames;var $g=Object.getPrototypeOf,Ig=Object.prototype.hasOwnProperty;var Br=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var he=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(i){throw n=[i],i}};var v=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},Ag=(e,t)=>{for(var n in t)ua(e,n,{get:t[n],enumerable:!0})},Ng=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Og(t))!Ig.call(e,r)&&r!==n&&ua(e,r,{get:()=>t[r],enumerable:!(i=Pg(t,r))||i.enumerable});return e};var ft=(e,t,n)=>(n=e!=null?xg($g(e)):{},Ng(t||!e||!e.__esModule?ua(n,"default",{value:e,enumerable:!0}):n,e));var M=v(ae=>{"use strict";var fa=Symbol.for("yaml.alias"),yu=Symbol.for("yaml.document"),Wr=Symbol.for("yaml.map"),vu=Symbol.for("yaml.pair"),da=Symbol.for("yaml.scalar"),Hr=Symbol.for("yaml.seq"),dt=Symbol.for("yaml.node.type"),Lg=e=>!!e&&typeof e=="object"&&e[dt]===fa,Mg=e=>!!e&&typeof e=="object"&&e[dt]===yu,qg=e=>!!e&&typeof e=="object"&&e[dt]===Wr,Dg=e=>!!e&&typeof e=="object"&&e[dt]===vu,bu=e=>!!e&&typeof e=="object"&&e[dt]===da,Fg=e=>!!e&&typeof e=="object"&&e[dt]===Hr;function Cu(e){if(e&&typeof e=="object")switch(e[dt]){case Wr:case Hr:return!0}return!1}function Bg(e){if(e&&typeof e=="object")switch(e[dt]){case fa:case Wr:case da:case Hr:return!0}return!1}var Wg=e=>(bu(e)||Cu(e))&&!!e.anchor;ae.ALIAS=fa;ae.DOC=yu;ae.MAP=Wr;ae.NODE_TYPE=dt;ae.PAIR=vu;ae.SCALAR=da;ae.SEQ=Hr;ae.hasAnchor=Wg;ae.isAlias=Lg;ae.isCollection=Cu;ae.isDocument=Mg;ae.isMap=qg;ae.isNode=Bg;ae.isPair=Dg;ae.isScalar=bu;ae.isSeq=Fg});var Si=v(ma=>{"use strict";var ie=M(),ke=Symbol("break visit"),ku=Symbol("skip children"),et=Symbol("remove node");function Kr(e,t){let n=Su(t);ie.isDocument(e)?qn(null,e.contents,n,Object.freeze([e]))===et&&(e.contents=null):qn(null,e,n,Object.freeze([]))}Kr.BREAK=ke;Kr.SKIP=ku;Kr.REMOVE=et;function qn(e,t,n,i){let r=Eu(e,t,n,i);if(ie.isNode(r)||ie.isPair(r))return Ru(e,i,r),qn(e,r,n,i);if(typeof r!="symbol"){if(ie.isCollection(t)){i=Object.freeze(i.concat(t));for(let s=0;s<t.items.length;++s){let o=qn(s,t.items[s],n,i);if(typeof o=="number")s=o-1;else{if(o===ke)return ke;o===et&&(t.items.splice(s,1),s-=1)}}}else if(ie.isPair(t)){i=Object.freeze(i.concat(t));let s=qn("key",t.key,n,i);if(s===ke)return ke;s===et&&(t.key=null);let o=qn("value",t.value,n,i);if(o===ke)return ke;o===et&&(t.value=null)}}return r}async function Jr(e,t){let n=Su(t);ie.isDocument(e)?await Dn(null,e.contents,n,Object.freeze([e]))===et&&(e.contents=null):await Dn(null,e,n,Object.freeze([]))}Jr.BREAK=ke;Jr.SKIP=ku;Jr.REMOVE=et;async function Dn(e,t,n,i){let r=await Eu(e,t,n,i);if(ie.isNode(r)||ie.isPair(r))return Ru(e,i,r),Dn(e,r,n,i);if(typeof r!="symbol"){if(ie.isCollection(t)){i=Object.freeze(i.concat(t));for(let s=0;s<t.items.length;++s){let o=await Dn(s,t.items[s],n,i);if(typeof o=="number")s=o-1;else{if(o===ke)return ke;o===et&&(t.items.splice(s,1),s-=1)}}}else if(ie.isPair(t)){i=Object.freeze(i.concat(t));let s=await Dn("key",t.key,n,i);if(s===ke)return ke;s===et&&(t.key=null);let o=await Dn("value",t.value,n,i);if(o===ke)return ke;o===et&&(t.value=null)}}return r}function Su(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Eu(e,t,n,i){if(typeof n=="function")return n(e,t,i);if(ie.isMap(t))return n.Map?.(e,t,i);if(ie.isSeq(t))return n.Seq?.(e,t,i);if(ie.isPair(t))return n.Pair?.(e,t,i);if(ie.isScalar(t))return n.Scalar?.(e,t,i);if(ie.isAlias(t))return n.Alias?.(e,t,i)}function Ru(e,t,n){let i=t[t.length-1];if(ie.isCollection(i))i.items[e]=n;else if(ie.isPair(i))e==="key"?i.key=n:i.value=n;else if(ie.isDocument(i))i.contents=n;else{let r=ie.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}ma.visit=Kr;ma.visitAsync=Jr});var pa=v(xu=>{"use strict";var _u=M(),Hg=Si(),Kg={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Jg=e=>e.replace(/[!,[\]{}]/g,t=>Kg[t]),Ei=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),r=i.shift();switch(r){case"%TAG":{if(i.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[s,o]=i;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[s]=i;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 ${r}`,!0),!1}}tagName(t,n){if(t==="!")return"!";if(t[0]!=="!")return n(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(n(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&n("Verbatim tags must end with a >"),o)}let[,i,r]=t.match(/^(.*!)([^!]*)$/s);r||n(`The ${t} tag has no suffix`);let s=this.tags[i];if(s)try{return s+decodeURIComponent(r)}catch(o){return n(String(o)),null}return i==="!"?t:(n(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[n,i]of Object.entries(this.tags))if(t.startsWith(i))return n+Jg(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),r;if(t&&i.length>0&&_u.isNode(t.contents)){let s={};Hg.visit(t.contents,(o,a)=>{_u.isNode(a)&&a.tag&&(s[a.tag]=!0)}),r=Object.keys(s)}else r=[];for(let[s,o]of i)s==="!!"&&o==="tag:yaml.org,2002:"||(!t||r.some(a=>a.startsWith(o)))&&n.push(`%TAG ${s} ${o}`);return n.join(`
|
|
5
|
+
`)}};Ei.defaultYaml={explicit:!1,version:"1.2"};Ei.defaultTags={"!!":"tag:yaml.org,2002:"};xu.Directives=Ei});var Ur=v(Ri=>{"use strict";var Pu=M(),Ug=Si();function Vg(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(n)}return!0}function Ou(e){let t=new Set;return Ug.visit(e,{Value(n,i){i.anchor&&t.add(i.anchor)}}),t}function $u(e,t){for(let n=1;;++n){let i=`${e}${n}`;if(!t.has(i))return i}}function Yg(e,t){let n=[],i=new Map,r=null;return{onAnchor:s=>{n.push(s),r??(r=Ou(e));let o=$u(t,r);return r.add(o),o},setAnchors:()=>{for(let s of n){let o=i.get(s);if(typeof o=="object"&&o.anchor&&(Pu.isScalar(o.node)||Pu.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:i}}Ri.anchorIsValid=Vg;Ri.anchorNames=Ou;Ri.createNodeAnchors=Yg;Ri.findNewAnchor=$u});var ha=v(Iu=>{"use strict";function _i(e,t,n,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let r=0,s=i.length;r<s;++r){let o=i[r],a=_i(e,i,String(r),o);a===void 0?delete i[r]:a!==o&&(i[r]=a)}else if(i instanceof Map)for(let r of Array.from(i.keys())){let s=i.get(r),o=_i(e,i,r,s);o===void 0?i.delete(r):o!==s&&i.set(r,o)}else if(i instanceof Set)for(let r of Array.from(i)){let s=_i(e,i,r,r);s===void 0?i.delete(r):s!==r&&(i.delete(r),i.add(s))}else for(let[r,s]of Object.entries(i)){let o=_i(e,i,r,s);o===void 0?delete i[r]:o!==s&&(i[r]=o)}return e.call(t,n,i)}Iu.applyReviver=_i});var Nt=v(Nu=>{"use strict";var Gg=M();function Au(e,t,n){if(Array.isArray(e))return e.map((i,r)=>Au(i,String(r),n));if(e&&typeof e.toJSON=="function"){if(!n||!Gg.hasAnchor(e))return e.toJSON(t,n);let i={aliasCount:0,count:1,res:void 0};n.anchors.set(e,i),n.onCreate=s=>{i.res=s,delete n.onCreate};let r=e.toJSON(t,n);return n.onCreate&&n.onCreate(r),r}return typeof e=="bigint"&&!n?.keep?Number(e):e}Nu.toJS=Au});var Vr=v(ju=>{"use strict";var zg=ha(),Tu=M(),Xg=Nt(),ga=class{constructor(t){Object.defineProperty(this,Tu.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:n,maxAliasCount:i,onAnchor:r,reviver:s}={}){if(!Tu.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},a=Xg.toJS(this,"",o);if(typeof r=="function")for(let{count:c,res:l}of o.anchors.values())r(l,c);return typeof s=="function"?zg.applyReviver(s,{"":a},"",a):a}};ju.NodeBase=ga});var xi=v(Lu=>{"use strict";var Qg=Ur(),Zg=Si(),Fn=M(),ew=Vr(),tw=Nt(),wa=class extends ew.NodeBase{constructor(t){super(Fn.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;n?.aliasResolveCache?i=n.aliasResolveCache:(i=[],Zg.visit(t,{Node:(s,o)=>{(Fn.isAlias(o)||Fn.hasAnchor(o))&&i.push(o)}}),n&&(n.aliasResolveCache=i));let r;for(let s of i){if(s===this)break;s.anchor===this.source&&(r=s)}return r}toJSON(t,n){if(!n)return{source:this.source};let{anchors:i,doc:r,maxAliasCount:s}=n,o=this.resolve(r,n);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=i.get(o);if(a||(tw.toJS(o,null,n),a=i.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=Yr(r,o,i)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(t,n,i){let r=`*${this.source}`;if(t){if(Qg.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(t.implicitKey)return`${r} `}return r}};function Yr(e,t,n){if(Fn.isAlias(t)){let i=t.resolve(e),r=n&&i&&n.get(i);return r?r.count*r.aliasCount:0}else if(Fn.isCollection(t)){let i=0;for(let r of t.items){let s=Yr(e,r,n);s>i&&(i=s)}return i}else if(Fn.isPair(t)){let i=Yr(e,t.key,n),r=Yr(e,t.value,n);return Math.max(i,r)}return 1}Lu.Alias=wa});var X=v(ya=>{"use strict";var nw=M(),iw=Vr(),rw=Nt(),sw=e=>!e||typeof e!="function"&&typeof e!="object",Tt=class extends iw.NodeBase{constructor(t){super(nw.SCALAR),this.value=t}toJSON(t,n){return n?.keep?this.value:rw.toJS(this.value,t,n)}toString(){return String(this.value)}};Tt.BLOCK_FOLDED="BLOCK_FOLDED";Tt.BLOCK_LITERAL="BLOCK_LITERAL";Tt.PLAIN="PLAIN";Tt.QUOTE_DOUBLE="QUOTE_DOUBLE";Tt.QUOTE_SINGLE="QUOTE_SINGLE";ya.Scalar=Tt;ya.isScalarValue=sw});var Pi=v(qu=>{"use strict";var ow=xi(),mn=M(),Mu=X(),aw="tag:yaml.org,2002:";function cw(e,t,n){if(t){let i=n.filter(s=>s.tag===t),r=i.find(s=>!s.format)??i[0];if(!r)throw new Error(`Tag ${t} not found`);return r}return n.find(i=>i.identify?.(e)&&!i.format)}function lw(e,t,n){if(mn.isDocument(e)&&(e=e.contents),mn.isNode(e))return e;if(mn.isPair(e)){let u=n.schema[mn.MAP].createNode?.(n.schema,null,n);return u.items.push(e),u}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:r,onTagObj:s,schema:o,sourceObjects:a}=n,c;if(i&&e&&typeof e=="object"){if(c=a.get(e),c)return c.anchor??(c.anchor=r(e)),new ow.Alias(c.anchor);c={anchor:null,node:null},a.set(e,c)}t?.startsWith("!!")&&(t=aw+t.slice(2));let l=cw(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let u=new Mu.Scalar(e);return c&&(c.node=u),u}l=e instanceof Map?o[mn.MAP]:Symbol.iterator in Object(e)?o[mn.SEQ]:o[mn.MAP]}s&&(s(l),delete n.onTagObj);let f=l?.createNode?l.createNode(n.schema,e,n):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(n.schema,e,n):new Mu.Scalar(e);return t?f.tag=t:l.default||(f.tag=l.tag),c&&(c.node=f),f}qu.createNode=lw});var zr=v(Gr=>{"use strict";var uw=Pi(),tt=M(),fw=Vr();function va(e,t,n){let i=n;for(let r=t.length-1;r>=0;--r){let s=t[r];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=i,i=o}else i=new Map([[s,i]])}return uw.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Du=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,ba=class extends fw.NodeBase{constructor(t,n){super(t),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(t){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(n.schema=t),n.items=n.items.map(i=>tt.isNode(i)||tt.isPair(i)?i.clone(t):i),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(Du(t))this.add(n);else{let[i,...r]=t,s=this.get(i,!0);if(tt.isCollection(s))s.addIn(r,n);else if(s===void 0&&this.schema)this.set(i,va(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}deleteIn(t){let[n,...i]=t;if(i.length===0)return this.delete(n);let r=this.get(n,!0);if(tt.isCollection(r))return r.deleteIn(i);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}getIn(t,n){let[i,...r]=t,s=this.get(i,!0);return r.length===0?!n&&tt.isScalar(s)?s.value:s:tt.isCollection(s)?s.getIn(r,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!tt.isPair(n))return!1;let i=n.value;return i==null||t&&tt.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[n,...i]=t;if(i.length===0)return this.has(n);let r=this.get(n,!0);return tt.isCollection(r)?r.hasIn(i):!1}setIn(t,n){let[i,...r]=t;if(r.length===0)this.set(i,n);else{let s=this.get(i,!0);if(tt.isCollection(s))s.setIn(r,n);else if(s===void 0&&this.schema)this.set(i,va(this.schema,r,n));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}};Gr.Collection=ba;Gr.collectionFromPath=va;Gr.isEmptyPath=Du});var Oi=v(Xr=>{"use strict";var dw=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Ca(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var mw=(e,t,n)=>e.endsWith(`
|
|
6
|
+
`)?Ca(n,t):n.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
`+
|
|
9
|
-
`)n===
|
|
8
|
+
`+Ca(n,t):(e.endsWith(" ")?"":" ")+n;Xr.indentComment=Ca;Xr.lineComment=mw;Xr.stringifyComment=dw});var Bu=v($i=>{"use strict";var pw="flow",ka="block",Qr="quoted";function hw(e,t,n="flow",{indentAtStart:i,lineWidth:r=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return e;r<s&&(s=0);let c=Math.max(1+s,1+r-t.length);if(e.length<=c)return e;let l=[],f={},u=r-t.length;typeof i=="number"&&(i>r-Math.max(2,s)?l.push(0):u=r-i);let d,h,g=!1,p=-1,m=-1,w=-1;n===ka&&(p=Fu(e,p,t.length),p!==-1&&(u=p+c));for(let C;C=e[p+=1];){if(n===Qr&&C==="\\"){switch(m=p,e[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}w=p}if(C===`
|
|
9
|
+
`)n===ka&&(p=Fu(e,p,t.length)),u=p+t.length+c,d=void 0;else{if(C===" "&&h&&h!==" "&&h!==`
|
|
10
10
|
`&&h!==" "){let k=e[p+1];k&&k!==" "&&k!==`
|
|
11
11
|
`&&k!==" "&&(d=p)}if(p>=u)if(d)l.push(d),u=d+c,d=void 0;else if(n===Qr){for(;h===" "||h===" ";)h=C,C=e[p+=1],g=!0;let k=p>w+1?p-2:m-1;if(f[k])return e;l.push(k),f[k]=!0,u=k+c,d=void 0}else g=!0}h=C}if(g&&a&&a(),l.length===0)return e;o&&o();let y=e.slice(0,l[0]);for(let C=0;C<l.length;++C){let k=l[C],E=l[C+1]||e.length;k===0?y=`
|
|
12
12
|
${t}${e.slice(0,E)}`:(n===Qr&&f[k]&&(y+=`${e[k]}\\`),y+=`
|
|
13
13
|
${t}${e.slice(k+1,E)}`)}return y}function Fu(e,t,n){let i=t,r=t+1,s=e[r];for(;s===" "||s===" ";)if(t<r+n)s=e[++t];else{do s=e[++t];while(s&&s!==`
|
|
14
|
-
`);i=t,r=t+1,s=e[r]}return i}$i.FOLD_BLOCK=
|
|
14
|
+
`);i=t,r=t+1,s=e[r]}return i}$i.FOLD_BLOCK=ka;$i.FOLD_FLOW=pw;$i.FOLD_QUOTED=Qr;$i.foldFlowLines=hw});var Ai=v(Wu=>{"use strict";var We=X(),jt=Bu(),es=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),ts=e=>/^(%|---|\.\.\.)/m.test(e);function gw(e,t,n){if(!t||t<0)return!1;let i=t-n,r=e.length;if(r<=i)return!1;for(let s=0,o=0;s<r;++s)if(e[s]===`
|
|
15
15
|
`){if(s-o>i)return!0;if(o=s+1,r-o<=i)return!1}return!0}function Ii(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:i}=t,r=t.options.doubleQuotedMinMultiLineLength,s=t.indent||(ts(e)?" ":""),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 f=n.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(i||n[c+2]==='"'||n.length<r)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,i?o:jt.foldFlowLines(o,s,jt.FOLD_QUOTED,es(t,!1))}function
|
|
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,i?o:jt.foldFlowLines(o,s,jt.FOLD_QUOTED,es(t,!1))}function Sa(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
19
|
`)||/[ \t]\n|\n[ \t]/.test(e))return Ii(e,t);let n=t.indent||(ts(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
-
${n}`)+"'";return t.implicitKey?i:jt.foldFlowLines(i,n,jt.FOLD_FLOW,es(t,!1))}function Bn(e,t){let{singleQuote:n}=t.options,i;if(n===!1)i=Ii;else{let r=e.includes('"'),s=e.includes("'");r&&!s?i=
|
|
20
|
+
${n}`)+"'";return t.implicitKey?i:jt.foldFlowLines(i,n,jt.FOLD_FLOW,es(t,!1))}function Bn(e,t){let{singleQuote:n}=t.options,i;if(n===!1)i=Ii;else{let r=e.includes('"'),s=e.includes("'");r&&!s?i=Sa:s&&!r?i=Ii:i=n?Sa:Ii}return i(e,t)}var Ea;try{Ea=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{
|
|
23
|
+
|$)`,"g")}catch{Ea=/\n+(?!\n|$)/g}function Zr({comment:e,type:t,value:n},i,r,s){let{blockQuote:o,commentString:a,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(n))return Bn(n,i);let l=i.indent||(i.forceBlockIndent||ts(n)?" ":""),f=o==="literal"?!0:o==="folded"||t===We.Scalar.BLOCK_FOLDED?!1:t===We.Scalar.BLOCK_LITERAL?!0:!gw(n,c,l.length);if(!n)return f?`|
|
|
24
24
|
`:`>
|
|
25
25
|
`;let u,d;for(d=n.length;d>0;--d){let E=n[d-1];if(E!==`
|
|
26
26
|
`&&E!==" "&&E!==" ")break}let h=n.substring(d),g=h.indexOf(`
|
|
27
27
|
`);g===-1?u="-":n===h||g!==h.length-1?(u="+",s&&s()):u="",h&&(n=n.slice(0,-h.length),h[h.length-1]===`
|
|
28
|
-
`&&(h=h.slice(0,-1)),h=h.replace(
|
|
28
|
+
`&&(h=h.slice(0,-1)),h=h.replace(Ea,`$&${l}`));let p=!1,m,w=-1;for(m=0;m<n.length;++m){let E=n[m];if(E===" ")p=!0;else if(E===`
|
|
29
29
|
`)w=m;else break}let y=n.substring(0,w<m?w+1:m);y&&(n=n.substring(y.length),y=y.replace(/\n+/g,`$&${l}`));let k=(p?l?"2":"1":"")+u;if(e&&(k+=" "+a(e.replace(/ ?[\r\n]+/g," ")),r&&r()),!f){let E=n.replace(/\n+/g,`
|
|
30
30
|
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),R=!1,I=es(i,!0);o!=="folded"&&t!==We.Scalar.BLOCK_FOLDED&&(I.onOverflow=()=>{R=!0});let b=jt.foldFlowLines(`${y}${E}${h}`,l,jt.FOLD_BLOCK,I);if(!R)return`>${k}
|
|
31
31
|
${l}${b}`}return n=n.replace(/\n+/g,`$&${l}`),`|${k}
|
|
32
|
-
${l}${y}${n}${h}`}function
|
|
32
|
+
${l}${y}${n}${h}`}function ww(e,t,n,i){let{type:r,value:s}=e,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:f}=t;if(a&&s.includes(`
|
|
33
33
|
`)||f&&/[[\]{},]/.test(s))return Bn(s,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||f||!s.includes(`
|
|
34
34
|
`)?Bn(s,t):Zr(e,t,n,i);if(!a&&!f&&r!==We.Scalar.PLAIN&&s.includes(`
|
|
35
35
|
`))return Zr(e,t,n,i);if(ts(s)){if(c==="")return t.forceBlockIndent=!0,Zr(e,t,n,i);if(a&&c===l)return Bn(s,t)}let u=s.replace(/\n+/g,`$&
|
|
36
|
-
${c}`);if(o){let d=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(u),{compat:h,tags:g}=t.doc.schema;if(g.some(d)||h?.some(d))return Bn(s,t)}return a?u:jt.foldFlowLines(u,c,jt.FOLD_FLOW,es(t,!1))}function
|
|
37
|
-
${t.indent}${a}`:a}
|
|
36
|
+
${c}`);if(o){let d=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(u),{compat:h,tags:g}=t.doc.schema;if(g.some(d)||h?.some(d))return Bn(s,t)}return a?u:jt.foldFlowLines(u,c,jt.FOLD_FLOW,es(t,!1))}function yw(e,t,n,i){let{implicitKey:r,inFlow:s}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:a}=e;a!==We.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=We.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case We.Scalar.BLOCK_FOLDED:case We.Scalar.BLOCK_LITERAL:return r||s?Bn(o.value,t):Zr(o,t,n,i);case We.Scalar.QUOTE_DOUBLE:return Ii(o.value,t);case We.Scalar.QUOTE_SINGLE:return Sa(o.value,t);case We.Scalar.PLAIN:return ww(o,t,n,i);default:return null}},l=c(a);if(l===null){let{defaultKeyType:f,defaultStringType:u}=t.options,d=r&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}Wu.stringifyString=yw});var Ni=v(Ra=>{"use strict";var vw=Ur(),Lt=M(),bw=Oi(),Cw=Ai();function kw(e,t){let n=Object.assign({blockQuote:!0,commentString:bw.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(n.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:i,options:n}}function Sw(e,t){if(t.tag){let r=e.filter(s=>s.tag===t.tag);if(r.length>0)return r.find(s=>s.format===t.format)??r[0]}let n,i;if(Lt.isScalar(t)){i=t.value;let r=e.filter(s=>s.identify?.(i));if(r.length>1){let s=r.filter(o=>o.test);s.length>0&&(r=s)}n=r.find(s=>s.format===t.format)??r.find(s=>!s.format)}else i=t,n=e.find(r=>r.nodeClass&&i instanceof r.nodeClass);if(!n){let r=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${r} value`)}return n}function Ew(e,t,{anchors:n,doc:i}){if(!i.directives)return"";let r=[],s=(Lt.isScalar(e)||Lt.isCollection(e))&&e.anchor;s&&vw.anchorIsValid(s)&&(n.add(s),r.push(`&${s}`));let o=e.tag??(t.default?null:t.tag);return o&&r.push(i.directives.tagString(o)),r.join(" ")}function Rw(e,t,n,i){if(Lt.isPair(e))return e.toString(t,n,i);if(Lt.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let r,s=Lt.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>r=c});r??(r=Sw(t.doc.schema.tags,s));let o=Ew(s,r,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let a=typeof r.stringify=="function"?r.stringify(s,t,n,i):Lt.isScalar(s)?Cw.stringifyString(s,t,n,i):s.toString(t,n,i);return o?Lt.isScalar(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
|
|
37
|
+
${t.indent}${a}`:a}Ra.createStringifyContext=kw;Ra.stringify=Rw});var Uu=v(Ju=>{"use strict";var mt=M(),Hu=X(),Ku=Ni(),Ti=Oi();function _w({key:e,value:t},n,i,r){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=n,d=mt.isNode(e)&&e.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(mt.isCollection(e)||!mt.isNode(e)&&typeof e=="object"){let I="With simple keys, collection cannot be used as a key value";throw new Error(I)}}let h=!u&&(!e||d&&t==null&&!n.inFlow||mt.isCollection(e)||(mt.isScalar(e)?e.type===Hu.Scalar.BLOCK_FOLDED||e.type===Hu.Scalar.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!h&&(u||!s),indent:a+c});let g=!1,p=!1,m=Ku.stringify(e,n,()=>g=!0,()=>p=!0);if(!h&&!n.inFlow&&m.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(n.inFlow){if(s||t==null)return g&&i&&i(),m===""?"?":h?`? ${m}`:m}else if(s&&!u||t==null&&h)return m=`? ${m}`,d&&!g?m+=Ti.lineComment(m,n.indent,l(d)):p&&r&&r(),m;g&&(d=null),h?(d&&(m+=Ti.lineComment(m,n.indent,l(d))),m=`? ${m}
|
|
38
38
|
${a}:`):(m=`${m}:`,d&&(m+=Ti.lineComment(m,n.indent,l(d))));let w,y,C;mt.isNode(t)?(w=!!t.spaceBefore,y=t.commentBefore,C=t.comment):(w=!1,y=null,C=null,t&&typeof t=="object"&&(t=o.createNode(t))),n.implicitKey=!1,!h&&!d&&mt.isScalar(t)&&(n.indentAtStart=m.length+1),p=!1,!f&&c.length>=2&&!n.inFlow&&!h&&mt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let k=!1,E=Ku.stringify(t,n,()=>k=!0,()=>p=!0),R=" ";if(d||w||y){if(R=w?`
|
|
39
39
|
`:"",y){let I=l(y);R+=`
|
|
40
40
|
${Ti.indentComment(I,n.indent)}`}E===""&&!n.inFlow?R===`
|
|
@@ -44,34 +44,34 @@ ${Ti.indentComment(I,n.indent)}`}E===""&&!n.inFlow?R===`
|
|
|
44
44
|
${n.indent}`}else if(!h&&mt.isCollection(t)){let I=E[0],b=E.indexOf(`
|
|
45
45
|
`),L=b!==-1,Ie=n.inFlow??t.flow??t.items.length===0;if(L||!Ie){let z=!1;if(L&&(I==="&"||I==="!")){let K=E.indexOf(" ");I==="&"&&K!==-1&&K<b&&E[K+1]==="!"&&(K=E.indexOf(" ",K+1)),(K===-1||b<K)&&(z=!0)}z||(R=`
|
|
46
46
|
${n.indent}`)}}else(E===""||E[0]===`
|
|
47
|
-
`)&&(R="");return m+=R+E,n.inFlow?k&&i&&i():C&&!k?m+=Ti.lineComment(m,n.indent,l(C)):p&&r&&r(),m}Ju.stringifyPair=
|
|
47
|
+
`)&&(R="");return m+=R+E,n.inFlow?k&&i&&i():C&&!k?m+=Ti.lineComment(m,n.indent,l(C)):p&&r&&r(),m}Ju.stringifyPair=_w});var xa=v(_a=>{"use strict";var Vu=Br("process");function xw(e,...t){e==="debug"&&console.log(...t)}function Pw(e,t){(e==="debug"||e==="warn")&&(typeof Vu.emitWarning=="function"?Vu.emitWarning(t):console.warn(t))}_a.debug=xw;_a.warn=Pw});var os=v(ss=>{"use strict";var rs=M(),Yu=X(),ns="<<",is={identify:e=>e===ns||typeof e=="symbol"&&e.description===ns,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Yu.Scalar(Symbol(ns)),{addToJSMap:Gu}),stringify:()=>ns},Ow=(e,t)=>(is.identify(t)||rs.isScalar(t)&&(!t.type||t.type===Yu.Scalar.PLAIN)&&is.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===is.tag&&n.default);function Gu(e,t,n){let i=zu(e,n);if(rs.isSeq(i))for(let r of i.items)Pa(e,t,r);else if(Array.isArray(i))for(let r of i)Pa(e,t,r);else Pa(e,t,i)}function Pa(e,t,n){let i=zu(e,n);if(!rs.isMap(i))throw new Error("Merge sources must be maps or map aliases");let r=i.toJSON(null,e,Map);for(let[s,o]of r)t instanceof Map?t.has(s)||t.set(s,o):t instanceof Set?t.add(s):Object.prototype.hasOwnProperty.call(t,s)||Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function zu(e,t){return e&&rs.isAlias(t)?t.resolve(e.doc,e):t}ss.addMergeToJSMap=Gu;ss.isMergeKey=Ow;ss.merge=is});var $a=v(Zu=>{"use strict";var $w=xa(),Xu=os(),Iw=Ni(),Qu=M(),Oa=Nt();function Aw(e,t,{key:n,value:i}){if(Qu.isNode(n)&&n.addToJSMap)n.addToJSMap(e,t,i);else if(Xu.isMergeKey(e,n))Xu.addMergeToJSMap(e,t,i);else{let r=Oa.toJS(n,"",e);if(t instanceof Map)t.set(r,Oa.toJS(i,r,e));else if(t instanceof Set)t.add(r);else{let s=Nw(n,r,e),o=Oa.toJS(i,s,e);s in t?Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[s]=o}}return t}function Nw(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(Qu.isNode(e)&&n?.doc){let i=Iw.createStringifyContext(n.doc,{});i.anchors=new Set;for(let s of n.anchors.keys())i.anchors.add(s.anchor);i.inFlow=!0,i.inStringifyKey=!0;let r=e.toString(i);if(!n.mapKeyWarned){let s=JSON.stringify(r);s.length>40&&(s=s.substring(0,36)+'..."'),$w.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 r}return JSON.stringify(t)}Zu.addPairToJSMap=Aw});var Mt=v(Ia=>{"use strict";var ef=Pi(),Tw=Uu(),jw=$a(),as=M();function Lw(e,t,n){let i=ef.createNode(e,void 0,n),r=ef.createNode(t,void 0,n);return new cs(i,r)}var cs=class e{constructor(t,n=null){Object.defineProperty(this,as.NODE_TYPE,{value:as.PAIR}),this.key=t,this.value=n}clone(t){let{key:n,value:i}=this;return as.isNode(n)&&(n=n.clone(t)),as.isNode(i)&&(i=i.clone(t)),new e(n,i)}toJSON(t,n){let i=n?.mapAsMap?new Map:{};return jw.addPairToJSMap(n,i,this)}toString(t,n,i){return t?.doc?Tw.stringifyPair(this,t,n,i):JSON.stringify(this)}};Ia.Pair=cs;Ia.createPair=Lw});var Aa=v(nf=>{"use strict";var pn=M(),tf=Ni(),ls=Oi();function Mw(e,t,n){return(t.inFlow??e.flow?Dw:qw)(e,t,n)}function qw({comment:e,items:t},n,{blockItemPrefix:i,flowChars:r,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=n,f=Object.assign({},n,{indent:s,type:null}),u=!1,d=[];for(let g=0;g<t.length;++g){let p=t[g],m=null;if(pn.isNode(p))!u&&p.spaceBefore&&d.push(""),us(n,d,p.commentBefore,u),p.comment&&(m=p.comment);else if(pn.isPair(p)){let y=pn.isNode(p.key)?p.key:null;y&&(!u&&y.spaceBefore&&d.push(""),us(n,d,y.commentBefore,u))}u=!1;let w=tf.stringify(p,f,()=>m=null,()=>u=!0);m&&(w+=ls.lineComment(w,s,l(m))),u&&m&&(u=!1),d.push(i+w)}let h;if(d.length===0)h=r.start+r.end;else{h=d[0];for(let g=1;g<d.length;++g){let p=d[g];h+=p?`
|
|
48
48
|
${c}${p}`:`
|
|
49
49
|
`}}return e?(h+=`
|
|
50
|
-
`+ls.indentComment(l(e),c),a&&a()):u&&o&&o(),h}function
|
|
50
|
+
`+ls.indentComment(l(e),c),a&&a()):u&&o&&o(),h}function Dw({items:e},t,{flowChars:n,itemIndent:i}){let{indent:r,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=t;i+=s;let c=Object.assign({},t,{indent:i,inFlow:!0,type:null}),l=!1,f=0,u=[];for(let g=0;g<e.length;++g){let p=e[g],m=null;if(pn.isNode(p))p.spaceBefore&&u.push(""),us(t,u,p.commentBefore,!1),p.comment&&(m=p.comment);else if(pn.isPair(p)){let y=pn.isNode(p.key)?p.key:null;y&&(y.spaceBefore&&u.push(""),us(t,u,y.commentBefore,!1),y.comment&&(l=!0));let C=pn.isNode(p.value)?p.value:null;C?(C.comment&&(m=C.comment),C.commentBefore&&(l=!0)):p.value==null&&y?.comment&&(m=y.comment)}m&&(l=!0);let w=tf.stringify(p,c,()=>m=null);l||(l=u.length>f||w.includes(`
|
|
51
51
|
`)),g<e.length-1?w+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=u.reduce((y,C)=>y+C.length+2,2)+(w.length+2)>t.options.lineWidth)),l&&(w+=",")),m&&(w+=ls.lineComment(w,i,a(m))),u.push(w),f=u.length}let{start:d,end:h}=n;if(u.length===0)return d+h;if(!l){let g=u.reduce((p,m)=>p+m.length+2,2);l=t.options.lineWidth>0&&g>t.options.lineWidth}if(l){let g=d;for(let p of u)g+=p?`
|
|
52
52
|
${s}${r}${p}`:`
|
|
53
53
|
`;return`${g}
|
|
54
|
-
${r}${h}`}else return`${d}${o}${u.join(" ")}${o}${h}`}function us({indent:e,options:{commentString:t}},n,i,r){if(i&&r&&(i=i.replace(/^\n+/,"")),i){let s=ls.indentComment(t(i),e);n.push(s.trimStart())}}nf.stringifyCollection=
|
|
55
|
-
`:" ")}return
|
|
54
|
+
${r}${h}`}else return`${d}${o}${u.join(" ")}${o}${h}`}function us({indent:e,options:{commentString:t}},n,i,r){if(i&&r&&(i=i.replace(/^\n+/,"")),i){let s=ls.indentComment(t(i),e);n.push(s.trimStart())}}nf.stringifyCollection=Mw});var Dt=v(Ta=>{"use strict";var Fw=Aa(),Bw=$a(),Ww=zr(),qt=M(),fs=Mt(),Hw=X();function ji(e,t){let n=qt.isScalar(t)?t.value:t;for(let i of e)if(qt.isPair(i)&&(i.key===t||i.key===n||qt.isScalar(i.key)&&i.key.value===n))return i}var Na=class extends Ww.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(qt.MAP,t),this.items=[]}static from(t,n,i){let{keepUndefined:r,replacer:s}=i,o=new this(t),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||r)&&o.items.push(fs.createPair(c,l,i))};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 t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,n){let i;qt.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new fs.Pair(t,t?.value):i=new fs.Pair(t.key,t.value);let r=ji(this.items,i.key),s=this.schema?.sortMapEntries;if(r){if(!n)throw new Error(`Key ${i.key} already set`);qt.isScalar(r.value)&&Hw.isScalarValue(i.value)?r.value.value=i.value:r.value=i.value}else if(s){let o=this.items.findIndex(a=>s(i,a)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(t){let n=ji(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){let r=ji(this.items,t)?.value;return(!n&&qt.isScalar(r)?r.value:r)??void 0}has(t){return!!ji(this.items,t)}set(t,n){this.add(new fs.Pair(t,n),!0)}toJSON(t,n,i){let r=i?new i:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(r);for(let s of this.items)Bw.addPairToJSMap(n,r,s);return r}toString(t,n,i){if(!t)return JSON.stringify(this);for(let r of this.items)if(!qt.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),Fw.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:n})}};Ta.YAMLMap=Na;Ta.findPair=ji});var Wn=v(sf=>{"use strict";var Kw=M(),rf=Dt(),Jw={collection:"map",default:!0,nodeClass:rf.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return Kw.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,n)=>rf.YAMLMap.from(e,t,n)};sf.map=Jw});var Ft=v(of=>{"use strict";var Uw=Pi(),Vw=Aa(),Yw=zr(),ms=M(),Gw=X(),zw=Nt(),ja=class extends Yw.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(ms.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let n=ds(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){let i=ds(t);if(typeof i!="number")return;let r=this.items[i];return!n&&ms.isScalar(r)?r.value:r}has(t){let n=ds(t);return typeof n=="number"&&n<this.items.length}set(t,n){let i=ds(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let r=this.items[i];ms.isScalar(r)&&Gw.isScalarValue(n)?r.value=n:this.items[i]=n}toJSON(t,n){let i=[];n?.onCreate&&n.onCreate(i);let r=0;for(let s of this.items)i.push(zw.toJS(s,String(r++),n));return i}toString(t,n,i){return t?Vw.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:n}):JSON.stringify(this)}static from(t,n,i){let{replacer:r}=i,s=new this(t);if(n&&Symbol.iterator in Object(n)){let o=0;for(let a of n){if(typeof r=="function"){let c=n instanceof Set?a:String(o++);a=r.call(n,c,a)}s.items.push(Uw.createNode(a,void 0,i))}}return s}};function ds(e){let t=ms.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}of.YAMLSeq=ja});var Hn=v(cf=>{"use strict";var Xw=M(),af=Ft(),Qw={collection:"seq",default:!0,nodeClass:af.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Xw.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,n)=>af.YAMLSeq.from(e,t,n)};cf.seq=Qw});var Li=v(lf=>{"use strict";var Zw=Ai(),ey={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,n,i){return t=Object.assign({actualString:!0},t),Zw.stringifyString(e,t,n,i)}};lf.string=ey});var ps=v(df=>{"use strict";var uf=X(),ff={identify:e=>e==null,createNode:()=>new uf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new uf.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&ff.test.test(e)?e:t.options.nullStr};df.nullTag=ff});var La=v(pf=>{"use strict";var ty=X(),mf={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new ty.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},n){if(e&&mf.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?n.options.trueStr:n.options.falseStr}};pf.boolTag=mf});var Kn=v(hf=>{"use strict";function ny({format:e,minFractionDigits:t,tag:n,value:i}){if(typeof i=="bigint")return String(i);let r=typeof i=="number"?i:Number(i);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let s=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!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=t-(s.length-o-1);for(;a-- >0;)s+="0"}return s}hf.stringifyNumber=ny});var qa=v(hs=>{"use strict";var iy=X(),Ma=Kn(),ry={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ma.stringifyNumber},sy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Ma.stringifyNumber(e)}},oy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new iy.Scalar(parseFloat(e)),n=e.indexOf(".");return n!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-n-1),t},stringify:Ma.stringifyNumber};hs.float=oy;hs.floatExp=sy;hs.floatNaN=ry});var Fa=v(ws=>{"use strict";var gf=Kn(),gs=e=>typeof e=="bigint"||Number.isInteger(e),Da=(e,t,n,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),n);function wf(e,t,n){let{value:i}=e;return gs(i)&&i>=0?n+i.toString(t):gf.stringifyNumber(e)}var ay={identify:e=>gs(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>Da(e,2,8,n),stringify:e=>wf(e,8,"0o")},cy={identify:gs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>Da(e,0,10,n),stringify:gf.stringifyNumber},ly={identify:e=>gs(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>Da(e,2,16,n),stringify:e=>wf(e,16,"0x")};ws.int=cy;ws.intHex=ly;ws.intOct=ay});var vf=v(yf=>{"use strict";var uy=Wn(),fy=ps(),dy=Hn(),my=Li(),py=La(),Ba=qa(),Wa=Fa(),hy=[uy.map,dy.seq,my.string,fy.nullTag,py.boolTag,Wa.intOct,Wa.int,Wa.intHex,Ba.floatNaN,Ba.floatExp,Ba.float];yf.schema=hy});var kf=v(Cf=>{"use strict";var gy=X(),wy=Wn(),yy=Hn();function bf(e){return typeof e=="bigint"||Number.isInteger(e)}var ys=({value:e})=>JSON.stringify(e),vy=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:ys},{identify:e=>e==null,createNode:()=>new gy.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:ys},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:ys},{identify:bf,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>bf(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:ys}],by={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},Cy=[wy.map,yy.seq].concat(vy,by);Cf.schema=Cy});var Ka=v(Sf=>{"use strict";var Mi=Br("buffer"),Ha=X(),ky=Ai(),Sy={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Mi.Buffer=="function")return Mi.Buffer.from(e,"base64");if(typeof atob=="function"){let n=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(n.length);for(let r=0;r<n.length;++r)i[r]=n.charCodeAt(r);return i}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:n},i,r,s){if(!n)return"";let o=n,a;if(typeof Mi.Buffer=="function")a=o instanceof Mi.Buffer?o.toString("base64"):Mi.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(t??(t=Ha.Scalar.BLOCK_LITERAL),t!==Ha.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(a.length/c),f=new Array(l);for(let u=0,d=0;u<l;++u,d+=c)f[u]=a.substr(d,c);a=f.join(t===Ha.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return ky.stringifyString({comment:e,type:t,value:a},i,r,s)}};Sf.binary=Sy});var Cs=v(bs=>{"use strict";var vs=M(),Ja=Mt(),Ey=X(),Ry=Ft();function Ef(e,t){if(vs.isSeq(e))for(let n=0;n<e.items.length;++n){let i=e.items[n];if(!vs.isPair(i)){if(vs.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let r=i.items[0]||new Ja.Pair(new Ey.Scalar(null));if(i.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${i.commentBefore}
|
|
56
56
|
${r.key.commentBefore}`:i.commentBefore),i.comment){let s=r.value??r.key;s.comment=s.comment?`${i.comment}
|
|
57
|
-
${s.comment}`:i.comment}i=r}e.items[n]=vs.isPair(i)?i:new Ka.Pair(i)}}else t("Expected a sequence for this tag");return e}function Rf(e,t,n){let{replacer:i}=n,r=new Ey.YAMLSeq(e);r.tag="tag:yaml.org,2002:pairs";let s=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,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;r.items.push(Ka.createPair(a,c,n))}return r}var Ry={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Ef,createNode:Rf};bs.createPairs=Rf;bs.pairs=Ry;bs.resolvePairs=Ef});var Va=v(Ua=>{"use strict";var _f=M(),Ja=Nt(),qi=Dt(),_y=Ft(),xf=Cs(),hn=class e extends _y.YAMLSeq{constructor(){super(),this.add=qi.YAMLMap.prototype.add.bind(this),this.delete=qi.YAMLMap.prototype.delete.bind(this),this.get=qi.YAMLMap.prototype.get.bind(this),this.has=qi.YAMLMap.prototype.has.bind(this),this.set=qi.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,n){if(!n)return super.toJSON(t);let i=new Map;n?.onCreate&&n.onCreate(i);for(let r of this.items){let s,o;if(_f.isPair(r)?(s=Ja.toJS(r.key,"",n),o=Ja.toJS(r.value,s,n)):s=Ja.toJS(r,"",n),i.has(s))throw new Error("Ordered maps must not include duplicate keys");i.set(s,o)}return i}static from(t,n,i){let r=xf.createPairs(t,n,i),s=new this;return s.items=r.items,s}};hn.tag="tag:yaml.org,2002:omap";var xy={collection:"seq",identify:e=>e instanceof Map,nodeClass:hn,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let n=xf.resolvePairs(e,t),i=[];for(let{key:r}of n.items)_f.isScalar(r)&&(i.includes(r.value)?t(`Ordered maps must not include duplicate keys: ${r.value}`):i.push(r.value));return Object.assign(new hn,n)},createNode:(e,t,n)=>hn.from(e,t,n)};Ua.YAMLOMap=hn;Ua.omap=xy});var Af=v(Ya=>{"use strict";var Pf=X();function Of({value:e,source:t},n){return t&&(e?$f:If).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var $f={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Pf.Scalar(!0),stringify:Of},If={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Pf.Scalar(!1),stringify:Of};Ya.falseTag=If;Ya.trueTag=$f});var Nf=v(ks=>{"use strict";var Py=X(),Ga=Kn(),Oy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ga.stringifyNumber},$y={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Ga.stringifyNumber(e)}},Iy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new Py.Scalar(parseFloat(e.replace(/_/g,""))),n=e.indexOf(".");if(n!==-1){let i=e.substring(n+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:Ga.stringifyNumber};ks.float=Iy;ks.floatExp=$y;ks.floatNaN=Oy});var jf=v(Fi=>{"use strict";var Tf=Kn(),Di=e=>typeof e=="bigint"||Number.isInteger(e);function Ss(e,t,n,{intAsBigInt:i}){let r=e[0];if((r==="-"||r==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return r==="-"?BigInt(-1)*o:o}let s=parseInt(e,n);return r==="-"?-1*s:s}function za(e,t,n){let{value:i}=e;if(Di(i)){let r=i.toString(t);return i<0?"-"+n+r.substr(1):n+r}return Tf.stringifyNumber(e)}var Ay={identify:Di,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>Ss(e,2,2,n),stringify:e=>za(e,2,"0b")},Ny={identify:Di,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>Ss(e,1,8,n),stringify:e=>za(e,8,"0")},Ty={identify:Di,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>Ss(e,0,10,n),stringify:Tf.stringifyNumber},jy={identify:Di,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>Ss(e,2,16,n),stringify:e=>za(e,16,"0x")};Fi.int=Ty;Fi.intBin=Ay;Fi.intHex=jy;Fi.intOct=Ny});var Qa=v(Xa=>{"use strict";var _s=M(),Es=Mt(),Rs=Dt(),gn=class e extends Rs.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let n;_s.isPair(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new Es.Pair(t.key,null):n=new Es.Pair(t,null),Rs.findPair(this.items,n.key)||this.items.push(n)}get(t,n){let i=Rs.findPair(this.items,t);return!n&&_s.isPair(i)?_s.isScalar(i.key)?i.key.value:i.key:i}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let i=Rs.findPair(this.items,t);i&&!n?this.items.splice(this.items.indexOf(i),1):!i&&n&&this.items.push(new Es.Pair(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),n,i);throw new Error("Set items must all have null values")}static from(t,n,i){let{replacer:r}=i,s=new this(t);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof r=="function"&&(o=r.call(n,o,o)),s.items.push(Es.createPair(o,null,i));return s}};gn.tag="tag:yaml.org,2002:set";var Ly={collection:"map",identify:e=>e instanceof Set,nodeClass:gn,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>gn.from(e,t,n),resolve(e,t){if(_s.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new gn,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Xa.YAMLSet=gn;Xa.set=Ly});var ec=v(xs=>{"use strict";var My=Kn();function Za(e,t){let n=e[0],i=n==="-"||n==="+"?e.substring(1):e,r=o=>t?BigInt(o):Number(o),s=i.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return n==="-"?r(-1)*s:s}function Lf(e){let{value:t}=e,n=o=>o;if(typeof t=="bigint")n=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return My.stringifyNumber(e);let i="";t<0&&(i="-",t*=n(-1));let r=n(60),s=[t%r];return t<60?s.unshift(0):(t=(t-s[0])/r,s.unshift(t%r),t>=60&&(t=(t-s[0])/r,s.unshift(t))),i+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var qy={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>Za(e,n),stringify:Lf},Dy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>Za(e,!1),stringify:Lf},Mf={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(Mf.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,i,r,s,o,a]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(n,i-1,r,s||0,o||0,a||0,c),f=t[8];if(f&&f!=="Z"){let u=Za(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};xs.floatTime=Dy;xs.intTime=qy;xs.timestamp=Mf});var Ff=v(Df=>{"use strict";var Fy=Wn(),By=ps(),Wy=Hn(),Hy=Li(),Ky=Ha(),qf=Af(),tc=Nf(),Ps=jf(),Jy=os(),Uy=Va(),Vy=Cs(),Yy=Qa(),nc=ec(),Gy=[Fy.map,Wy.seq,Hy.string,By.nullTag,qf.trueTag,qf.falseTag,Ps.intBin,Ps.intOct,Ps.int,Ps.intHex,tc.floatNaN,tc.floatExp,tc.float,Ky.binary,Jy.merge,Uy.omap,Vy.pairs,Yy.set,nc.intTime,nc.floatTime,nc.timestamp];Df.schema=Gy});var zf=v(sc=>{"use strict";var Kf=Wn(),zy=ps(),Jf=Hn(),Xy=Li(),Qy=ja(),ic=Ma(),rc=Da(),Zy=vf(),ev=kf(),Uf=Ha(),Bi=os(),Vf=Va(),Yf=Cs(),Bf=Ff(),Gf=Qa(),Os=ec(),Wf=new Map([["core",Zy.schema],["failsafe",[Kf.map,Jf.seq,Xy.string]],["json",ev.schema],["yaml11",Bf.schema],["yaml-1.1",Bf.schema]]),Hf={binary:Uf.binary,bool:Qy.boolTag,float:ic.float,floatExp:ic.floatExp,floatNaN:ic.floatNaN,floatTime:Os.floatTime,int:rc.int,intHex:rc.intHex,intOct:rc.intOct,intTime:Os.intTime,map:Kf.map,merge:Bi.merge,null:zy.nullTag,omap:Vf.omap,pairs:Yf.pairs,seq:Jf.seq,set:Gf.set,timestamp:Os.timestamp},tv={"tag:yaml.org,2002:binary":Uf.binary,"tag:yaml.org,2002:merge":Bi.merge,"tag:yaml.org,2002:omap":Vf.omap,"tag:yaml.org,2002:pairs":Yf.pairs,"tag:yaml.org,2002:set":Gf.set,"tag:yaml.org,2002:timestamp":Os.timestamp};function nv(e,t,n){let i=Wf.get(t);if(i&&!e)return n&&!i.includes(Bi.merge)?i.concat(Bi.merge):i.slice();let r=i;if(!r)if(Array.isArray(e))r=[];else{let s=Array.from(Wf.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${s} or define customTags array`)}if(Array.isArray(e))for(let s of e)r=r.concat(s);else typeof e=="function"&&(r=e(r.slice()));return n&&(r=r.concat(Bi.merge)),r.reduce((s,o)=>{let a=typeof o=="string"?Hf[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Hf).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}sc.coreKnownTags=tv;sc.getTags=nv});var cc=v(Xf=>{"use strict";var oc=M(),iv=Wn(),rv=Hn(),sv=Li(),$s=zf(),ov=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,ac=class e{constructor({compat:t,customTags:n,merge:i,resolveKnownTags:r,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(t)?$s.getTags(t,"compat"):t?$s.getTags(null,t):null,this.name=typeof s=="string"&&s||"core",this.knownTags=r?$s.coreKnownTags:{},this.tags=$s.getTags(n,this.name,i),this.toStringOptions=a??null,Object.defineProperty(this,oc.MAP,{value:iv.map}),Object.defineProperty(this,oc.SCALAR,{value:sv.string}),Object.defineProperty(this,oc.SEQ,{value:rv.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?ov:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Xf.Schema=ac});var Zf=v(Qf=>{"use strict";var av=M(),lc=Ni(),Wi=Oi();function cv(e,t){let n=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(n.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&n.push("---");let r=lc.createStringifyContext(e,t),{commentString:s}=r.options;if(e.commentBefore){n.length!==1&&n.unshift("");let c=s(e.commentBefore);n.unshift(Wi.indentComment(c,""))}let o=!1,a=null;if(e.contents){if(av.isNode(e.contents)){if(e.contents.spaceBefore&&i&&n.push(""),e.contents.commentBefore){let f=s(e.contents.commentBefore);n.push(Wi.indentComment(f,""))}r.forceBlockIndent=!!e.comment,a=e.contents.comment}let c=a?void 0:()=>o=!0,l=lc.stringify(e.contents,r,()=>a=null,c);a&&(l+=Wi.lineComment(l,"",s(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(lc.stringify(e.contents,r));if(e.directives?.docEnd)if(e.comment){let c=s(e.comment);c.includes(`
|
|
57
|
+
${s.comment}`:i.comment}i=r}e.items[n]=vs.isPair(i)?i:new Ja.Pair(i)}}else t("Expected a sequence for this tag");return e}function Rf(e,t,n){let{replacer:i}=n,r=new Ry.YAMLSeq(e);r.tag="tag:yaml.org,2002:pairs";let s=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,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;r.items.push(Ja.createPair(a,c,n))}return r}var _y={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Ef,createNode:Rf};bs.createPairs=Rf;bs.pairs=_y;bs.resolvePairs=Ef});var Ya=v(Va=>{"use strict";var _f=M(),Ua=Nt(),qi=Dt(),xy=Ft(),xf=Cs(),hn=class e extends xy.YAMLSeq{constructor(){super(),this.add=qi.YAMLMap.prototype.add.bind(this),this.delete=qi.YAMLMap.prototype.delete.bind(this),this.get=qi.YAMLMap.prototype.get.bind(this),this.has=qi.YAMLMap.prototype.has.bind(this),this.set=qi.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,n){if(!n)return super.toJSON(t);let i=new Map;n?.onCreate&&n.onCreate(i);for(let r of this.items){let s,o;if(_f.isPair(r)?(s=Ua.toJS(r.key,"",n),o=Ua.toJS(r.value,s,n)):s=Ua.toJS(r,"",n),i.has(s))throw new Error("Ordered maps must not include duplicate keys");i.set(s,o)}return i}static from(t,n,i){let r=xf.createPairs(t,n,i),s=new this;return s.items=r.items,s}};hn.tag="tag:yaml.org,2002:omap";var Py={collection:"seq",identify:e=>e instanceof Map,nodeClass:hn,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let n=xf.resolvePairs(e,t),i=[];for(let{key:r}of n.items)_f.isScalar(r)&&(i.includes(r.value)?t(`Ordered maps must not include duplicate keys: ${r.value}`):i.push(r.value));return Object.assign(new hn,n)},createNode:(e,t,n)=>hn.from(e,t,n)};Va.YAMLOMap=hn;Va.omap=Py});var Af=v(Ga=>{"use strict";var Pf=X();function Of({value:e,source:t},n){return t&&(e?$f:If).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var $f={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Pf.Scalar(!0),stringify:Of},If={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Pf.Scalar(!1),stringify:Of};Ga.falseTag=If;Ga.trueTag=$f});var Nf=v(ks=>{"use strict";var Oy=X(),za=Kn(),$y={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:za.stringifyNumber},Iy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():za.stringifyNumber(e)}},Ay={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new Oy.Scalar(parseFloat(e.replace(/_/g,""))),n=e.indexOf(".");if(n!==-1){let i=e.substring(n+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:za.stringifyNumber};ks.float=Ay;ks.floatExp=Iy;ks.floatNaN=$y});var jf=v(Fi=>{"use strict";var Tf=Kn(),Di=e=>typeof e=="bigint"||Number.isInteger(e);function Ss(e,t,n,{intAsBigInt:i}){let r=e[0];if((r==="-"||r==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return r==="-"?BigInt(-1)*o:o}let s=parseInt(e,n);return r==="-"?-1*s:s}function Xa(e,t,n){let{value:i}=e;if(Di(i)){let r=i.toString(t);return i<0?"-"+n+r.substr(1):n+r}return Tf.stringifyNumber(e)}var Ny={identify:Di,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>Ss(e,2,2,n),stringify:e=>Xa(e,2,"0b")},Ty={identify:Di,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>Ss(e,1,8,n),stringify:e=>Xa(e,8,"0")},jy={identify:Di,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>Ss(e,0,10,n),stringify:Tf.stringifyNumber},Ly={identify:Di,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>Ss(e,2,16,n),stringify:e=>Xa(e,16,"0x")};Fi.int=jy;Fi.intBin=Ny;Fi.intHex=Ly;Fi.intOct=Ty});var Za=v(Qa=>{"use strict";var _s=M(),Es=Mt(),Rs=Dt(),gn=class e extends Rs.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let n;_s.isPair(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new Es.Pair(t.key,null):n=new Es.Pair(t,null),Rs.findPair(this.items,n.key)||this.items.push(n)}get(t,n){let i=Rs.findPair(this.items,t);return!n&&_s.isPair(i)?_s.isScalar(i.key)?i.key.value:i.key:i}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let i=Rs.findPair(this.items,t);i&&!n?this.items.splice(this.items.indexOf(i),1):!i&&n&&this.items.push(new Es.Pair(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),n,i);throw new Error("Set items must all have null values")}static from(t,n,i){let{replacer:r}=i,s=new this(t);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof r=="function"&&(o=r.call(n,o,o)),s.items.push(Es.createPair(o,null,i));return s}};gn.tag="tag:yaml.org,2002:set";var My={collection:"map",identify:e=>e instanceof Set,nodeClass:gn,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>gn.from(e,t,n),resolve(e,t){if(_s.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new gn,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Qa.YAMLSet=gn;Qa.set=My});var tc=v(xs=>{"use strict";var qy=Kn();function ec(e,t){let n=e[0],i=n==="-"||n==="+"?e.substring(1):e,r=o=>t?BigInt(o):Number(o),s=i.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return n==="-"?r(-1)*s:s}function Lf(e){let{value:t}=e,n=o=>o;if(typeof t=="bigint")n=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return qy.stringifyNumber(e);let i="";t<0&&(i="-",t*=n(-1));let r=n(60),s=[t%r];return t<60?s.unshift(0):(t=(t-s[0])/r,s.unshift(t%r),t>=60&&(t=(t-s[0])/r,s.unshift(t))),i+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Dy={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>ec(e,n),stringify:Lf},Fy={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>ec(e,!1),stringify:Lf},Mf={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(Mf.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,i,r,s,o,a]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(n,i-1,r,s||0,o||0,a||0,c),f=t[8];if(f&&f!=="Z"){let u=ec(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};xs.floatTime=Fy;xs.intTime=Dy;xs.timestamp=Mf});var Ff=v(Df=>{"use strict";var By=Wn(),Wy=ps(),Hy=Hn(),Ky=Li(),Jy=Ka(),qf=Af(),nc=Nf(),Ps=jf(),Uy=os(),Vy=Ya(),Yy=Cs(),Gy=Za(),ic=tc(),zy=[By.map,Hy.seq,Ky.string,Wy.nullTag,qf.trueTag,qf.falseTag,Ps.intBin,Ps.intOct,Ps.int,Ps.intHex,nc.floatNaN,nc.floatExp,nc.float,Jy.binary,Uy.merge,Vy.omap,Yy.pairs,Gy.set,ic.intTime,ic.floatTime,ic.timestamp];Df.schema=zy});var zf=v(oc=>{"use strict";var Kf=Wn(),Xy=ps(),Jf=Hn(),Qy=Li(),Zy=La(),rc=qa(),sc=Fa(),ev=vf(),tv=kf(),Uf=Ka(),Bi=os(),Vf=Ya(),Yf=Cs(),Bf=Ff(),Gf=Za(),Os=tc(),Wf=new Map([["core",ev.schema],["failsafe",[Kf.map,Jf.seq,Qy.string]],["json",tv.schema],["yaml11",Bf.schema],["yaml-1.1",Bf.schema]]),Hf={binary:Uf.binary,bool:Zy.boolTag,float:rc.float,floatExp:rc.floatExp,floatNaN:rc.floatNaN,floatTime:Os.floatTime,int:sc.int,intHex:sc.intHex,intOct:sc.intOct,intTime:Os.intTime,map:Kf.map,merge:Bi.merge,null:Xy.nullTag,omap:Vf.omap,pairs:Yf.pairs,seq:Jf.seq,set:Gf.set,timestamp:Os.timestamp},nv={"tag:yaml.org,2002:binary":Uf.binary,"tag:yaml.org,2002:merge":Bi.merge,"tag:yaml.org,2002:omap":Vf.omap,"tag:yaml.org,2002:pairs":Yf.pairs,"tag:yaml.org,2002:set":Gf.set,"tag:yaml.org,2002:timestamp":Os.timestamp};function iv(e,t,n){let i=Wf.get(t);if(i&&!e)return n&&!i.includes(Bi.merge)?i.concat(Bi.merge):i.slice();let r=i;if(!r)if(Array.isArray(e))r=[];else{let s=Array.from(Wf.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${s} or define customTags array`)}if(Array.isArray(e))for(let s of e)r=r.concat(s);else typeof e=="function"&&(r=e(r.slice()));return n&&(r=r.concat(Bi.merge)),r.reduce((s,o)=>{let a=typeof o=="string"?Hf[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Hf).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}oc.coreKnownTags=nv;oc.getTags=iv});var lc=v(Xf=>{"use strict";var ac=M(),rv=Wn(),sv=Hn(),ov=Li(),$s=zf(),av=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,cc=class e{constructor({compat:t,customTags:n,merge:i,resolveKnownTags:r,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(t)?$s.getTags(t,"compat"):t?$s.getTags(null,t):null,this.name=typeof s=="string"&&s||"core",this.knownTags=r?$s.coreKnownTags:{},this.tags=$s.getTags(n,this.name,i),this.toStringOptions=a??null,Object.defineProperty(this,ac.MAP,{value:rv.map}),Object.defineProperty(this,ac.SCALAR,{value:ov.string}),Object.defineProperty(this,ac.SEQ,{value:sv.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?av:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Xf.Schema=cc});var Zf=v(Qf=>{"use strict";var cv=M(),uc=Ni(),Wi=Oi();function lv(e,t){let n=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(n.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&n.push("---");let r=uc.createStringifyContext(e,t),{commentString:s}=r.options;if(e.commentBefore){n.length!==1&&n.unshift("");let c=s(e.commentBefore);n.unshift(Wi.indentComment(c,""))}let o=!1,a=null;if(e.contents){if(cv.isNode(e.contents)){if(e.contents.spaceBefore&&i&&n.push(""),e.contents.commentBefore){let f=s(e.contents.commentBefore);n.push(Wi.indentComment(f,""))}r.forceBlockIndent=!!e.comment,a=e.contents.comment}let c=a?void 0:()=>o=!0,l=uc.stringify(e.contents,r,()=>a=null,c);a&&(l+=Wi.lineComment(l,"",s(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(uc.stringify(e.contents,r));if(e.directives?.docEnd)if(e.comment){let c=s(e.comment);c.includes(`
|
|
58
58
|
`)?(n.push("..."),n.push(Wi.indentComment(c,""))):n.push(`... ${c}`)}else n.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&n[n.length-1]!==""&&n.push(""),n.push(Wi.indentComment(s(c),"")))}return n.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}Qf.stringifyDocument=
|
|
60
|
+
`}Qf.stringifyDocument=lv});var Hi=v(ed=>{"use strict";var uv=xi(),Jn=zr(),Le=M(),fv=Mt(),dv=Nt(),mv=lc(),pv=Zf(),fc=Ur(),hv=ha(),gv=Pi(),dc=pa(),mc=class e{constructor(t,n,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Le.NODE_TYPE,{value:Le.DOC});let r=null;typeof n=="function"||Array.isArray(n)?r=n:i===void 0&&n&&(i=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"},i);this.options=s;let{version:o}=s;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new dc.Directives({version:o}),this.setSchema(o,i),this.contents=t===void 0?null:this.createNode(t,r,i)}clone(){let t=Object.create(e.prototype,{[Le.NODE_TYPE]:{value:Le.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=Le.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Un(this.contents)&&this.contents.add(t)}addIn(t,n){Un(this.contents)&&this.contents.addIn(t,n)}createAlias(t,n){if(!t.anchor){let i=fc.anchorNames(this);t.anchor=!n||i.has(n)?fc.findNewAnchor(n||"a",i):n}return new uv.Alias(t.anchor)}createNode(t,n,i){let r;if(typeof n=="function")t=n.call({"":t},"",t),r=n;else if(Array.isArray(n)){let m=y=>typeof y=="number"||y instanceof String||y instanceof Number,w=n.filter(m).map(String);w.length>0&&(n=n.concat(w)),r=n}else i===void 0&&n&&(i=n,n=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:f}=i??{},{onAnchor:u,setAnchors:d,sourceObjects:h}=fc.createNodeAnchors(this,o||"a"),g={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:r,schema:this.schema,sourceObjects:h},p=gv.createNode(t,f,g);return a&&Le.isCollection(p)&&(p.flow=!0),d(),p}createPair(t,n,i={}){let r=this.createNode(t,null,i),s=this.createNode(n,null,i);return new fv.Pair(r,s)}delete(t){return Un(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Jn.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Un(this.contents)?this.contents.deleteIn(t):!1}get(t,n){return Le.isCollection(this.contents)?this.contents.get(t,n):void 0}getIn(t,n){return Jn.isEmptyPath(t)?!n&&Le.isScalar(this.contents)?this.contents.value:this.contents:Le.isCollection(this.contents)?this.contents.getIn(t,n):void 0}has(t){return Le.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Jn.isEmptyPath(t)?this.contents!==void 0:Le.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,n){this.contents==null?this.contents=Jn.collectionFromPath(this.schema,[t],n):Un(this.contents)&&this.contents.set(t,n)}setIn(t,n){Jn.isEmptyPath(t)?this.contents=n:this.contents==null?this.contents=Jn.collectionFromPath(this.schema,Array.from(t),n):Un(this.contents)&&this.contents.setIn(t,n)}setSchema(t,n={}){typeof t=="number"&&(t=String(t));let i;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new dc.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new dc.Directives({version:t}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let r=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(i)this.schema=new mv.Schema(Object.assign(i,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:n,mapAsMap:i,maxAliasCount:r,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=dv.toJS(this.contents,n??"",a);if(typeof s=="function")for(let{count:l,res:f}of a.anchors.values())s(f,l);return typeof o=="function"?hv.applyReviver(o,{"":c},"",c):c}toJSON(t,n){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:n})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let n=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return pv.stringifyDocument(this,t)}};function Un(e){if(Le.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}ed.Document=mc});var Ui=v(Ji=>{"use strict";var Ki=class extends Error{constructor(t,n,i,r){super(),this.name=t,this.code=i,this.message=r,this.pos=n}},pc=class extends Ki{constructor(t,n,i){super("YAMLParseError",t,n,i)}},hc=class extends Ki{constructor(t,n,i){super("YAMLWarning",t,n,i)}},wv=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>t.linePos(a));let{line:i,col:r}=n.linePos[0];n.message+=` at line ${i}, column ${r}`;let s=r-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).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)+"…"),i>1&&/^ *$/.test(o.substring(0,s))){let a=e.substring(t.lineStarts[i-2],t.lineStarts[i-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===i&&c.col>r&&(a=Math.max(1,Math.min(c.col-r,80-s)));let l=" ".repeat(s)+"^".repeat(a);n.message+=`:
|
|
62
62
|
|
|
63
63
|
${o}
|
|
64
64
|
${l}
|
|
65
|
-
`}};Ji.YAMLError=Ki;Ji.YAMLParseError=
|
|
66
|
-
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let n of t.start)if(n.type==="newline")return!0;if(t.sep){for(let n of t.sep)if(n.type==="newline")return!0}if(
|
|
67
|
-
`+p.comment:a.comment=p.comment);continue}(p.newlineAfterProp||
|
|
68
|
-
`+C.comment:y.comment=C.comment);let k=new od.Pair(y);n.options.keepSourceTokens&&(k.srcToken=f),a.items.push(k)}}return l&&l<c&&r(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[i.offset,c,l??c],a}ud.resolveBlockMap=
|
|
69
|
-
`+R.comment:l.comment=R.comment),u=R.end;continue}!o&&n.options.strict&&
|
|
70
|
-
`+I:b.comment=I,R.comment=R.comment.substring(I.length+1)}}if(!o&&!k&&!R.found){let I=E?e(n,E,R,r):t(n,R.end,k,null,R,r);l.items.push(I),u=I.range[2],
|
|
71
|
-
`+L.comment:b.comment=L.comment);let z=new
|
|
72
|
-
`+m.comment:l.comment=m.comment),l.range=[i.offset,p,m.offset]}else l.range=[i.offset,p,p];return l}wd.resolveFlowCollection=
|
|
65
|
+
`}};Ji.YAMLError=Ki;Ji.YAMLParseError=pc;Ji.YAMLWarning=hc;Ji.prettifyError=wv});var Vi=v(td=>{"use strict";function yv(e,{flow:t,indicator:n,next:i,offset:r,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,f=a,u="",d="",h=!1,g=!1,p=null,m=null,w=null,y=null,C=null,k=null,E=null;for(let b of e)switch(g&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&s(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g=!1),p&&(l&&b.type!=="comment"&&b.type!=="newline"&&s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),b.type){case"space":!t&&(n!=="doc-start"||i?.type!=="flow-collection")&&b.source.includes(" ")&&(p=b),f=!0;break;case"comment":{f||s(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let L=b.source.substring(1)||" ";u?u+=d+L:u=L,d="",l=!1;break}case"newline":l?u?u+=b.source:(!k||n!=="seq-item-ind")&&(c=!0):d+=b.source,l=!0,h=!0,(m||w)&&(y=b),f=!0;break;case"anchor":m&&s(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&s(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=b,E??(E=b.offset),l=!1,f=!1,g=!0;break;case"tag":{w&&s(b,"MULTIPLE_TAGS","A node can have at most one tag"),w=b,E??(E=b.offset),l=!1,f=!1,g=!0;break}case n:(m||w)&&s(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),k&&s(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${t??"collection"}`),k=b,l=n==="seq-item-ind"||n==="explicit-key-ind",f=!1;break;case"comma":if(t){C&&s(b,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),C=b,l=!1,f=!1;break}default:s(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,f=!1}let R=e[e.length-1],I=R?R.offset+R.source.length:r;return g&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&s(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(l&&p.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&s(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:C,found:k,spaceBefore:c,comment:u,hasNewline:h,anchor:m,tag:w,newlineAfterProp:y,end:I,start:E??I}}td.resolveProps=yv});var Is=v(nd=>{"use strict";function gc(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
|
|
66
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let n of t.start)if(n.type==="newline")return!0;if(t.sep){for(let n of t.sep)if(n.type==="newline")return!0}if(gc(t.key)||gc(t.value))return!0}return!1;default:return!0}}nd.containsNewline=gc});var wc=v(id=>{"use strict";var vv=Is();function bv(e,t,n){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&vv.containsNewline(t)&&n(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}id.flowIndentCheck=bv});var yc=v(sd=>{"use strict";var rd=M();function Cv(e,t,n){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let r=typeof i=="function"?i:(s,o)=>s===o||rd.isScalar(s)&&rd.isScalar(o)&&s.value===o.value;return t.some(s=>r(s.key,n))}sd.mapIncludes=Cv});var fd=v(ud=>{"use strict";var od=Mt(),kv=Dt(),ad=Vi(),Sv=Is(),cd=wc(),Ev=yc(),ld="All mapping items must start at the same column";function Rv({composeNode:e,composeEmptyNode:t},n,i,r,s){let o=s?.nodeClass??kv.YAMLMap,a=new o(n.schema);n.atRoot&&(n.atRoot=!1);let c=i.offset,l=null;for(let f of i.items){let{start:u,key:d,sep:h,value:g}=f,p=ad.resolveProps(u,{indicator:"explicit-key-ind",next:d??h?.[0],offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0}),m=!p.found;if(m){if(d&&(d.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==i.indent&&r(c,"BAD_INDENT",ld)),!p.anchor&&!p.tag&&!h){l=p.end,p.comment&&(a.comment?a.comment+=`
|
|
67
|
+
`+p.comment:a.comment=p.comment);continue}(p.newlineAfterProp||Sv.containsNewline(d))&&r(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==i.indent&&r(c,"BAD_INDENT",ld);n.atKey=!0;let w=p.end,y=d?e(n,d,p,r):t(n,w,u,null,p,r);n.schema.compat&&cd.flowIndentCheck(i.indent,d,r),n.atKey=!1,Ev.mapIncludes(n,a.items,y)&&r(w,"DUPLICATE_KEY","Map keys must be unique");let C=ad.resolveProps(h??[],{indicator:"map-value-ind",next:g,offset:y.range[2],onError:r,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=C.end,C.found){m&&(g?.type==="block-map"&&!C.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&p.start<C.found.offset-1024&&r(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let k=g?e(n,g,C,r):t(n,c,h,null,C,r);n.schema.compat&&cd.flowIndentCheck(i.indent,g,r),c=k.range[2];let E=new od.Pair(y,k);n.options.keepSourceTokens&&(E.srcToken=f),a.items.push(E)}else{m&&r(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),C.comment&&(y.comment?y.comment+=`
|
|
68
|
+
`+C.comment:y.comment=C.comment);let k=new od.Pair(y);n.options.keepSourceTokens&&(k.srcToken=f),a.items.push(k)}}return l&&l<c&&r(l,"IMPOSSIBLE","Map comment with trailing content"),a.range=[i.offset,c,l??c],a}ud.resolveBlockMap=Rv});var md=v(dd=>{"use strict";var _v=Ft(),xv=Vi(),Pv=wc();function Ov({composeNode:e,composeEmptyNode:t},n,i,r,s){let o=s?.nodeClass??_v.YAMLSeq,a=new o(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=i.offset,l=null;for(let{start:f,value:u}of i.items){let d=xv.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:r,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?r(d.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(a.comment=d.comment);continue}let h=u?e(n,u,d,r):t(n,d.end,f,null,d,r);n.schema.compat&&Pv.flowIndentCheck(i.indent,u,r),c=h.range[2],a.items.push(h)}return a.range=[i.offset,c,l??c],a}dd.resolveBlockSeq=Ov});var Vn=v(pd=>{"use strict";function $v(e,t,n,i){let r="";if(e){let s=!1,o="";for(let a of e){let{source:c,type:l}=a;switch(l){case"space":s=!0;break;case"comment":{n&&!s&&i(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";r?r+=o+f:r=f,o="";break}case"newline":r&&(o+=c),s=!0;break;default:i(a,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:r,offset:t}}pd.resolveEnd=$v});var yd=v(wd=>{"use strict";var Iv=M(),Av=Mt(),hd=Dt(),Nv=Ft(),Tv=Vn(),gd=Vi(),jv=Is(),Lv=yc(),vc="Block collections are not allowed within flow collections",bc=e=>e&&(e.type==="block-map"||e.type==="block-seq");function Mv({composeNode:e,composeEmptyNode:t},n,i,r,s){let o=i.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?hd.YAMLMap:Nv.YAMLSeq),l=new c(n.schema);l.flow=!0;let f=n.atRoot;f&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let u=i.offset+i.start.source.length;for(let m=0;m<i.items.length;++m){let w=i.items[m],{start:y,key:C,sep:k,value:E}=w,R=gd.resolveProps(y,{flow:a,indicator:"explicit-key-ind",next:C??k?.[0],offset:u,onError:r,parentIndent:i.indent,startOnNewline:!1});if(!R.found){if(!R.anchor&&!R.tag&&!k&&!E){m===0&&R.comma?r(R.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):m<i.items.length-1&&r(R.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),R.comment&&(l.comment?l.comment+=`
|
|
69
|
+
`+R.comment:l.comment=R.comment),u=R.end;continue}!o&&n.options.strict&&jv.containsNewline(C)&&r(C,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)R.comma&&r(R.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(R.comma||r(R.start,"MISSING_CHAR",`Missing , between ${a} items`),R.comment){let I="";e:for(let b of y)switch(b.type){case"comma":case"space":break;case"comment":I=b.source.substring(1);break e;default:break e}if(I){let b=l.items[l.items.length-1];Iv.isPair(b)&&(b=b.value??b.key),b.comment?b.comment+=`
|
|
70
|
+
`+I:b.comment=I,R.comment=R.comment.substring(I.length+1)}}if(!o&&!k&&!R.found){let I=E?e(n,E,R,r):t(n,R.end,k,null,R,r);l.items.push(I),u=I.range[2],bc(E)&&r(I.range,"BLOCK_IN_FLOW",vc)}else{n.atKey=!0;let I=R.end,b=C?e(n,C,R,r):t(n,I,y,null,R,r);bc(C)&&r(b.range,"BLOCK_IN_FLOW",vc),n.atKey=!1;let L=gd.resolveProps(k??[],{flow:a,indicator:"map-value-ind",next:E,offset:b.range[2],onError:r,parentIndent:i.indent,startOnNewline:!1});if(L.found){if(!o&&!R.found&&n.options.strict){if(k)for(let K of k){if(K===L.found)break;if(K.type==="newline"){r(K,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}R.start<L.found.offset-1024&&r(L.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else E&&("source"in E&&E.source?.[0]===":"?r(E,"MISSING_CHAR",`Missing space after : in ${a}`):r(L.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let Ie=E?e(n,E,L,r):L.found?t(n,L.end,k,null,L,r):null;Ie?bc(E)&&r(Ie.range,"BLOCK_IN_FLOW",vc):L.comment&&(b.comment?b.comment+=`
|
|
71
|
+
`+L.comment:b.comment=L.comment);let z=new Av.Pair(b,Ie);if(n.options.keepSourceTokens&&(z.srcToken=w),o){let K=l;Lv.mapIncludes(n,K.items,b)&&r(I,"DUPLICATE_KEY","Map keys must be unique"),K.items.push(z)}else{let K=new hd.YAMLMap(n.schema);K.flow=!0,K.items.push(z);let Ce=(Ie??b).range;K.range=[b.range[0],Ce[1],Ce[2]],l.items.push(K)}u=Ie?Ie.range[2]:L.end}}let d=o?"}":"]",[h,...g]=i.end,p=u;if(h?.source===d)p=h.offset+h.source.length;else{let m=a[0].toUpperCase()+a.substring(1),w=f?`${m} must end with a ${d}`:`${m} in block collection must be sufficiently indented and end with a ${d}`;r(u,f?"MISSING_CHAR":"BAD_INDENT",w),h&&h.source.length!==1&&g.unshift(h)}if(g.length>0){let m=Tv.resolveEnd(g,p,n.options.strict,r);m.comment&&(l.comment?l.comment+=`
|
|
72
|
+
`+m.comment:l.comment=m.comment),l.range=[i.offset,p,m.offset]}else l.range=[i.offset,p,p];return l}wd.resolveFlowCollection=Mv});var bd=v(vd=>{"use strict";var qv=M(),Dv=X(),Fv=Dt(),Bv=Ft(),Wv=fd(),Hv=md(),Kv=yd();function Cc(e,t,n,i,r,s){let o=n.type==="block-map"?Wv.resolveBlockMap(e,t,n,i,s):n.type==="block-seq"?Hv.resolveBlockSeq(e,t,n,i,s):Kv.resolveFlowCollection(e,t,n,i,s),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}function Jv(e,t,n,i,r){let s=i.tag,o=s?t.directives.tagName(s.source,d=>r(s,"TAG_RESOLVE_FAILED",d)):null;if(n.type==="block-seq"){let{anchor:d,newlineAfterProp:h}=i,g=d&&s?d.offset>s.offset?d:s:d??s;g&&(!h||h.offset<g.offset)&&r(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===Fv.YAMLMap.tagName&&a==="map"||o===Bv.YAMLSeq.tagName&&a==="seq")return Cc(e,t,n,r,o);let c=t.schema.tags.find(d=>d.tag===o&&d.collection===a);if(!c){let d=t.schema.knownTags[o];if(d?.collection===a)t.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?r(s,"BAD_COLLECTION_TYPE",`${d.tag} used for ${a} collection, but expects ${d.collection??"scalar"}`,!0):r(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Cc(e,t,n,r,o)}let l=Cc(e,t,n,r,o,c),f=c.resolve?.(l,d=>r(s,"TAG_RESOLVE_FAILED",d),t.options)??l,u=qv.isNode(f)?f:new Dv.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}vd.composeCollection=Jv});var Sc=v(Cd=>{"use strict";var kc=X();function Uv(e,t,n){let i=t.offset,r=Vv(t,e.options.strict,n);if(!r)return{value:"",type:null,comment:"",range:[i,i,i]};let s=r.mode===">"?kc.Scalar.BLOCK_FOLDED:kc.Scalar.BLOCK_LITERAL,o=t.source?Yv(t.source):[],a=o.length;for(let p=o.length-1;p>=0;--p){let m=o[p][1];if(m===""||m==="\r")a=p;else break}if(a===0){let p=r.chomp==="+"&&o.length>0?`
|
|
73
73
|
`.repeat(Math.max(1,o.length-1)):"",m=i+r.length;return t.source&&(m+=t.source.length),{value:p,type:s,comment:r.comment,range:[i,m,m]}}let c=t.indent+r.indent,l=t.offset+r.length,f=0;for(let p=0;p<a;++p){let[m,w]=o[p];if(w===""||w==="\r")r.indent===0&&m.length>c&&(c=m.length);else{m.length<c&&n(l+m.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),r.indent===0&&(c=m.length),f=p,c===0&&!e.atRoot&&n(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=m.length+w.length+1}for(let p=o.length-1;p>=a;--p)o[p][0].length>c&&(a=p+1);let u="",d="",h=!1;for(let p=0;p<f;++p)u+=o[p][0].slice(c)+`
|
|
74
|
-
`;for(let p=f;p<a;++p){let[m,w]=o[p];l+=m.length+w.length+1;let y=w[w.length-1]==="\r";if(y&&(w=w.slice(0,-1)),w&&m.length<c){let k=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;n(l-w.length-(y?2:1),"BAD_INDENT",k),m=""}s===
|
|
74
|
+
`;for(let p=f;p<a;++p){let[m,w]=o[p];l+=m.length+w.length+1;let y=w[w.length-1]==="\r";if(y&&(w=w.slice(0,-1)),w&&m.length<c){let k=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;n(l-w.length-(y?2:1),"BAD_INDENT",k),m=""}s===kc.Scalar.BLOCK_LITERAL?(u+=d+m.slice(c)+w,d=`
|
|
75
75
|
`):m.length>c||w[0]===" "?(d===" "?d=`
|
|
76
76
|
`:!h&&d===`
|
|
77
77
|
`&&(d=`
|
|
@@ -84,46 +84,46 @@ ${l}
|
|
|
84
84
|
`+o[p][0].slice(c);u[u.length-1]!==`
|
|
85
85
|
`&&(u+=`
|
|
86
86
|
`);break;default:u+=`
|
|
87
|
-
`}let g=i+r.length+t.source.length;return{value:u,type:s,comment:r.comment,range:[i,g,g]}}function
|
|
87
|
+
`}let g=i+r.length+t.source.length;return{value:u,type:s,comment:r.comment,range:[i,g,g]}}function Vv({offset:e,props:t},n,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:r}=t[0],s=r[0],o=0,a="",c=-1;for(let d=1;d<r.length;++d){let h=r[d];if(!a&&(h==="-"||h==="+"))a=h;else{let g=Number(h);!o&&g?o=g:c===-1&&(c=e+d)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${r}`);let l=!1,f="",u=r.length;for(let d=1;d<t.length;++d){let h=t[d];switch(h.type){case"space":l=!0;case"newline":u+=h.source.length;break;case"comment":n&&!l&&i(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=h.source.length,f=h.source.substring(1);break;case"error":i(h,"UNEXPECTED_TOKEN",h.message),u+=h.source.length;break;default:{let g=`Unexpected token in block scalar header: ${h.type}`;i(h,"UNEXPECTED_TOKEN",g);let p=h.source;p&&typeof p=="string"&&(u+=p.length)}}}return{mode:s,indent:o,chomp:a,comment:f,length:u}}function Yv(e){let t=e.split(/\n( *)/),n=t[0],i=n.match(/^( *)/),s=[i?.[1]?[i[1],n.slice(i[1].length)]:["",n]];for(let o=1;o<t.length;o+=2)s.push([t[o],t[o+1]]);return s}Cd.resolveBlockScalar=Uv});var Rc=v(Sd=>{"use strict";var Ec=X(),Gv=Vn();function zv(e,t,n){let{offset:i,type:r,source:s,end:o}=e,a,c,l=(d,h,g)=>n(i+d,h,g);switch(r){case"scalar":a=Ec.Scalar.PLAIN,c=Xv(s,l);break;case"single-quoted-scalar":a=Ec.Scalar.QUOTE_SINGLE,c=Qv(s,l);break;case"double-quoted-scalar":a=Ec.Scalar.QUOTE_DOUBLE,c=Zv(s,l);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[i,i+s.length,i+s.length]}}let f=i+s.length,u=Gv.resolveEnd(o,f,t,n);return{value:c,type:a,comment:u.comment,range:[i,f,u.offset]}}function Xv(e,t){let n="";switch(e[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 ${e[0]}`;break}case"@":case"`":{n=`reserved character ${e[0]}`;break}}return n&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),kd(e)}function Qv(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),kd(e.slice(1,-1)).replace(/''/g,"'")}function kd(e){let t,n;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
88
|
`,"sy"),n=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
89
|
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let i=t.exec(e);if(!i)return e;let r=i[1],s=" ",o=t.lastIndex;for(n.lastIndex=o;i=n.exec(e);)i[1]===""?s===`
|
|
90
90
|
`?r+=s:s=`
|
|
91
|
-
`:(r+=s+i[1],s=" "),o=n.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,i=a.exec(e),r+s+(i?.[1]??"")}function
|
|
91
|
+
`:(r+=s+i[1],s=" "),o=n.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,i=a.exec(e),r+s+(i?.[1]??"")}function Zv(e,t){let n="";for(let i=1;i<e.length-1;++i){let r=e[i];if(!(r==="\r"&&e[i+1]===`
|
|
92
92
|
`))if(r===`
|
|
93
|
-
`){let{fold:s,offset:o}=
|
|
93
|
+
`){let{fold:s,offset:o}=eb(e,i);n+=s,i=o}else if(r==="\\"){let s=e[++i],o=tb[s];if(o)n+=o;else if(s===`
|
|
94
94
|
`)for(s=e[i+1];s===" "||s===" ";)s=e[++i+1];else if(s==="\r"&&e[i+1]===`
|
|
95
|
-
`)for(s=e[++i+1];s===" "||s===" ";)s=e[++i+1];else if(s==="x"||s==="u"||s==="U"){let a=s==="x"?2:s==="u"?4:8;n+=
|
|
95
|
+
`)for(s=e[++i+1];s===" "||s===" ";)s=e[++i+1];else if(s==="x"||s==="u"||s==="U"){let a=s==="x"?2:s==="u"?4:8;n+=nb(e,i+1,a,t),i+=a}else{let a=e.substr(i-1,2);t(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),n+=a}}else if(r===" "||r===" "){let s=i,o=e[i+1];for(;o===" "||o===" ";)o=e[++i+1];o!==`
|
|
96
96
|
`&&!(o==="\r"&&e[i+2]===`
|
|
97
|
-
`)&&(n+=i>s?e.slice(s,i+1):r)}else n+=r}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),n}function
|
|
97
|
+
`)&&(n+=i>s?e.slice(s,i+1):r)}else n+=r}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),n}function eb(e,t){let n="",i=e[t+1];for(;(i===" "||i===" "||i===`
|
|
98
98
|
`||i==="\r")&&!(i==="\r"&&e[t+2]!==`
|
|
99
99
|
`);)i===`
|
|
100
100
|
`&&(n+=`
|
|
101
|
-
`),t+=1,i=e[t+1];return n||(n=" "),{fold:n,offset:t}}var
|
|
102
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
101
|
+
`),t+=1,i=e[t+1];return n||(n=" "),{fold:n,offset:t}}var tb={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function nb(e,t,n,i){let r=e.substr(t,n),o=r.length===n&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):NaN;try{return String.fromCodePoint(o)}catch{let a=e.substr(t-2,n+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}Sd.resolveFlowScalar=zv});var _d=v(Rd=>{"use strict";var wn=M(),Ed=X(),ib=Sc(),rb=Rc();function sb(e,t,n,i){let{value:r,type:s,comment:o,range:a}=t.type==="block-scalar"?ib.resolveBlockScalar(e,t,i):rb.resolveFlowScalar(t,e.options.strict,i),c=n?e.directives.tagName(n.source,u=>i(n,"TAG_RESOLVE_FAILED",u)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[wn.SCALAR]:c?l=ob(e.schema,r,c,n,i):t.type==="scalar"?l=ab(e,r,t,i):l=e.schema[wn.SCALAR];let f;try{let u=l.resolve(r,d=>i(n??t,"TAG_RESOLVE_FAILED",d),e.options);f=wn.isScalar(u)?u:new Ed.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);i(n??t,"TAG_RESOLVE_FAILED",d),f=new Ed.Scalar(r)}return f.range=a,f.source=r,s&&(f.type=s),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function ob(e,t,n,i,r){if(n==="!")return e[wn.SCALAR];let s=[];for(let a of e.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(t))return a;let o=e.knownTags[n];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),e[wn.SCALAR])}function ab({atKey:e,directives:t,schema:n},i,r,s){let o=n.tags.find(a=>(a.default===!0||e&&a.default==="key")&&a.test?.test(i))||n[wn.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(i))??n[wn.SCALAR];if(o.tag!==a.tag){let c=t.tagString(o.tag),l=t.tagString(a.tag),f=`Value may be parsed as either ${c} or ${l}`;s(r,"TAG_RESOLVE_FAILED",f,!0)}}return o}Rd.composeScalar=sb});var Pd=v(xd=>{"use strict";function cb(e,t,n){if(t){n??(n=t.length);for(let i=n-1;i>=0;--i){let r=t[i];switch(r.type){case"space":case"comment":case"newline":e-=r.source.length;continue}for(r=t[++i];r?.type==="space";)e+=r.source.length,r=t[++i];break}}return e}xd.emptyScalarPosition=cb});var Id=v(xc=>{"use strict";var lb=xi(),ub=M(),fb=bd(),Od=_d(),db=Vn(),mb=Pd(),pb={composeNode:$d,composeEmptyNode:_c};function $d(e,t,n,i){let r=e.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=n,l,f=!0;switch(t.type){case"alias":l=hb(e,t,i),(a||c)&&i(t,"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=Od.composeScalar(e,t,c,i),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=fb.composeCollection(pb,e,t,n,i),a&&(l.anchor=a.source.substring(1))}catch(u){let d=u instanceof Error?u.message:String(u);i(t,"RESOURCE_EXHAUSTION",d)}break;default:{let u=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",u),f=!1}}return l??(l=_c(e,t.offset,void 0,null,n,i)),a&&l.anchor===""&&i(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&e.options.stringKeys&&(!ub.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&f&&(l.srcToken=t),l}function _c(e,t,n,i,{spaceBefore:r,comment:s,anchor:o,tag:a,end:c},l){let f={type:"scalar",offset:mb.emptyScalarPosition(t,n,i),indent:-1,source:""},u=Od.composeScalar(e,f,a,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(u.spaceBefore=!0),s&&(u.comment=s,u.range[2]=c),u}function hb({options:e},{offset:t,source:n,end:i},r){let s=new lb.Alias(n.substring(1));s.source===""&&r(t,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&r(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+n.length,a=db.resolveEnd(i,o,e.strict,r);return s.range=[t,o,a.offset],a.comment&&(s.comment=a.comment),s}xc.composeEmptyNode=_c;xc.composeNode=$d});var Td=v(Nd=>{"use strict";var gb=Hi(),Ad=Id(),wb=Vn(),yb=Vi();function vb(e,t,{offset:n,start:i,value:r,end:s},o){let a=Object.assign({_directives:t},e),c=new gb.Document(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=yb.resolveProps(i,{indicator:"doc-start",next:r??s?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?Ad.composeNode(l,r,f,o):Ad.composeEmptyNode(l,f.end,i,null,f,o);let u=c.contents.range[2],d=wb.resolveEnd(s,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[n,u,d.offset],c}Nd.composeDoc=vb});var Oc=v(Md=>{"use strict";var bb=Br("process"),Cb=pa(),kb=Hi(),Yi=Ui(),jd=M(),Sb=Td(),Eb=Vn();function Gi(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n=="string"?n.length:1)]}function Ld(e){let t="",n=!1,i=!1;for(let r=0;r<e.length;++r){let s=e[r];switch(s[0]){case"#":t+=(t===""?"":i?`
|
|
103
103
|
|
|
104
104
|
`:`
|
|
105
|
-
`)+(s.substring(1)||" "),n=!0,i=!1;break;case"%":e[r+1]?.[0]!=="#"&&(r+=1),n=!1;break;default:n||(i=!0),n=!1}}return{comment:t,afterEmptyLine:i}}var
|
|
105
|
+
`)+(s.substring(1)||" "),n=!0,i=!1;break;case"%":e[r+1]?.[0]!=="#"&&(r+=1),n=!1;break;default:n||(i=!0),n=!1}}return{comment:t,afterEmptyLine:i}}var Pc=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,i,r,s)=>{let o=Gi(n);s?this.warnings.push(new Yi.YAMLWarning(o,i,r)):this.errors.push(new Yi.YAMLParseError(o,i,r))},this.directives=new Cb.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,n){let{comment:i,afterEmptyLine:r}=Ld(this.prelude);if(i){let s=t.contents;if(n)t.comment=t.comment?`${t.comment}
|
|
106
106
|
${i}`:i;else if(r||t.directives.docStart||!s)t.commentBefore=i;else if(jd.isCollection(s)&&!s.flow&&s.items.length>0){let o=s.items[0];jd.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${i}
|
|
107
107
|
${a}`:i}else{let o=s.commentBefore;s.commentBefore=o?`${i}
|
|
108
|
-
${o}`:i}}if(n){for(let s=0;s<this.errors.length;++s)t.errors.push(this.errors[s]);for(let s=0;s<this.warnings.length;++s)t.warnings.push(this.warnings[s])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Ld(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,n=!1,i=-1){for(let r of t)yield*this.next(r);yield*this.end(n,i)}*next(t){switch(
|
|
109
|
-
${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new Yi.YAMLParseError(Gi(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let i=Object.assign({_directives:this.directives},this.options),r=new
|
|
108
|
+
${o}`:i}}if(n){for(let s=0;s<this.errors.length;++s)t.errors.push(this.errors[s]);for(let s=0;s<this.warnings.length;++s)t.warnings.push(this.warnings[s])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Ld(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,n=!1,i=-1){for(let r of t)yield*this.next(r);yield*this.end(n,i)}*next(t){switch(bb.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(n,i,r)=>{let s=Gi(t);s[0]+=n,this.onError(s,"BAD_DIRECTIVE",i,r)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let n=Sb.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let n=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,i=new Yi.YAMLParseError(Gi(t),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new Yi.YAMLParseError(Gi(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let n=Eb.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let i=this.doc.comment;this.doc.comment=i?`${i}
|
|
109
|
+
${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new Yi.YAMLParseError(Gi(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let i=Object.assign({_directives:this.directives},this.options),r=new kb.Document(void 0,i);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,n,n],this.decorate(r,!1),yield r}}};Md.Composer=Pc});var Fd=v(As=>{"use strict";var Rb=Sc(),_b=Rc(),xb=Ui(),qd=Ai();function Pb(e,t=!0,n){if(e){let i=(r,s,o)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(n)n(a,s,o);else throw new xb.YAMLParseError([a,a+1],s,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return _b.resolveFlowScalar(e,t,i);case"block-scalar":return Rb.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function Ob(e,t){let{implicitKey:n=!1,indent:i,inFlow:r=!1,offset:s=-1,type:o="PLAIN"}=t,a=qd.stringifyString({type:o,value:e},{implicitKey:n,indent:i>0?" ".repeat(i):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:i,source:`
|
|
110
110
|
`}];switch(a[0]){case"|":case">":{let l=a.indexOf(`
|
|
111
111
|
`),f=a.substring(0,l),u=a.substring(l+1)+`
|
|
112
112
|
`,d=[{type:"block-scalar-header",offset:s,indent:i,source:f}];return Dd(d,c)||d.push({type:"newline",offset:-1,indent:i,source:`
|
|
113
|
-
`}),{type:"block-scalar",offset:s,indent:i,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:s,indent:i,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:i,source:a,end:c};default:return{type:"scalar",offset:s,indent:i,source:a,end:c}}}function
|
|
113
|
+
`}),{type:"block-scalar",offset:s,indent:i,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:s,indent:i,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:s,indent:i,source:a,end:c};default:return{type:"scalar",offset:s,indent:i,source:a,end:c}}}function $b(e,t,n={}){let{afterKey:i=!1,implicitKey:r=!1,inFlow:s=!1,type:o}=n,a="indent"in e?e.indent:null;if(i&&typeof a=="number"&&(a+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=qd.stringifyString({type:o,value:t},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Ib(e,c);break;case'"':$c(e,c,"double-quoted-scalar");break;case"'":$c(e,c,"single-quoted-scalar");break;default:$c(e,c,"scalar")}}function Ib(e,t){let n=t.indexOf(`
|
|
114
114
|
`),i=t.substring(0,n),r=t.substring(n+1)+`
|
|
115
115
|
`;if(e.type==="block-scalar"){let s=e.props[0];if(s.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s.source=i,e.source=r}else{let{offset:s}=e,o="indent"in e?e.indent:-1,a=[{type:"block-scalar-header",offset:s,indent:o,source:i}];Dd(a,"end"in e?e.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
|
|
116
|
-
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:a,source:r})}}function Dd(e,t){if(t)for(let n of t)switch(n.type){case"space":case"comment":e.push(n);break;case"newline":return e.push(n),!0}return!1}function
|
|
117
|
-
`};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{let i="indent"in e?e.indent:-1,r="end"in e&&Array.isArray(e.end)?e.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(e))s!=="type"&&s!=="offset"&&delete e[s];Object.assign(e,{type:n,indent:i,source:t,end:r})}}}As.createScalarToken=
|
|
116
|
+
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:a,source:r})}}function Dd(e,t){if(t)for(let n of t)switch(n.type){case"space":case"comment":e.push(n);break;case"newline":return e.push(n),!0}return!1}function $c(e,t,n){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=n,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),r=t.length;e.props[0].type==="block-scalar-header"&&(r-=e.props[0].source.length);for(let s of i)s.offset+=r;delete e.props,Object.assign(e,{type:n,source:t,end:i});break}case"block-map":case"block-seq":{let r={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
117
|
+
`};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{let i="indent"in e?e.indent:-1,r="end"in e&&Array.isArray(e.end)?e.end.filter(s=>s.type==="space"||s.type==="comment"||s.type==="newline"):[];for(let s of Object.keys(e))s!=="type"&&s!=="offset"&&delete e[s];Object.assign(e,{type:n,indent:i,source:t,end:r})}}}As.createScalarToken=Ob;As.resolveAsScalar=Pb;As.setScalarValue=$b});var Wd=v(Bd=>{"use strict";var Ab=e=>"type"in e?Ts(e):Ns(e);function Ts(e){switch(e.type){case"block-scalar":{let t="";for(let n of e.props)t+=Ts(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(let n of e.items)t+=Ns(n);return t}case"flow-collection":{let t=e.start.source;for(let n of e.items)t+=Ns(n);for(let n of e.end)t+=n.source;return t}case"document":{let t=Ns(e);if(e.end)for(let n of e.end)t+=n.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let n of e.end)t+=n.source;return t}}}function Ns({start:e,key:t,sep:n,value:i}){let r="";for(let s of e)r+=s.source;if(t&&(r+=Ts(t)),n)for(let s of n)r+=s.source;return i&&(r+=Ts(i)),r}Bd.stringify=Ab});var Ud=v(Jd=>{"use strict";var Ic=Symbol("break visit"),Nb=Symbol("skip children"),Hd=Symbol("remove item");function yn(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Kd(Object.freeze([]),e,t)}yn.BREAK=Ic;yn.SKIP=Nb;yn.REMOVE=Hd;yn.itemAtPath=(e,t)=>{let n=e;for(let[i,r]of t){let s=n?.[i];if(s&&"items"in s)n=s.items[r];else return}return n};yn.parentCollection=(e,t)=>{let n=yn.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],r=n?.[i];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function Kd(e,t,n){let i=n(t,e);if(typeof i=="symbol")return i;for(let r of["key","value"]){let s=t[r];if(s&&"items"in s){for(let o=0;o<s.items.length;++o){let a=Kd(Object.freeze(e.concat([[r,o]])),s.items[o],n);if(typeof a=="number")o=a-1;else{if(a===Ic)return Ic;a===Hd&&(s.items.splice(o,1),o-=1)}}typeof i=="function"&&r==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}Jd.visit=yn});var js=v(Se=>{"use strict";var Ac=Fd(),Tb=Wd(),jb=Ud(),Nc="\uFEFF",Tc="",jc="",Lc="",Lb=e=>!!e&&"items"in e,Mb=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function qb(e){switch(e){case Nc:return"<BOM>";case Tc:return"<DOC>";case jc:return"<FLOW_END>";case Lc:return"<SCALAR>";default:return JSON.stringify(e)}}function Db(e){switch(e){case Nc:return"byte-order-mark";case Tc:return"doc-mode";case jc:return"flow-error-end";case Lc: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(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Se.createScalarToken=
|
|
120
|
-
`:case"\r":case" ":return!0;default:return!1}}var Vd=new Set("0123456789ABCDEFabcdef"),
|
|
121
|
-
\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(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Se.createScalarToken=Ac.createScalarToken;Se.resolveAsScalar=Ac.resolveAsScalar;Se.setScalarValue=Ac.setScalarValue;Se.stringify=Tb.stringify;Se.visit=jb.visit;Se.BOM=Nc;Se.DOCUMENT=Tc;Se.FLOW_END=jc;Se.SCALAR=Lc;Se.isCollection=Lb;Se.isScalar=Mb;Se.prettyToken=qb;Se.tokenType=Db});var Dc=v(Yd=>{"use strict";var zi=js();function He(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var Vd=new Set("0123456789ABCDEFabcdef"),Fb=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ls=new Set(",[]{}"),Bb=new Set(` ,[]{}
|
|
121
|
+
\r `),Mc=e=>!e||Bb.has(e),qc=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,n=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!n;let i=this.next??"stream";for(;i&&(n||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,n=this.buffer[t];for(;n===" "||n===" ";)n=this.buffer[++t];return!n||n==="#"||n===`
|
|
122
122
|
`?!0:n==="\r"?this.buffer[t+1]===`
|
|
123
123
|
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let n=this.buffer[t];if(this.indentNext>0){let i=0;for(;n===" ";)n=this.buffer[++i+t];if(n==="\r"){let r=this.buffer[i+t+1];if(r===`
|
|
124
124
|
`||!r&&!this.atEnd)return t+i+1}return n===`
|
|
125
125
|
`||i>=this.indentNext||!n&&!this.atEnd?t+i:-1}if(n==="-"||n==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&He(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
|
|
126
|
-
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===zi.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let n=t.length,i=t.indexOf("#");for(;i!==-1;){let s=t[i-1];if(s===" "||s===" "){n=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let s=t[n-1];if(s===" "||s===" ")n-=1;else break}let r=(yield*this.pushCount(n))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-r),this.pushNewline(),"stream"}if(this.atLineEnd()){let n=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-n),yield*this.pushNewline(),"stream"}return yield zi.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let n=this.peek(3);if((n==="---"||n==="...")&&He(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&&!He(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&He(n)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(t[n]){case"#":yield*this.pushCount(t.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(
|
|
126
|
+
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===zi.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let n=t.length,i=t.indexOf("#");for(;i!==-1;){let s=t[i-1];if(s===" "||s===" "){n=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let s=t[n-1];if(s===" "||s===" ")n-=1;else break}let r=(yield*this.pushCount(n))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-r),this.pushNewline(),"stream"}if(this.atLineEnd()){let n=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-n),yield*this.pushNewline(),"stream"}return yield zi.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let n=this.peek(3);if((n==="---"||n==="...")&&He(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&&!He(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&He(n)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(t[n]){case"#":yield*this.pushCount(t.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(Mc),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,n,i=-1;do t=yield*this.pushNewline(),t>0?(n=yield*this.pushSpaces(!1),this.indentValue=i=n):n=0,n+=yield*this.pushSpaces(!0);while(t+n>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&r[0]!=="#"||i===0&&(r.startsWith("---")||r.startsWith("..."))&&He(r[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield zi.FLOW_END,yield*this.parseLineStart();let s=0;for(;r[s]===",";)s+=yield*this.pushCount(1),s+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(s+=yield*this.pushIndicators(),r[s]){case void 0:return"flow";case"#":return yield*this.pushCount(r.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(Mc),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||He(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),n=this.buffer.indexOf(t,this.pos+1);if(t==="'")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 i=this.buffer.substring(0,n),r=i.indexOf(`
|
|
127
127
|
`,this.pos);if(r!==-1){for(;r!==-1;){let s=this.continueScalar(r+1);if(s===-1)break;r=i.indexOf(`
|
|
128
128
|
`,s)}r!==-1&&(n=r-(i[r-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 t=this.pos;for(;;){let n=this.buffer[++t];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=>He(n)||n==="#")}*parseBlockScalar(){let t=this.pos-1,n=0,i;e:for(let s=this.pos;i=this.buffer[s];++s)switch(i){case" ":n+=1;break;case`
|
|
129
129
|
`:t=s,n=0;break;case"\r":{let o=this.buffer[s+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
@@ -133,16 +133,16 @@ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.pus
|
|
|
133
133
|
`&&s>=this.pos&&s+1+n>a)t=s;else break}while(!0);return yield zi.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,n=this.pos-1,i=this.pos-1,r;for(;r=this.buffer[++i];)if(r===":"){let s=this.buffer[i+1];if(He(s)||t&&Ls.has(s))break;n=i}else if(He(r)){let s=this.buffer[i+1];if(r==="\r"&&(s===`
|
|
134
134
|
`?(i+=1,r=`
|
|
135
135
|
`,s=this.buffer[i+1]):n=i),s==="#"||t&&Ls.has(s))break;if(r===`
|
|
136
|
-
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&Ls.has(r))break;n=i}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield zi.SCALAR,yield*this.pushToIndex(n+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,n){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(n&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(
|
|
136
|
+
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&Ls.has(r))break;n=i}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield zi.SCALAR,yield*this.pushToIndex(n+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,n){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(n&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Mc),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,i=this.charAt(1);if(He(i)||n&&Ls.has(i)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,n=this.buffer[t];for(;!He(n)&&n!==">";)n=this.buffer[++t];return yield*this.pushToIndex(n===">"?t+1:t,!1)}else{let t=this.pos+1,n=this.buffer[t];for(;n;)if(Fb.has(n))n=this.buffer[++t];else if(n==="%"&&Vd.has(this.buffer[t+1])&&Vd.has(this.buffer[t+2]))n=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
|
|
137
137
|
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
138
|
-
`?yield*this.pushCount(2):0}*pushSpaces(t){let n=this.pos-1,i;do i=this.buffer[++n];while(i===" "||t&&i===" ");let r=n-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=n),r}*pushUntil(t){let n=this.pos,i=this.buffer[n];for(;!t(i);)i=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};Yd.Lexer=
|
|
138
|
+
`?yield*this.pushCount(2):0}*pushSpaces(t){let n=this.pos-1,i;do i=this.buffer[++n];while(i===" "||t&&i===" ");let r=n-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=n),r}*pushUntil(t){let n=this.pos,i=this.buffer[n];for(;!t(i);)i=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};Yd.Lexer=qc});var Bc=v(Gd=>{"use strict";var Fc=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let n=0,i=this.lineStarts.length;for(;n<i;){let s=n+i>>1;this.lineStarts[s]<t?n=s+1:i=s}if(this.lineStarts[n]===t)return{line:n+1,col:1};if(n===0)return{line:0,col:t};let r=this.lineStarts[n-1];return{line:n,col:t-r+1}}}};Gd.LineCounter=Fc});var Hc=v(em=>{"use strict";var Wb=Br("process"),zd=js(),Hb=Dc();function Bt(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function Xd(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function Zd(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Ms(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Yn(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function qs(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function Qd(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Bt(t.start,"explicit-key-ind")&&!Bt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Zd(t.value)?t.value.end?qs(t.value.end,t.sep):t.value.end=t.sep:qs(t.start,t.sep),delete t.sep)}var Wc=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Hb.Lexer,this.onNewLine=t}*parse(t,n=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,n))yield*this.next(i);n||(yield*this.end())}*next(t){if(this.source=t,Wb.env.LOG_TOKENS&&console.log("|",zd.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let n=zd.tokenType(t);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+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let n=t??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 i=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in i?i.indent:0:n.type==="flow-collection"&&i.type==="document"&&(n.indent=0),n.type==="flow-collection"&&Qd(n),i.type){case"document":i.value=n;break;case"block-scalar":i.props.push(n);break;case"block-map":{let r=i.items[i.items.length-1];if(r.value){i.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=n;else{Object.assign(r,{key:n,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=i.items[i.items.length-1];r.value?i.items.push({start:[],value:n}):r.value=n;break}case"flow-collection":{let r=i.items[i.items.length-1];!r||r.value?i.items.push({start:[],key:n,sep:[]}):r.sep?r.value=n:Object.assign(r,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let r=n.items[n.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&Xd(r.start)===-1&&(n.indent===0||r.start.every(s=>s.type!=="comment"||s.indent<n.indent))&&(i.type==="document"?i.end=r.start:i.items.push({start:r.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 t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{Xd(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let n=Ms(this.peek(2)),i=Yn(n),r;t.end?(r=t.end,r.push(this.sourceToken),delete t.end):r=[this.sourceToken];let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let n=this.source.indexOf(`
|
|
139
139
|
`)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
|
|
140
140
|
`,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let i="end"in n.value?n.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.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)t.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,t.indent)){let r=t.items[t.items.length-2]?.value?.end;if(Array.isArray(r)){qs(r,n.start),r.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,r=i&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",s=[];if(r&&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>t.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":r||n.value?(s.push(this.sourceToken),t.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):r||n.value?(s.push(this.sourceToken),t.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)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Bt(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(Zd(n.key)&&!Bt(n.sep,"newline")){let o=Yn(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(Bt(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let o=Yn(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||r?t.items.push({start:s,key:null,sep:[this.sourceToken]}):Bt(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);r||n.value?(t.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(t);if(o){if(o.type==="block-seq"){if(!n.explicitKey&&n.sep&&!Bt(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 i&&t.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(n.value){let i="end"in n.value?n.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,t.indent)){let r=t.items[t.items.length-2]?.value?.end;if(Array.isArray(r)){qs(r,n.start),r.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=t.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;n.value||Bt(n.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let n=t.items[t.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?t.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?t.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 r=this.flowScalar(this.type);!n||n.value?t.items.push({start:[],key:r,sep:[]}):n.sep?this.stack.push(r):Object.assign(n,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===t.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let r=Ms(i),s=Yn(r);Qd(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:s,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}}flowScalar(t){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:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Ms(t),i=Yn(n);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Ms(t),i=Yn(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,n){return this.type!=="comment"||this.indent<=n?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};em.Parser=
|
|
143
|
-
`)){let o=
|
|
142
|
+
`,n)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Ms(t),i=Yn(n);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Ms(t),i=Yn(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,n){return this.type!=="comment"||this.indent<=n?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};em.Parser=Wc});var sm=v(Qi=>{"use strict";var tm=Oc(),Kb=Hi(),Xi=Ui(),Jb=xa(),Ub=M(),Vb=Bc(),nm=Hc();function im(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Vb.LineCounter||null,prettyErrors:t}}function Yb(e,t={}){let{lineCounter:n,prettyErrors:i}=im(t),r=new nm.Parser(n?.addNewLine),s=new tm.Composer(t),o=Array.from(s.compose(r.parse(e)));if(i&&n)for(let a of o)a.errors.forEach(Xi.prettifyError(e,n)),a.warnings.forEach(Xi.prettifyError(e,n));return o.length>0?o:Object.assign([],{empty:!0},s.streamInfo())}function rm(e,t={}){let{lineCounter:n,prettyErrors:i}=im(t),r=new nm.Parser(n?.addNewLine),s=new tm.Composer(t),o=null;for(let a of s.compose(r.parse(e),!0,e.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Xi.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&n&&(o.errors.forEach(Xi.prettifyError(e,n)),o.warnings.forEach(Xi.prettifyError(e,n))),o}function Gb(e,t,n){let i;typeof t=="function"?i=t:n===void 0&&t&&typeof t=="object"&&(n=t);let r=rm(e,n);if(!r)return null;if(r.warnings.forEach(s=>Jb.warn(r.options.logLevel,s)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:i},n))}function zb(e,t,n){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:n===void 0&&t&&(n=t),typeof n=="string"&&(n=n.length),typeof n=="number"){let r=Math.round(n);n=r<1?void 0:r>8?{indent:8}:{indent:r}}if(e===void 0){let{keepUndefined:r}=n??t??{};if(!r)return}return Ub.isDocument(e)&&!i?e.toString(n):new Kb.Document(e,i,n).toString(n)}Qi.parse=Gb;Qi.parseAllDocuments=Yb;Qi.parseDocument=rm;Qi.stringify=zb});var nt=v(F=>{"use strict";var Xb=Oc(),Qb=Hi(),Zb=lc(),Kc=Ui(),eC=xi(),Wt=M(),tC=Mt(),nC=X(),iC=Dt(),rC=Ft(),sC=js(),oC=Dc(),aC=Bc(),cC=Hc(),Ds=sm(),om=Si();F.Composer=Xb.Composer;F.Document=Qb.Document;F.Schema=Zb.Schema;F.YAMLError=Kc.YAMLError;F.YAMLParseError=Kc.YAMLParseError;F.YAMLWarning=Kc.YAMLWarning;F.Alias=eC.Alias;F.isAlias=Wt.isAlias;F.isCollection=Wt.isCollection;F.isDocument=Wt.isDocument;F.isMap=Wt.isMap;F.isNode=Wt.isNode;F.isPair=Wt.isPair;F.isScalar=Wt.isScalar;F.isSeq=Wt.isSeq;F.Pair=tC.Pair;F.Scalar=nC.Scalar;F.YAMLMap=iC.YAMLMap;F.YAMLSeq=rC.YAMLSeq;F.CST=sC;F.Lexer=oC.Lexer;F.LineCounter=aC.LineCounter;F.Parser=cC.Parser;F.parse=Ds.parse;F.parseAllDocuments=Ds.parseAllDocuments;F.parseDocument=Ds.parseDocument;F.stringify=Ds.stringify;F.visit=om.visit;F.visitAsync=om.visitAsync});import Bs from"path";function cm(e,t){return Fs[t][e]}function fC(e,t,n){let i=/^(\s*)([a-z_]+):/u.exec(e);if(!i)return null;let r=i[1].length,s=i[2];if(r===0&&s in Fs.en)return s;if(r===2&&t){let o=`${t}.${s}`;if(o in Fs.en)return o}if(r===4&&t==="native"&&n==="snapshot"){let o=`native.snapshot.${s}`;if(o in Fs.en)return o}return null}function Gn(e,t){let n=[],i=null,r=null;for(let s of(0,Hs.stringify)(e).trimEnd().split(`
|
|
143
|
+
`)){let o=fC(s,i,r);if(o){let a=s.match(/^\s*/u)?.[0]??"";for(let c of cm(o,t).split(`
|
|
144
144
|
`))n.push(`${a}${c}`)}n.push(s),/^[a-z_]+:/u.test(s)?(s.startsWith("native:")?i="native":s.startsWith("classic:")?i="classic":i=null,r=null):/^ {2}[a-z_]+:/u.test(s)&&i==="native"&&(r=s.startsWith(" snapshot:")?"snapshot":null)}return n.push(""),n.join(`
|
|
145
|
-
`)}function
|
|
145
|
+
`)}function dC(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let n=e.trim();if(n.length===0||Bs.posix.isAbsolute(n)||Bs.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${t} must be a project-relative path`);if(n===".")return[];let i=n.replaceAll("\\","/").split("/");if(i.some(r=>r===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(r=>r===""||r==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function Ws(e){let t=dC(e,"native.artifact_root");return t.length===0?".":t.join("/")}function lm(e,t="docs"){let n=e??t;if(n!=="legacy"&&n!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return n}function Ht(e,t,n=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||Bs.posix.isAbsolute(i)||Bs.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let r=i.split("/");if(r.some(s=>s===".."))throw new Error(`${t} must stay inside its declared path base`);if(r.some(s=>s===""||s==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!n&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return r.join("/")}function Zi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function um(e,t,n){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${n} must be en or zh-CN`);return i}function fm(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>Uc)throw new Error(`${t} exceeds ${Uc} characters`);let n=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?n+=1:e[i]==="*"&&(n+=1,e[i+1]==="*"&&(i+=1));if(n>Vc)throw new Error(`${t} contains more than ${Vc} wildcard tokens`);return e}function am(e,t,n){if(e===void 0)return[...n];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>fm(i,t)))].sort((i,r)=>i.localeCompare(r,"en"))}function Jc(e,t,n){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${n} must be a positive integer`);return i}function mC(e){if(e===void 0)return{...pt,include:[...pt.include],exclude:[...pt.exclude]};let t=Zi(e,"native.snapshot");return{include:am(t.include,"native.snapshot.include",pt.include),exclude:am(t.exclude,"native.snapshot.exclude",pt.exclude),max_files:Jc(t.max_files,pt.max_files,"native.snapshot.max_files"),max_total_bytes:Jc(t.max_total_bytes,pt.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Jc(t.max_duration_ms,pt.max_duration_ms,"native.snapshot.max_duration_ms")}}function pC(e){if(e===void 0)return;let t=Zi(e,"native.pending_root_move"),n=t.id,i=t.from_artifact_root,r=t.to_artifact_root,s=t.stage;if(typeof n!="string"||!/^[a-f0-9-]{8,}$/u.test(n))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof r!="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(t.cleanup!==void 0){let a=Zi(t.cleanup,"native.pending_root_move.cleanup"),c=a.kind,l=a.state,f=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 f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:n,fromArtifactRoot:Ws(i),toArtifactRoot:Ws(r),stage:s,...o?{cleanup:o}:{}}}function hC(e,t={}){let n=Zi(e,"native"),i=n.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let r=n.clarification_mode??"sequential";if(r!=="sequential"&&r!=="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??lC;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let a=pC(n.pending_root_move);return{artifact_root:Ws(i),language:um(n.language,"en","native.language"),clarification_mode:r,archive_confirmation:s,max_verify_failures:o,snapshot:mC(n.snapshot),...a?{pending_root_move:a}:{}}}function gC(e){let t=Zi(e,"classic"),n=t.context_compression??"off";if(n!=="off"&&n!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let r=t.auto_transition??!0;if(typeof r!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:lm(t.artifact_layout),language:um(t.language,"zh-CN","classic.language"),context_compression:n,review_mode:i,auto_transition:r}}function wC(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function yC(e,t,n,i,r){let s=e.schema!==void 0;if(!(s||e.default_workflow!==void 0||e.workflows!==void 0||!r.allowPartialProject&&e.native!==void 0)||r.allowPartialProject&&!s)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let a=e.workflows??[e.default_workflow];if(!Array.isArray(a)||a.length===0||a.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(a)];if(!c.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!t)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:c,ambient_resume:i,...t?{native:t}:{},...n?{classic:n}:{}}}function vn(e,t={}){let n=(0,Hs.parseDocument)(e,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${n.errors[0].message}`);let i=n.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let r=i,s=wC(r.ambient_resume),o=r.native===void 0?void 0:hC(r.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),a=r.classic===void 0?void 0:gC(r.classic),c=yC(r,o,a,s,{allowPartialProject:t.allowPartialProject??!1});return{value:r,config:c,ambient_resume:s,...o?{native:o}:{},...a?{classic:a}:{}}}var Hs,er,Uc,Vc,lC,uC,pt,Fs,ht=he(()=>{"use strict";Hs=ft(nt(),1),er=64*1024,Uc=1024,Vc=64,lC=5,uC=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],pt={include:["**/*"],exclude:[...uC],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Fs={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
|
|
146
146
|
# ambient_resume: true | false`,native:"# Native workflow settings. They do not change Classic state or behavior.","native.artifact_root":"# Root directory where Native stores Comet specs, changes, and runtime data.","native.language":`# Artifact language used by Native workflow documents.
|
|
147
147
|
# language: en | zh-CN`,"native.clarification_mode":`# Controls whether Native asks one clarification at a time or every currently answerable question in a round.
|
|
148
148
|
# clarification_mode: sequential | batch`,"native.archive_confirmation":`# Controls whether Native archives automatically after a successful preview or waits for explicit user confirmation.
|
|
@@ -160,51 +160,51 @@ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.pus
|
|
|
160
160
|
# 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。
|
|
161
161
|
# 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
|
|
162
162
|
# 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
|
|
163
|
-
# 可选值:true | false`}}});function Kt(e){return e!==0&&e!==0n&&e!=="0"}function bn(e,t){return Kt(e.dev)&&Kt(t.dev)&&Kt(e.ino)&&Kt(t.ino)}function Ae(e,t){let n=Kt(e.dev)&&Kt(t.dev);if(n&&e.dev!==t.dev)return!1;let i=Kt(e.ino)&&Kt(t.ino);return i&&e.ino!==t.ino?!1:n&&i?!0:e.birthtime===t.birthtime}var tr=he(()=>{"use strict"});import{constants as Ks,promises as Cn}from"fs";function Vc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function dm(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function nr(e){return{dev:e.dev,ino:e.ino,birthtime:Vc(e)}}function Js(e,t){let n=nr(e),i=nr(t);return bn(n,i)?Ae(n,i):Ae(n,i)&&Vc(e)===Vc(t)&&dm(e)===dm(t)&&e.size===t.size}async function Us(e,t,n={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=n.label??"file",r=n.bigint===!0,s=await Cn.lstat(e,{bigint:r});if(!s.isFile()||s.isSymbolicLink())throw new Jt("not-regular-file",`${i} must be a regular file`);if(BigInt(s.size)>BigInt(t))throw new Jt("too-large",`${i} exceeds ${t} bytes`);let o=await Cn.realpath(e);await n.verify?.("pre-open",{realPath:o,identity:nr(s)});let a=process.platform==="win32"?Ks.O_RDONLY:Ks.O_RDONLY|Ks.O_NOFOLLOW|Ks.O_NONBLOCK,c;try{c=await Cn.open(e,a)}catch(l){throw l.code==="ELOOP"?new Jt("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,u]=await Promise.all([c.stat({bigint:r}),Cn.lstat(e,{bigint:r}),Cn.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!Js(s,l)||!Js(s,f))throw new Jt("changed",`${i} changed while opening`);await n.verify?.("post-open",{realPath:u,identity:nr(l)}),await n.hooks?.afterOpen?.();let d=[],h=0,g=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-h,{bytesRead:C}=await c.read(g,0,Math.min(g.length,y),null);if(C===0)break;if(h+=C,h>t)throw new Jt("too-large",`${i} exceeds ${t} bytes`);d.push(Buffer.from(g.subarray(0,C)))}await n.hooks?.beforeFinalCheck?.();let[p,m,w]=await Promise.all([c.stat({bigint:r}),Cn.lstat(e,{bigint:r}),Cn.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||w!==o||!Js(s,p)||!Js(s,m))throw new Jt("changed",`${i} changed while reading`);return await n.verify?.("post-read",{realPath:w,identity:nr(p)}),{bytes:Buffer.concat(d,h),stat:p,realPath:w}}finally{await c.close()}}var Jt,Yc=he(()=>{"use strict";tr();Jt=class extends Error{reason;constructor(t,n,i){super(n,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as Ut}from"fs";import Ke from"path";function mm(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Vs(e,t){let n=Ke.relative(e,t);return n===""||!Ke.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${Ke.sep}`)}async function Gc(e,t){let n=Ke.resolve(e),i=await Ut.lstat(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Ut.realpath(n)}async function zc(e,t,n,i){let r=e;for(let s=0;s<n.length;s++){r=Ke.join(r,n[s]);let o;try{o=await Ut.lstat(r)}catch(f){if(mm(f))return{exists:!1,kind:"missing"};throw f}let a=Ke.relative(e,r).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${a}`);let c=s===n.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${a} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await Ut.realpath(r);if(!Vs(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function T(e,t,n){let i=Ht(t,n.label),r=Ke.resolve(e),s=await Gc(r,n.label),o=i.split("/"),a=Ke.resolve(r,...o);if(!Vs(r,a))throw new Error(`${n.label} must stay inside the project root`);let c=await zc(r,s,o,n);return{projectRoot:r,target:a,relative:i,exists:c.exists,kind:c.kind}}async function Xc(e,t,n){let i=Ht(t,n.label),r=Ke.resolve(e),s=await Gc(r,n.label),o=i.split("/"),a=r;for(let c of o){a=Ke.join(a,c);let l;try{l=await Ut.lstat(a)}catch(d){if(!mm(d))throw d;try{await Ut.mkdir(a)}catch(h){if(h.code!=="EEXIST")throw h}l=await Ut.lstat(a)}let f=Ke.relative(r,a).replaceAll("\\","/");if(l.isSymbolicLink())throw new Error(`${n.label} crosses a symbolic link or junction at ${f}`);if(!l.isDirectory())throw new Error(`${n.label} directory ${f} must be a real directory`);let u=await Ut.realpath(a);if(!Vs(s,u))throw new Error(`${n.label} resolves outside the project root`)}return await zc(r,s,o,{label:n.label,expected:"directory"}),a}async function Ys(e,t,n){return(await T(e,t,{...n,expected:"file"})).exists}async function Y(e,t,n,i){let r=await T(e,t,{label:i.label,expected:"file"});if(!r.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let s=await Gc(r.projectRoot,i.label);return Us(r.target,n,{...i,verify:async(o,a)=>{if(!Vs(s,a.realPath))throw new Error(`${i.label} resolves outside the project root`);await zc(r.projectRoot,s,r.relative.split("/"),{label:i.label,expected:"file"})}})}var Me=he(()=>{"use strict";Yc();ht()});import{createHash as yC}from"crypto";function Qc(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function vC(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function it(e,t={}){return(await kn(e,t)).document}async function pm(e){try{return(await Y(e,ce,er,{label:ce})).bytes}catch(t){if(vC(t))return null;throw t}}function hm(e){return e?{exists:!0,sha256:yC("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function gt(e){return hm(await pm(e))}async function kn(e,t={}){let n=await pm(e);return{document:n?vn(n.toString("utf8"),t):null,identity:hm(n)}}async function Zc(e){return(await it(e))?.config??null}var ce,wt=he(()=>{"use strict";ht();Me();ce=".comet/config.yaml"});import{randomUUID as bC}from"crypto";import{promises as ie}from"fs";import le from"path";function zn(e,t){let n=le.relative(e,t);return n===""||!le.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${le.sep}`)}function zs(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function CC(e,t){return Ae(e,zs(t))}function Gs(e,t){let n=zs(e),i=zs(t);return bn(n,i)?Ae(n,i):Ae(n,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Xs(e){let t=await ie.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await ie.realpath(e),...zs(t)}}async function Vt(e){for(let t of e){let n=await ie.lstat(t.path);if(!n.isDirectory()||n.isSymbolicLink()||!CC(t,n)||await ie.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function kC(e,t){let n=le.resolve(e),i=le.resolve(t);if(!zn(n,i))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let r=[await Xs(n)],s=le.relative(n,i).split(le.sep).filter(Boolean),o=n;for(let a of s){await Vt(r),o=le.join(o,a);try{await ie.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Xs(o);if(!zn(r[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await Vt(r),r}async function SC(e,t){let n=le.resolve(e),i=le.resolve(t);if(!zn(n,i))throw new Error(`Contained file parent is outside its managed root: ${t}`);let r=[await Xs(n)],s=le.relative(n,i).split(le.sep).filter(Boolean),o=n;for(let a of s){o=le.join(o,a);try{let c=await Xs(o);if(!zn(r[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);r.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await Vt(r),r}async function gm(e){let t;try{t=await ie.open(e,"r"),await t.sync()}catch(n){let i=n.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw n}finally{await t?.close()}}async function EC(e,t,n){let i=le.dirname(e),r=await kC(n.containedRoot,i),s=le.join(i,`.${le.basename(e)}.${bC()}.tmp`),o,a;try{await n.beforeTemporaryOpen?.(),o=await ie.open(s,"wx"),a=await o.stat();let[c,l]=await Promise.all([ie.lstat(s),ie.realpath(s)]);if(await Vt(r),!c.isFile()||c.isSymbolicLink()||!Gs(a,c)||!zn(r[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!Gs(a,await o.stat()))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await n.beforeCommit?.(),await Vt(r);let f=await ie.lstat(s);if(!f.isFile()||f.isSymbolicLink()||!Gs(f,a))throw new Error("Contained atomic write temporary file changed before commit");n.exclusive?(await ie.link(s,e),await ie.unlink(s)):await ie.rename(s,e),await gm(i)}catch(c){await o?.close();try{await Vt(r),await ie.rm(s,{force:!0})}catch{}throw c}}async function qe(e,t,n){await EC(e,t,n)}async function el(e,t){let n=le.dirname(e),i=await SC(t.containedRoot,n);if(!i)return!1;let r,s;try{r=await ie.lstat(e),s=await ie.realpath(e)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!r.isFile()||r.isSymbolicLink()||!zn(i[0].realPath,s))throw new Error("Contained file removal target must be a regular file inside its managed root");await t.beforeRemove?.(),await Vt(i);let[o,a]=await Promise.all([ie.lstat(e),ie.realpath(e)]);if(!o.isFile()||o.isSymbolicLink()||!Gs(r,o)||a!==s)throw new Error("Contained file removal target changed before removal");return await ie.unlink(e),await Vt(i),await gm(n),!0}var Xn=he(()=>{"use strict";tr()});import{createHash as RC,randomUUID as _C}from"crypto";import{promises as Yt}from"fs";function bm(e){return`.comet/config.yaml.${e}.next`}function Cm(e){return`.comet/config.yaml.${e}.quarantine`}function xC(e){return`.comet/config-write-transaction.${e}.cleanup`}function tl(e){return RC("sha256").update(e).digest("hex")}function km(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function il(e){let t;try{t=(await Y(e,Qs,nl,{label:"project config write transaction"})).bytes}catch(o){if(km(o))return null;throw o}let n;try{n=JSON.parse(t.toString("utf8"))}catch{throw new Error("Invalid project config write transaction: expected JSON")}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid project config write transaction: expected an object");let i=n,r=Object.keys(i).sort(),s=["candidate","expected_sha256","id","output_sha256","owner_pid","quarantine","schema"].sort();if(r.join(`
|
|
163
|
+
# 可选值:true | false`}}});function Kt(e){return e!==0&&e!==0n&&e!=="0"}function bn(e,t){return Kt(e.dev)&&Kt(t.dev)&&Kt(e.ino)&&Kt(t.ino)}function Ae(e,t){let n=Kt(e.dev)&&Kt(t.dev);if(n&&e.dev!==t.dev)return!1;let i=Kt(e.ino)&&Kt(t.ino);return i&&e.ino!==t.ino?!1:n&&i?!0:e.birthtime===t.birthtime}var tr=he(()=>{"use strict"});import{constants as Ks,promises as Cn}from"fs";function Yc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function dm(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function nr(e){return{dev:e.dev,ino:e.ino,birthtime:Yc(e)}}function Js(e,t){let n=nr(e),i=nr(t);return bn(n,i)?Ae(n,i):Ae(n,i)&&Yc(e)===Yc(t)&&dm(e)===dm(t)&&e.size===t.size}async function Us(e,t,n={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=n.label??"file",r=n.bigint===!0,s=await Cn.lstat(e,{bigint:r});if(!s.isFile()||s.isSymbolicLink())throw new Jt("not-regular-file",`${i} must be a regular file`);if(BigInt(s.size)>BigInt(t))throw new Jt("too-large",`${i} exceeds ${t} bytes`);let o=await Cn.realpath(e);await n.verify?.("pre-open",{realPath:o,identity:nr(s)});let a=process.platform==="win32"?Ks.O_RDONLY:Ks.O_RDONLY|Ks.O_NOFOLLOW|Ks.O_NONBLOCK,c;try{c=await Cn.open(e,a)}catch(l){throw l.code==="ELOOP"?new Jt("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,u]=await Promise.all([c.stat({bigint:r}),Cn.lstat(e,{bigint:r}),Cn.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!Js(s,l)||!Js(s,f))throw new Jt("changed",`${i} changed while opening`);await n.verify?.("post-open",{realPath:u,identity:nr(l)}),await n.hooks?.afterOpen?.();let d=[],h=0,g=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-h,{bytesRead:C}=await c.read(g,0,Math.min(g.length,y),null);if(C===0)break;if(h+=C,h>t)throw new Jt("too-large",`${i} exceeds ${t} bytes`);d.push(Buffer.from(g.subarray(0,C)))}await n.hooks?.beforeFinalCheck?.();let[p,m,w]=await Promise.all([c.stat({bigint:r}),Cn.lstat(e,{bigint:r}),Cn.realpath(e)]);if(!m.isFile()||m.isSymbolicLink()||w!==o||!Js(s,p)||!Js(s,m))throw new Jt("changed",`${i} changed while reading`);return await n.verify?.("post-read",{realPath:w,identity:nr(p)}),{bytes:Buffer.concat(d,h),stat:p,realPath:w}}finally{await c.close()}}var Jt,Gc=he(()=>{"use strict";tr();Jt=class extends Error{reason;constructor(t,n,i){super(n,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as Ut}from"fs";import Ke from"path";function mm(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Vs(e,t){let n=Ke.relative(e,t);return n===""||!Ke.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${Ke.sep}`)}async function zc(e,t){let n=Ke.resolve(e),i=await Ut.lstat(n);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Ut.realpath(n)}async function Xc(e,t,n,i){let r=e;for(let s=0;s<n.length;s++){r=Ke.join(r,n[s]);let o;try{o=await Ut.lstat(r)}catch(f){if(mm(f))return{exists:!1,kind:"missing"};throw f}let a=Ke.relative(e,r).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${a}`);let c=s===n.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${a} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await Ut.realpath(r);if(!Vs(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function T(e,t,n){let i=Ht(t,n.label),r=Ke.resolve(e),s=await zc(r,n.label),o=i.split("/"),a=Ke.resolve(r,...o);if(!Vs(r,a))throw new Error(`${n.label} must stay inside the project root`);let c=await Xc(r,s,o,n);return{projectRoot:r,target:a,relative:i,exists:c.exists,kind:c.kind}}async function Qc(e,t,n){let i=Ht(t,n.label),r=Ke.resolve(e),s=await zc(r,n.label),o=i.split("/"),a=r;for(let c of o){a=Ke.join(a,c);let l;try{l=await Ut.lstat(a)}catch(d){if(!mm(d))throw d;try{await Ut.mkdir(a)}catch(h){if(h.code!=="EEXIST")throw h}l=await Ut.lstat(a)}let f=Ke.relative(r,a).replaceAll("\\","/");if(l.isSymbolicLink())throw new Error(`${n.label} crosses a symbolic link or junction at ${f}`);if(!l.isDirectory())throw new Error(`${n.label} directory ${f} must be a real directory`);let u=await Ut.realpath(a);if(!Vs(s,u))throw new Error(`${n.label} resolves outside the project root`)}return await Xc(r,s,o,{label:n.label,expected:"directory"}),a}async function Ys(e,t,n){return(await T(e,t,{...n,expected:"file"})).exists}async function Y(e,t,n,i){let r=await T(e,t,{label:i.label,expected:"file"});if(!r.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let s=await zc(r.projectRoot,i.label);return Us(r.target,n,{...i,verify:async(o,a)=>{if(!Vs(s,a.realPath))throw new Error(`${i.label} resolves outside the project root`);await Xc(r.projectRoot,s,r.relative.split("/"),{label:i.label,expected:"file"})}})}var Me=he(()=>{"use strict";Gc();ht()});import{createHash as vC}from"crypto";function Zc(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function bC(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function it(e,t={}){return(await kn(e,t)).document}async function pm(e){try{return(await Y(e,ce,er,{label:ce})).bytes}catch(t){if(bC(t))return null;throw t}}function hm(e){return e?{exists:!0,sha256:vC("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function gt(e){return hm(await pm(e))}async function kn(e,t={}){let n=await pm(e);return{document:n?vn(n.toString("utf8"),t):null,identity:hm(n)}}async function el(e){return(await it(e))?.config??null}var ce,wt=he(()=>{"use strict";ht();Me();ce=".comet/config.yaml"});import{randomUUID as CC}from"crypto";import{constants as kC,promises as Q}from"fs";import le from"path";async function Qs(e,t){try{return await Q.link(e,t),{linked:!0}}catch(n){let i=n.code;if(i!=="ENOTSUP"&&i!=="EOPNOTSUPP")throw n}return await Q.copyFile(e,t,kC.COPYFILE_EXCL),{linked:!1}}function zn(e,t){let n=le.relative(e,t);return n===""||!le.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${le.sep}`)}function zs(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function SC(e,t){return Ae(e,zs(t))}function Gs(e,t){let n=zs(e),i=zs(t);return bn(n,i)?Ae(n,i):Ae(n,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Xs(e){let t=await Q.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await Q.realpath(e),...zs(t)}}async function Vt(e){for(let t of e){let n=await Q.lstat(t.path);if(!n.isDirectory()||n.isSymbolicLink()||!SC(t,n)||await Q.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function EC(e,t){let n=le.resolve(e),i=le.resolve(t);if(!zn(n,i))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let r=[await Xs(n)],s=le.relative(n,i).split(le.sep).filter(Boolean),o=n;for(let a of s){await Vt(r),o=le.join(o,a);try{await Q.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Xs(o);if(!zn(r[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);r.push(c)}return await Vt(r),r}async function RC(e,t){let n=le.resolve(e),i=le.resolve(t);if(!zn(n,i))throw new Error(`Contained file parent is outside its managed root: ${t}`);let r=[await Xs(n)],s=le.relative(n,i).split(le.sep).filter(Boolean),o=n;for(let a of s){o=le.join(o,a);try{let c=await Xs(o);if(!zn(r[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);r.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await Vt(r),r}async function gm(e){let t;try{t=await Q.open(e,"r"),await t.sync()}catch(n){let i=n.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw n}finally{await t?.close()}}async function _C(e,t,n){let i=le.dirname(e),r=await EC(n.containedRoot,i),s=le.join(i,`.${le.basename(e)}.${CC()}.tmp`),o,a;try{await n.beforeTemporaryOpen?.(),o=await Q.open(s,"wx"),a=await o.stat();let[c,l]=await Promise.all([Q.lstat(s),Q.realpath(s)]);if(await Vt(r),!c.isFile()||c.isSymbolicLink()||!Gs(a,c)||!zn(r[0].realPath,l))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),!Gs(a,await o.stat()))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await n.beforeCommit?.(),await Vt(r);let f=await Q.lstat(s);if(!f.isFile()||f.isSymbolicLink()||!Gs(f,a))throw new Error("Contained atomic write temporary file changed before commit");n.exclusive?(await Qs(s,e),await Q.unlink(s)):await Q.rename(s,e),await gm(i)}catch(c){await o?.close();try{await Vt(r),await Q.rm(s,{force:!0})}catch{}throw c}}async function qe(e,t,n){await _C(e,t,n)}async function tl(e,t){let n=le.dirname(e),i=await RC(t.containedRoot,n);if(!i)return!1;let r,s;try{r=await Q.lstat(e),s=await Q.realpath(e)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!r.isFile()||r.isSymbolicLink()||!zn(i[0].realPath,s))throw new Error("Contained file removal target must be a regular file inside its managed root");await t.beforeRemove?.(),await Vt(i);let[o,a]=await Promise.all([Q.lstat(e),Q.realpath(e)]);if(!o.isFile()||o.isSymbolicLink()||!Gs(r,o)||a!==s)throw new Error("Contained file removal target changed before removal");return await Q.unlink(e),await Vt(i),await gm(n),!0}var Xn=he(()=>{"use strict";tr()});import{createHash as xC,randomUUID as PC}from"crypto";import{promises as Yt}from"fs";function bm(e){return`.comet/config.yaml.${e}.next`}function Cm(e){return`.comet/config.yaml.${e}.quarantine`}function OC(e){return`.comet/config-write-transaction.${e}.cleanup`}function nl(e){return xC("sha256").update(e).digest("hex")}function km(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function rl(e){let t;try{t=(await Y(e,Zs,il,{label:"project config write transaction"})).bytes}catch(o){if(km(o))return null;throw o}let n;try{n=JSON.parse(t.toString("utf8"))}catch{throw new Error("Invalid project config write transaction: expected JSON")}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid project config write transaction: expected an object");let i=n,r=Object.keys(i).sort(),s=["candidate","expected_sha256","id","output_sha256","owner_pid","quarantine","schema"].sort();if(r.join(`
|
|
164
164
|
`)!==s.join(`
|
|
165
|
-
`))throw new Error("Invalid project config write transaction: unexpected fields");if(i.schema!==ym)throw new Error("Invalid project config write transaction: unsupported schema");if(typeof i.id!="string"||!vm.test(i.id))throw new Error("Invalid project config write transaction: invalid id");if(typeof i.owner_pid!="number"||!Number.isSafeInteger(i.owner_pid)||i.owner_pid<=0)throw new Error("Invalid project config write transaction: invalid owner pid");if(typeof i.expected_sha256!="string"||!
|
|
166
|
-
`,{containedRoot:e,exclusive:!0}),{candidate:r.candidate,quarantine:r.quarantine}}async function to(e){let t=await il(e);if(!t)return null;let{journal:n}=t,[i,r,s]=await Promise.all([gt(e),eo(e,n.candidate),eo(e,n.quarantine)]);if(r!==null&&r!==n.output_sha256)throw new Error("Project config write transaction candidate changed after creation");if(s!==null&&s!==n.expected_sha256)throw new Error("Project config write transaction quarantine changed after creation");let o;return!i.exists&&s===n.expected_sha256?o="config-quarantined":i.sha256===n.output_sha256?o="published-cleanup-pending":i.exists&&i.sha256!==n.expected_sha256&&i.sha256!==n.output_sha256?o="successor-preserved-cleanup-pending":o="prepared",{id:n.id,stage:o,candidate:n.candidate,quarantine:n.quarantine,allowedRepair:"rollback-or-cleanup"}}async function no(e,t={}){let n=await il(e);if(!n)return!1;let{journal:i}=n;if(t.ownerId!==i.id&&PC(i.owner_pid))throw new Error(`Project config write transaction ${i.id} is still active in process ${i.owner_pid}`);if(!await to(e))return!1;let s=await gt(e),o=await eo(e,i.quarantine);if(!s.exists){if(o!==i.expected_sha256)throw new Error("Cannot recover project config write transaction: the config and owned quarantine are missing");let a=await T(e,ce,{label:ce,expected:"file"}),c=await T(e,i.quarantine,{label:"project config write transaction quarantine",expected:"file"});try{await Yt.link(c.target,a.target)}catch(l){if(l.code!=="EEXIST")throw l}if(s=await gt(e),!s.exists)throw new Error("Cannot recover project config write transaction: config publish failed")}return await wm(e,i.candidate,i.output_sha256,t.testHooks?.afterOwnedFileQuarantine),s.exists&&await wm(e,i.quarantine,i.expected_sha256,t.testHooks?.afterOwnedFileQuarantine),await OC(e,n),!0}var ym,Qs,nl,vm,Zs,rl=he(()=>{"use strict";Xn();wt();Me();ym="comet.project-config-write.v1",Qs=".comet/config-write-transaction.json",nl=16*1024,vm=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Zs=/^[0-9a-f]{64}$/});import{createHash as Em,randomUUID as IC}from"crypto";import{promises as ol}from"fs";import sl from"path";async function al(e,t){if(!t)return;let n=await gt(e);if(!Qc(n,t))throw new Error("Project config changed before commit; rerun the operation")}async function cl(e,t,n={}){vn(t,{allowPartialProject:n.allowPartialProject??!1});let i=sl.resolve(e);if(await to(i))throw new Error("An unfinished project config write transaction exists; run comet doctor --repair");let r=n.expectedIdentity??await gt(i);await al(i,r);let s=await T(i,ce,{label:ce,expected:"file"}),o=IC(),a=Em("sha256").update(t).digest("hex"),c=r.exists&&r.sha256?await Sm(i,o,r.sha256,a):null,l=c!==null,f=c?.candidate??`.comet/config.yaml.${o}.next`,u=sl.join(i,...f.split("/")),d=c?.quarantine??null;try{if(await qe(u,t,{containedRoot:i,exclusive:!0}),await n.beforeCommit?.(),await al(i,r),await T(i,f,{label:"project config candidate",expected:"file"}),r.exists){if(!d)throw new Error("Project config write transaction was not created");let g=sl.join(i,...d.split("/"));if(await T(i,ce,{label:ce,expected:"file"}),(await T(i,d,{label:"project config quarantine",expected:"file"})).exists)throw new Error("Project config quarantine already exists");await ol.rename(s.target,g);let{bytes:m}=await Y(i,d,er,{label:"project config quarantine"});if(Em("sha256").update(m).digest("hex")!==r.sha256)throw new Error("Project config changed before final publish; successor was preserved")}else if(s.exists)throw new Error("Project config changed before final publish; successor was preserved");await n.beforePublish?.(),await T(i,f,{label:"project config candidate",expected:"file"});try{await ol.link(u,s.target)}catch(g){throw new Error("Project config final publish failed; successor was preserved",{cause:g})}let h=await gt(i);if(!h.exists||h.sha256!==a)throw new Error("Project config changed during final publish; successor was preserved");l&&(await no(i,{ownerId:o}),l=!1)}catch(h){if(l)try{await no(i,{ownerId:o})&&(l=!1)}catch{}throw h}finally{l||await AC(i,f).catch(()=>!1)}}async function AC(e,t){let n=await T(e,t,{label:t,expected:"file"});return n.exists?(await ol.unlink(n.target),!0):!1}var ll=he(()=>{"use strict";Xn();ht();wt();Me();rl()});var co=he(()=>{"use strict"});var Lm=he(()=>{"use strict"});var dl=he(()=>{"use strict";co()});var Mm=he(()=>{"use strict";co();dl()});var qm=he(()=>{"use strict";co();Xn();Lm();Mm();ht();Me();wt();ll();rl();dl()});import{TextDecoder as ak}from"util";function Dm(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function ck(e,t){try{return new ak("utf-8",{fatal:!0}).decode(e.bytes)}catch(n){throw new Error(`${t} is not valid UTF-8`,{cause:n})}}async function ml(e,t,n,i,r={}){try{let s=await Y(e,t,n,{label:i,hooks:r.hooks});return{result:s,text:ck(s,i)}}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw s}}async function Ct(e,t,n,i,r={}){return(await ml(e,t,n,i,r))?.text??null}async function Xt(e,t,n,i,r,s={}){if(Buffer.byteLength(n,"utf8")>i)throw new Error(`${r} exceeds ${i} bytes`);let o=await ml(e,t,i,r),a=await T(e,t,{label:r,expected:"file"});await qe(a.target,n,{containedRoot:a.projectRoot,beforeCommit:async()=>{await s.beforeCommit?.();let c=await ml(e,t,i,r);if(!(!o&&!c)){if(!o||!c)throw new Error(`${r} changed before commit`);if(o.result.realPath!==c.result.realPath||!Ae(Dm(o.result.stat),Dm(c.result.stat))||o.text!==c.text)throw new Error(`${r} changed before commit`)}}})}async function lo(e,t,n,i,r,s={}){let o=await Ct(e,t,i,r);await Xt(e,t,`${o??""}${n}`,i,r,s)}async function uo(e,t,n,i={}){let r=await T(e,t,{label:n,expected:"file"});return r.exists?el(r.target,{containedRoot:r.projectRoot,beforeRemove:i.beforeRemove}):!1}var fo=he(()=>{"use strict";qm();tr()});var Wm={};Ig(Wm,{RUN_STATE_FILE:()=>po,applyRunStateToDocument:()=>pl,readRunState:()=>ur,removeRunState:()=>hl,runStateFromDocument:()=>mo,writeRunState:()=>ho});import lk from"path";function lr(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return n}function cr(e,t){let n=lr(e,t);if(lk.isAbsolute(n)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return n}function uk(e){let t=e.run_retries??"{}",n;try{n=typeof t=="string"?JSON.parse(t):t}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(n))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return n}function mo(e){if(!e.run_id)return null;let t=lr(e,"run_id"),n=lr(e,"skill"),i=lr(e,"skill_version"),r=lr(e,"skill_hash"),s=cr(e,"pending_ref"),o=cr(e,"trajectory_ref"),a=cr(e,"context_ref"),c=cr(e,"artifacts_ref"),l=cr(e,"checkpoint_ref"),f=Number(e.iteration);if(!Number.isInteger(f)||f<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:n,skillVersion:i,skillHash:r,orchestration:e.orchestration,currentStep:Fm(e,"current_step"),iteration:f,pending:Fm(e,"pending"),pendingRef:s,trajectoryRef:o,contextRef:a,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:uk(e)}}function pl(e,t){t?e.run_id=t.runId:delete e.run_id}function fk(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,currentStep:e.currentStep,iteration:e.iteration,pending:e.pending,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,status:e.status,retries:e.retries}}function dk(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)};return mo(t)}async function ur(e,t={}){let n=await Ct(e,po,Bm,"Run state",t);if(n===null)return null;let i=JSON.parse(n);return dk(i)}async function ho(e,t,n={}){await Xt(e,po,JSON.stringify(fk(t),null,2),Bm,"Run state",n)}async function hl(e,t={}){await uo(e,po,"Run state",t)}var Fm,po,Bm,fr=he(()=>{"use strict";fo();Fm=(e,t)=>{let n=e[t];return n==null?null:String(n)};po=".comet/run-state.json",Bm=256*1024});import{pathToFileURL as lx}from"url";import{createHash as ES}from"crypto";import{promises as RS}from"fs";import st from"path";import{spawnSync as FC}from"child_process";function Ng(e){return e.length>0&&/^[A-Za-z0-9@+=:,./\\_-]+$/.test(e)?e:`"${e.replace(/"/g,'""')}"`}function hu(e){return e.map(t=>Ng(t))}import{promises as NC}from"fs";import G from"path";import{promises as gu}from"fs";async function ki(e){try{return await gu.access(e),!0}catch(t){if(Tg(t))return!1;throw t}}async function wu(e){try{return await gu.readdir(e)}catch(t){let n=t?.code;if(n==="ENOENT"||n==="ENOTDIR")return[];throw t}}function Tg(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}ht();wt();ll();Me();var ir=class extends Error{code="classic-layout-unavailable";constructor(t="Classic artifact layout is unavailable from .comet/config.yaml"){super(t),this.name="ClassicLayoutUnavailableError"}},ul=class extends Error{constructor(n,i,r){let s=N(r,n),o=N(r,i);super(`Classic layout conflict: both ${s}/ and ${o}/ exist; run comet doctor and resolve the conflict before writing`);this.configuredRoot=n;this.alternateRoot=i;this.name="ClassicLayoutConflictError"}configuredRoot;alternateRoot;code="classic-layout-conflict"},Rm=".comet/config.yaml";function TC(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function io(e){await T(e,Rm,{label:Rm,expected:"file"})}function yt(e,t){let n=G.resolve(e),i=t==="docs"?G.join(n,"docs"):n,r=G.join(i,"openspec"),s=G.join(n,"docs","superpowers");return{projectRoot:n,artifactLayout:t,openSpecBase:i,openSpecRoot:r,changesDir:G.join(r,"changes"),archiveDir:G.join(r,"changes","archive"),specsDir:G.join(r,"specs"),superpowersRoot:s,superpowersSpecsDir:G.join(s,"specs"),superpowersPlansDir:G.join(s,"plans"),superpowersReportsDir:G.join(s,"reports")}}async function Gt(e){await io(e);let t=await it(e,{allowPartialProject:!0});if(!t?.config)throw new ir;if(!(t.config.workflows??[t.config.default_workflow]).includes("classic"))throw new ir("Classic artifact layout is unavailable because Classic is not enabled");return t.classic?.artifact_layout??"legacy"}async function _m(e){await io(e);let t=(await it(e))?.config;if(!t)throw new Error(".comet/config.yaml must use comet.project.v1 before migration");if(!(t.workflows??[t.default_workflow]).includes("classic"))throw new Error("Classic root move requires the Classic workflow to be enabled")}async function xm(e,t,n={}){await io(e);let i=await kn(e,{allowPartialProject:!0}),r=i.document;if(!r)throw new Error(".comet/config.yaml does not exist");let s=r.value.classic;if(!s||typeof s!="object"||Array.isArray(s))throw new Error("classic must be a mapping");let o={...r.value,classic:{...s,artifact_layout:t}},a=Gn(o,r.classic?.language==="zh-CN"||r.native?.language==="zh-CN"?"zh-CN":"en");vn(a,{allowPartialProject:!0}),await cl(e,a,{expectedIdentity:n.expectedIdentity??i.identity,beforeCommit:n.beforeCommit})}async function jC(e,t){return yt(e,t??await Gt(e))}async function LC(e,t){let n=await jC(e,t),i=n.artifactLayout==="legacy"?"docs":"legacy",r=yt(e,i).openSpecRoot,[s,o]=await Promise.all([T(n.projectRoot,N(n.projectRoot,n.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),T(n.projectRoot,N(n.projectRoot,r),{label:"Alternate Classic OpenSpec root",expected:"directory"})]),a=s.exists,c=o.exists;return{paths:n,configuredRootExists:a,alternateRoot:r,alternateRootExists:c,dualRoots:a&&c}}async function MC(e,t){let n=[e.openSpecRoot,e.changesDir,e.archiveDir,e.specsDir,t,e.superpowersRoot,e.superpowersSpecsDir,e.superpowersPlansDir,e.superpowersReportsDir];for(let i of n){let r=N(e.projectRoot,i);await T(e.projectRoot,r,{label:`Classic managed physical path ${r}`,expected:"directory"})}}async function Q(e,t,n={}){let i=await LC(e,t);if(await MC(i.paths,i.alternateRoot),i.dualRoots&&!n.allowAlternateRoot)throw new ul(i.paths.openSpecRoot,i.alternateRoot,i.paths.projectRoot);if(!i.configuredRootExists){let r=N(i.paths.projectRoot,i.paths.openSpecRoot),s=N(i.paths.projectRoot,i.alternateRoot);throw new ir(`Configured Classic OpenSpec root is missing: ${r} (alternate ${s} is ${i.alternateRootExists?"present":"missing"})`)}return i.paths}async function Ee(e,t,n={}){let i=G.join(G.resolve(e),".comet","classic-root-move.json");if(await ki(i))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let r=await Q(e,t,n);if(!await ki(r.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${N(r.projectRoot,r.openSpecRoot)}`);return r}async function ue(e){let t=G.resolve(e),n=null;try{(await NC.lstat(t)).isDirectory()||(t=G.dirname(t))}catch(i){if(!TC(i))throw i}for(;;){G.basename(t)==="openspec"&&(n=G.dirname(t));let i=G.join(t,".comet","config.yaml"),r=!1;if(await ki(i))try{await io(t);let o=(await it(t))?.value;r=!!o&&typeof o=="object"&&!Array.isArray(o)&&(o.schema==="comet.project.v1"||o.default_workflow!==void 0||o.native!==void 0)}catch{}if(r||await ki(G.join(t,".git")))return t;let s=G.dirname(t);if(s===t)return n??G.resolve(e);t=s}}function N(e,t){return G.relative(G.resolve(e),t).replaceAll("\\","/")}var Pm=ft(nt(),1);Me();import qC from"path";var DC=1024*1024;async function Om(e,t){let n=t??await Q(e),i=qC.join(n.openSpecRoot,"config.yaml"),r=N(n.projectRoot,i),s;try{s=(await Y(n.projectRoot,r,DC,{label:"Classic OpenSpec project config",bigint:!0})).bytes.toString("utf8")}catch(l){throw l.code==="ENOENT"?new Error(`Classic OpenSpec root is unhealthy: ${r} 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,Pm.parseDocument)(s,{uniqueKeys:!0});if(o.errors.length>0)throw new Error(`Classic OpenSpec root is unhealthy: ${r} 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: ${r} must contain a mapping`);let c=a.schema;if(typeof c!="string"||c.trim()==="")throw new Error(`Classic OpenSpec root is unhealthy: ${r} must declare a non-empty schema`);return{layout:n,configPath:r,schema:c}}function BC(e){return e[0]==="--"?e.slice(1):[...e]}async function fl(e,t=process.cwd()){let n=BC(e);if(n.length===0)return{exitCode:64,stderr:"Usage: comet classic openspec -- <openspec-args...>"};let i=await ue(t),r=await Ee(i);await Om(i,r);let s=process.env.COMET_OPENSPEC||"openspec",o=process.platform==="win32",a=FC(s,o?hu(n):n,{cwd:r.openSpecBase,encoding:"utf8",shell:o,windowsHide:!0});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}}var $m=async e=>fl(e);import{promises as HC}from"fs";import Rn from"path";Xn();ht();Me();import rr from"path";var WC=2*1024*1024;function ro(e,t,n){let i=rr.resolve(e),r=rr.isAbsolute(t)?rr.resolve(t):rr.resolve(i,t),s=rr.relative(i,r).replaceAll("\\","/");return{root:i,relative:Ht(s,n),target:r}}async function V(e,t,n){let i=ro(e,t,n.label);return T(i.root,i.relative,n)}async function Z(e,t,n){return(await V(e,t,{label:n.label,expected:n.expected??"any"})).exists}async function Sn(e,t,n,i){return await Z(e,t,{label:n,expected:"file"})?(await so(e,t,{label:n,hooks:i})).byteLength>0:!1}async function B(e,t,n){return(await so(e,t,n)).toString("utf8")}async function so(e,t,n){let i=ro(e,t,n.label);return(await Y(i.root,i.relative,n.maxBytes??WC,{label:n.label,hooks:n.hooks})).bytes}async function En(e,t,n){let i=ro(e,t,n);return Xc(i.root,i.relative,{label:n})}async function Qn(e,t,n,i){let r=ro(e,t,i.label);await T(r.root,r.relative,{label:i.label,expected:"file"}),await qe(r.target,n,{containedRoot:r.root,beforeTemporaryOpen:i.beforeTemporaryOpen,beforeCommit:i.beforeCommit,exclusive:i.exclusive})}function ge(e){return e?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e)?e.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${e}'
|
|
167
|
-
Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function zt(e){let t=ge(e);if(t)throw new Error(t)}function KC(e,t){return{label:N(e,t),directory:t}}async function Zn(e,t,n){let i=KC(e,t);if(!(await V(e,t,{label:n,expected:"directory"})).exists)return{change:i,exists:!1,stateExists:!1};let s=await V(e,Rn.join(t,".comet.yaml"),{label:`${n} state`,expected:"file"});return{change:i,exists:!0,stateExists:s.exists}}function Im(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${n}$`,"u").test(e)}async function Am(e,t,n,i={}){if(!i.skipExactCompatibility){let o=await Zn(e,Rn.join(t,n),`Classic archived change ${n}`);if(o.exists)return o.change}if(!(await V(e,t,{label:"Classic archive directory",expected:"directory"})).exists)return null;let s=[];for(let o of await HC.readdir(t,{withFileTypes:!0})){if(!Im(o.name,n))continue;let a=await Zn(e,Rn.join(t,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 Je(e,t=process.cwd()){zt(e);let n=await Q(t),i=await Zn(n.projectRoot,Rn.join(n.changesDir,e),`Classic active change ${e}`);return{...i.change,exists:i.exists,stateExists:i.stateExists}}async function Nm(e,t=process.cwd()){zt(e);let n=await Ee(t),i=Rn.join(n.changesDir,e),r=await Zn(n.projectRoot,i,`Classic active change ${e}`);return r.exists||await En(n.projectRoot,i,`Classic active change ${e}`),r.change}async function oo(e,t=process.cwd(),n={}){zt(e);let i=await Q(t);if(n.preferredArchiveName!==void 0){let r=n.preferredArchiveName;if(r!==e&&!Im(r,e))throw new Error(`Classic preferred archive name '${r}' does not belong to change '${e}'`);let s=await Zn(i.projectRoot,Rn.join(i.archiveDir,r),`Classic preferred archived change ${r}`);return s.exists&&s.stateExists?s.change:null}return Am(i.projectRoot,i.archiveDir,e,n)}async function ei(e,t=process.cwd()){zt(e);let n=await Q(t),i=await Zn(n.projectRoot,Rn.join(n.changesDir,e),`Classic active change ${e}`);if(i.exists)return i.change;let r=await Am(n.projectRoot,n.archiveDir,e);return r||i.change}import{promises as bp}from"fs";import ve from"path";import{fileURLToPath as Sl}from"url";import{promises as UC}from"fs";import vt from"path";Me();ht();import sr from"path";function JC(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Tm(e,t,n,i){let r=Ht(n,"Classic handoff artifact pointer");if((await T(e,r,{label:"Classic handoff artifact",expected:"file"})).exists)return null;let o=await Q(e),a=`${N(e,o.changesDir)}/`,l=(o.artifactLayout==="docs"?[a,"openspec/changes/"]:[a]).find(y=>r.startsWith(y));if(!l)return null;let f=r.slice(l.length).split("/");if(f.length<4||f[1]!==".comet"||f.slice(2).some(y=>y.length===0))return null;let u=f[0];zt(u);let d=f.slice(2),h=sr.resolve(t);if(sr.dirname(h)!==sr.resolve(o.archiveDir))return null;let g=sr.basename(h),p=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(g);if(g!==u&&p?.[1]!==u)return null;await T(e,N(e,h),{label:"Classic archived change directory",expected:"directory"});let m=sr.join(h,".comet",...d),w=N(e,m);try{return await Y(e,w,i,{label:"Historical Classic archived handoff artifact"}),w}catch(y){if(JC(y))return null;throw y}}Me();var jm=2*1024*1024;function or(e,t){return vt.relative(e,t).split(vt.sep).join("/")}async function ar(e,t,n){if(!n)return{code:t,satisfied:!1};let i=n.replaceAll("\\","/");try{let r=await Ys(e,i,{label:`${t} artifact`});return{code:t,satisfied:r,source:i,...r?{resolvedSource:i}:{}}}catch(r){return{code:t,satisfied:!1,source:i,detail:`unsafe artifact pointer outside the project or through a special path: ${r instanceof Error?r.message:String(r)}`}}}async function VC(e,t,n){try{await Q(e)}catch(r){return{code:"design.handoff",satisfied:!1,...n?{source:n.replaceAll("\\","/")}:{},detail:`Classic layout is unsafe or unavailable for handoff evidence: ${r instanceof Error?r.message:String(r)}`}}let i=await ar(e,"design.handoff",n);if(!n||i.satisfied||i.detail)return i;try{let r=await Tm(e,t,n,jm);return r?{...i,satisfied:!0,resolvedSource:r,detail:`resolved historical legacy pointer from archived change: ${r}`}:i}catch(r){return{...i,satisfied:!1,detail:`unsafe archived handoff fallback: ${r instanceof Error?r.message:String(r)}`}}}async function ao(e,t,n){return ar(e,t,or(e,n))}async function YC(e,t){let n=vt.join(t,"specs"),i;try{let o=or(e,n);if(!(await T(e,o,{label:"OpenSpec delta-spec directory",expected:"directory"})).exists)return{code:"openspec.delta-spec",satisfied:!1};i=await UC.readdir(n)}catch(o){return o.code==="ENOENT"?{code:"openspec.delta-spec",satisfied:!1}:{code:"openspec.delta-spec",satisfied:!1,detail:`unsafe delta-spec path: ${o instanceof Error?o.message:String(o)}`}}let r=i.map(o=>vt.join(n,o,"spec.md")),s=(await Promise.all(r.map(async o=>{try{return await Ys(e,or(e,o),{label:"OpenSpec delta spec"})?o:null}catch{return null}}))).filter(o=>o!==null);return{code:"openspec.delta-spec",satisfied:s.length>0,source:s[0]?or(e,s[0]):void 0,detail:`${s.length} delta spec${s.length===1?"":"s"}`}}async function GC(e,t){let n,i=or(e,t);try{n=(await Y(e,i,jm,{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:i,detail:`unsafe tasks artifact: ${o instanceof Error?o.message:String(o)}`}}let r=[...n.matchAll(/^\s*[-*]\s+\[([ xX])\]\s+/gmu)],s=r.filter(o=>o[1].toLowerCase()==="x").length;return{code:"build.tasks-complete",satisfied:r.length>0&&s===r.length,source:i,detail:`${s} of ${r.length} tasks complete`}}function _n(e,t){return e.some(n=>n.code===t&&n.satisfied)}async function Ue(e,t){let n=await ue(e),i=t.classic,r=vt.join(e,"proposal.md"),s=vt.join(e,"design.md"),o=vt.join(e,"tasks.md"),a=t.run?vt.resolve(e,t.run.checkpointRef):vt.join(e,".comet","checkpoint.json"),c=await Promise.all([ao(n,"openspec.proposal",r),ao(n,"openspec.design",s),ao(n,"openspec.tasks",o),YC(n,e),ar(n,"design.document",i?.designDoc??null),ar(n,"build.plan",i?.plan??null),GC(n,o),ar(n,"verification.report",i?.verificationReport??null),VC(n,e,i?.handoffContext??null),ao(n,"run.checkpoint",a)]),l=c.find(f=>f.code==="design.handoff");return l&&!i?.handoffHash&&(l.satisfied=!1,l.detail="handoff hash is missing"),c.push({code:"archive.confirmed",satisfied:i?.archiveConfirmation==="confirmed"}),c}import{createHash as nS,randomUUID as iS}from"crypto";import{promises as kl}from"fs";import kt from"path";function zC(e){return e.classicProfile??e.workflow}function XC(e){return!e.buildMode||!e.tddMode||!e.isolation||!e.verifyMode?!1:e.buildMode==="subagent-driven-development"?e.subagentDispatch==="confirmed":e.buildMode==="direct"?e.directOverride===!0:!0}function QC(e){return e.buildMode==="direct"&&e.tddMode==="direct"&&e.isolation!==null&&e.verifyMode==="light"}function ZC(e,t,n){if(t.verifyResult==="fail")return e==="full"?"full.build.fix":`${e}.build.execute`;if(e==="full"){if(!_n(n,"build.plan"))return"full.build.plan";if(t.buildPause==="plan-ready")return"full.build.plan-ready";if(!XC(t))return"full.build.configure"}else if(!QC(t))throw new Error(`${e} build configuration is incomplete`);return _n(n,"build.tasks-complete")?`${e}.build.complete`:`${e}.build.execute`}function ek(e,t,n){return t.verifyResult!=="pass"||!_n(n,"verification.report")?`${e}.verify.run`:`${e}.verify.branch`}function tk(e,t){if(t.verifyResult!=="pass")throw new Error("archive requires verify_result=pass");return t.archiveConfirmation==="confirmed"?`${e}.archive.execute`:`${e}.archive.confirm`}function bt(e,t){let n=zC(e);if(e.archived&&e.phase!=="archive")throw new Error("archived=true requires phase=archive");if(e.archived)return"completed";if(n!=="full"&&e.phase==="design")throw new Error(`${n} workflow cannot enter design`);switch(e.phase){case"open":return`${n}.open`;case"design":return _n(t,"design.handoff")?"full.design.document":"full.design.handoff";case"build":return ZC(n,e,t);case"verify":return ek(n,e,t);case"archive":return tk(n,e)}}var wo=ft(nt(),1);Xn();Me();import pr from"path";fr();var wl=["full","hotfix","tweak"],Qt=1,Km=["open","design","build","verify","archive"],mk=["en","zh-CN"],pk=["off","beta"],hk=["subagent-driven-development","executing-plans","direct"],gk=["plan-ready"],wk=["confirmed"],yk=["tdd","direct"],vk=["off","standard","thorough"],bk=["current","branch","worktree"],Ck=["light","full"],kk=["pending","pass","fail"],Sk=["pending","handled"],Ek=["pending","confirmed"],Zt=["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","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],dr=["run_id"],Jm=new Set([...Zt,...dr]),Rk=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function Hm(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ti(e,t){let n=e[t];if(n==null||n==="")return null;if(typeof n!="string")throw new Error(`Invalid Classic state: ${t} must be a string or null`);return n}function we(e,t,n,i=!0){let r=e[t];if(r==null||r===""){if(i)return null;throw new Error(`Invalid Classic state: ${t} is required`)}if(typeof r!="string"||!n.includes(r))throw new Error(`Invalid Classic state: ${t} must be one of ${n.join(", ")}${i?" or null":""}`);return r}function gl(e,t,n=!0){let i=e[t];if(i==null||i===""){if(n)return null;throw new Error(`Invalid Classic state: ${t} is required`)}if(typeof i!="boolean")throw new Error(`Invalid Classic state: ${t} must be true or false`);return i}function _k(e,t,n=0){let i=e[t];if(i==null||i==="")return n;if(typeof i!="number"||!Number.isInteger(i)||i<0)throw new Error(`Invalid Classic state: ${t} must be a non-negative integer`);return i}function go(e,t){let n=ti(e,t);if(n===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${t} must be a relative repository path`);return n}function xk(e,t){let n=ti(e,t);if(n!==null&&!/^[a-f0-9]{64}$/u.test(n))throw new Error(`Invalid Classic state: ${t} must be a sha256 hex digest`);return n}function Pk(e){let t=e.classic_migration;if(t==null||t==="")return null;if(t!==Qt)throw new Error(`Invalid Classic state: classic_migration must be ${Qt}`);return t}function Ok(e){if(!Zt.some(n=>Hm(e,n)))return null;for(let n of Rk)if(!Hm(e,n))return null;return{workflow:we(e,"workflow",wl,!1),language:we(e,"language",mk),phase:we(e,"phase",Km,!1),contextCompression:we(e,"context_compression",pk),buildMode:we(e,"build_mode",hk),buildPause:we(e,"build_pause",gk),subagentDispatch:we(e,"subagent_dispatch",wk),tddMode:we(e,"tdd_mode",yk),reviewMode:we(e,"review_mode",vk),isolation:we(e,"isolation",bk),boundBranch:ti(e,"bound_branch"),verifyMode:we(e,"verify_mode",Ck),autoTransition:gl(e,"auto_transition"),baseRef:ti(e,"base_ref"),designDoc:go(e,"design_doc"),plan:go(e,"plan"),verifyResult:we(e,"verify_result",kk,!1),verifyFailures:_k(e,"verify_failures"),verificationReport:go(e,"verification_report"),branchStatus:we(e,"branch_status",Sk),createdAt:ti(e,"created_at"),verifiedAt:ti(e,"verified_at"),archiveConfirmation:we(e,"archive_confirmation",Ek),archived:gl(e,"archived",!1),directOverride:gl(e,"direct_override"),handoffContext:go(e,"handoff_context"),handoffHash:xk(e,"handoff_hash"),classicProfile:we(e,"classic_profile",wl),classicMigration:Pk(e)}}function mr(e,t){let n=t??null;if(n===null&&t===void 0&&e.run_id&&e.skill)try{n=mo(e)}catch(i){let r=i instanceof Error?i.message:String(i);throw new Error(r.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:i})}return{classic:Ok(e),run:n,unknownKeys:Object.keys(e).filter(i=>!Jm.has(i))}}function Um(e){let t=e.workflow,n=e.phase,i=e.archived,r=e.design_doc;return{workflow:typeof t=="string"&&wl.includes(t)?t:null,phase:typeof n=="string"&&Km.includes(n)?n:null,archived:i===!0,designDoc:typeof r=="string"&&r!==""?r:null,unknownKeys:Object.keys(e).filter(s=>!Jm.has(s))}}function Vm(e){return{workflow:e.workflow,language:e.language,phase:e.phase,context_compression:e.contextCompression,build_mode:e.buildMode,build_pause:e.buildPause,subagent_dispatch:e.subagentDispatch,tdd_mode:e.tddMode,review_mode:e.reviewMode,isolation:e.isolation,bound_branch:e.boundBranch,verify_mode:e.verifyMode,auto_transition:e.autoTransition,base_ref:e.baseRef,design_doc:e.designDoc,plan:e.plan,verify_result:e.verifyResult,verify_failures:e.verifyFailures,verification_report:e.verificationReport,branch_status:e.branchStatus,created_at:e.createdAt,verified_at:e.verifiedAt,archive_confirmation:e.archiveConfirmation,archived:e.archived,direct_override:e.directOverride,handoff_context:e.handoffContext,handoff_hash:e.handoffHash,classic_profile:e.classicProfile,classic_migration:e.classicMigration}}fr();var $k=2*1024*1024;function ni(e){let t=e.toJS();if(t===null)return{};if(typeof t!="object"||Array.isArray(t))throw new Error("Invalid Classic state document: root must be a mapping");return t}function Ym(e,t,n){e.get(t)!==n&&e.set(t,n)}function Ik(e,t){if(t.classic)for(let[n,i]of Object.entries(Vm(t.classic)))Ym(e,n,i);else for(let n of Zt)e.delete(n);pl(e.toJS(),t.run),t.run?Ym(e,"run_id",t.run.runId):e.delete("run_id")}function Ak(e){let t=["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 t)e.delete(n)}function Nk(e){let t=!1;for(let n of["build_command","verify_command"])e.has(n)&&(e.delete(n),t=!0);return t}async function yl(e){let t;try{t=(await Y(pr.dirname(e),pr.basename(e),$k,{label:"Classic state document"})).bytes.toString("utf8")}catch(i){if(i.code!=="ENOENT")throw i;return new wo.Document({})}let n=(0,wo.parseDocument)(t);if(n.errors.length>0)throw new Error(`Invalid Classic state document: ${n.errors[0].message}`);return ni(n),n}async function W(e,t={}){let n=t.migrate!==!1,i=pr.join(e,".comet.yaml"),r=await yl(i),s=ni(r),o=Nk(r);o&&(s=ni(r));let a=await ur(e);if(!a&&s.run_id&&s.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>(fr(),Wm));a=c(s),a&&n&&(await ho(e,a),Ak(r),o=!0)}return o&&n&&await qe(i,r.toString(),{containedRoot:e}),mr(ni(r),a)}async function Gm(e){let t=await yl(pr.join(e,".comet.yaml"));return Um(ni(t))}async function Ne(e,t,n={}){let i=pr.join(e,".comet.yaml"),r=await yl(i);Ik(r,{...t,unknownKeys:t.unknownKeys??[]}),mr(ni(r),t.run??null),await qe(i,r.toString(),{containedRoot:e,beforeCommit:n.beforeCommit}),t.run?await ho(e,t.run):await hl(e)}function zm(e,t,n){return{runId:t,skill:e.definition.metadata.name,skillVersion:e.definition.metadata.version,skillHash:n,orchestration:e.definition.orchestration.mode,currentStep:e.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:{}}}fo();import yo from"path";var rt={trajectory:8*1024*1024,artifacts:1024*1024,context:1024*1024,pendingAction:256*1024,checkpoint:256*1024};function Ve(e,t){if(yo.isAbsolute(t))throw new Error("Run path must stay inside the change directory");let n=yo.resolve(e),i=yo.resolve(n,t);if(i!==n&&!i.startsWith(n+yo.sep))throw new Error("Run path must stay inside the change directory")}async function De(e,t,n,i={}){Ve(e,t),await lo(e,t,`${JSON.stringify(n)}
|
|
165
|
+
`))throw new Error("Invalid project config write transaction: unexpected fields");if(i.schema!==ym)throw new Error("Invalid project config write transaction: unsupported schema");if(typeof i.id!="string"||!vm.test(i.id))throw new Error("Invalid project config write transaction: invalid id");if(typeof i.owner_pid!="number"||!Number.isSafeInteger(i.owner_pid)||i.owner_pid<=0)throw new Error("Invalid project config write transaction: invalid owner pid");if(typeof i.expected_sha256!="string"||!eo.test(i.expected_sha256)||typeof i.output_sha256!="string"||!eo.test(i.output_sha256))throw new Error("Invalid project config write transaction: invalid config hash");if(i.candidate!==bm(i.id)||i.quarantine!==Cm(i.id))throw new Error("Invalid project config write transaction: paths do not match its id");return{journal:i,source:t.toString("utf8")}}async function to(e,t){try{let{bytes:n}=await Y(e,t,il,{label:t});return nl(n)}catch(n){if(km(n))return null;throw n}}async function wm(e,t,n,i){let r=await T(e,t,{label:t,expected:"file"});if(!r.exists)return!1;let s=`${t}.${PC()}.cleanup`,o=await T(e,s,{label:`${t} cleanup`,expected:"file"});if(o.exists)throw new Error(`Owned cleanup path already exists: ${s}`);if(await Yt.rename(r.target,o.target),await i?.(t,s),await to(e,s)!==n){try{let c=await T(e,t,{label:t,expected:"file"});c.exists||(await Yt.link(o.target,c.target),await Yt.unlink(o.target))}catch{}throw new Error(`Refusing to remove modified project config transaction file: ${t}`)}return await Yt.unlink(o.target),!0}function $C(e){if(e===process.pid)return!0;try{return process.kill(e,0),!0}catch(t){return t.code!=="ESRCH"}}async function IC(e,t){let n=OC(t.journal.id),i=await T(e,n,{label:"project config write transaction cleanup",expected:"file"});if(i.exists)throw new Error("Project config write transaction cleanup path already exists");let r=await T(e,Zs,{label:"project config write transaction",expected:"file"});if(!r.exists)throw new Error("Project config write transaction changed before cleanup");await Yt.rename(r.target,i.target);let s=await Y(e,n,il,{label:"project config write transaction cleanup"});if(nl(s.bytes)!==nl(t.source)){try{let o=await T(e,Zs,{label:"project config write transaction",expected:"file"});o.exists||await Yt.link(i.target,o.target)}catch{}throw new Error("Project config write transaction changed before cleanup")}await Yt.unlink(i.target)}async function Sm(e,t,n,i){if(!vm.test(t))throw new Error("Invalid project config write transaction id");if(!eo.test(n)||!eo.test(i))throw new Error("Invalid project config write transaction hash");if(await rl(e))throw new Error("An unfinished project config write transaction exists; run comet doctor --repair");let r={schema:ym,id:t,owner_pid:process.pid,expected_sha256:n,output_sha256:i,candidate:bm(t),quarantine:Cm(t)};return await qe((await T(e,Zs,{label:"project config write transaction",expected:"file"})).target,`${JSON.stringify(r,null,2)}
|
|
166
|
+
`,{containedRoot:e,exclusive:!0}),{candidate:r.candidate,quarantine:r.quarantine}}async function no(e){let t=await rl(e);if(!t)return null;let{journal:n}=t,[i,r,s]=await Promise.all([gt(e),to(e,n.candidate),to(e,n.quarantine)]);if(r!==null&&r!==n.output_sha256)throw new Error("Project config write transaction candidate changed after creation");if(s!==null&&s!==n.expected_sha256)throw new Error("Project config write transaction quarantine changed after creation");let o;return!i.exists&&s===n.expected_sha256?o="config-quarantined":i.sha256===n.output_sha256?o="published-cleanup-pending":i.exists&&i.sha256!==n.expected_sha256&&i.sha256!==n.output_sha256?o="successor-preserved-cleanup-pending":o="prepared",{id:n.id,stage:o,candidate:n.candidate,quarantine:n.quarantine,allowedRepair:"rollback-or-cleanup"}}async function io(e,t={}){let n=await rl(e);if(!n)return!1;let{journal:i}=n;if(t.ownerId!==i.id&&$C(i.owner_pid))throw new Error(`Project config write transaction ${i.id} is still active in process ${i.owner_pid}`);if(!await no(e))return!1;let s=await gt(e),o=await to(e,i.quarantine);if(!s.exists){if(o!==i.expected_sha256)throw new Error("Cannot recover project config write transaction: the config and owned quarantine are missing");let a=await T(e,ce,{label:ce,expected:"file"}),c=await T(e,i.quarantine,{label:"project config write transaction quarantine",expected:"file"});try{await Yt.link(c.target,a.target)}catch(l){if(l.code!=="EEXIST")throw l}if(s=await gt(e),!s.exists)throw new Error("Cannot recover project config write transaction: config publish failed")}return await wm(e,i.candidate,i.output_sha256,t.testHooks?.afterOwnedFileQuarantine),s.exists&&await wm(e,i.quarantine,i.expected_sha256,t.testHooks?.afterOwnedFileQuarantine),await IC(e,n),!0}var ym,Zs,il,vm,eo,sl=he(()=>{"use strict";Xn();wt();Me();ym="comet.project-config-write.v1",Zs=".comet/config-write-transaction.json",il=16*1024,vm=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,eo=/^[0-9a-f]{64}$/});import{createHash as Em,randomUUID as NC}from"crypto";import{promises as Rm}from"fs";import ol from"path";async function al(e,t){if(!t)return;let n=await gt(e);if(!Zc(n,t))throw new Error("Project config changed before commit; rerun the operation")}async function cl(e,t,n={}){vn(t,{allowPartialProject:n.allowPartialProject??!1});let i=ol.resolve(e);if(await no(i))throw new Error("An unfinished project config write transaction exists; run comet doctor --repair");let r=n.expectedIdentity??await gt(i);await al(i,r);let s=await T(i,ce,{label:ce,expected:"file"}),o=NC(),a=Em("sha256").update(t).digest("hex"),c=r.exists&&r.sha256?await Sm(i,o,r.sha256,a):null,l=c!==null,f=c?.candidate??`.comet/config.yaml.${o}.next`,u=ol.join(i,...f.split("/")),d=c?.quarantine??null;try{if(await qe(u,t,{containedRoot:i,exclusive:!0}),await n.beforeCommit?.(),await al(i,r),await T(i,f,{label:"project config candidate",expected:"file"}),r.exists){if(!d)throw new Error("Project config write transaction was not created");let g=ol.join(i,...d.split("/"));if(await T(i,ce,{label:ce,expected:"file"}),(await T(i,d,{label:"project config quarantine",expected:"file"})).exists)throw new Error("Project config quarantine already exists");await Rm.rename(s.target,g);let{bytes:m}=await Y(i,d,er,{label:"project config quarantine"});if(Em("sha256").update(m).digest("hex")!==r.sha256)throw new Error("Project config changed before final publish; successor was preserved")}else if(s.exists)throw new Error("Project config changed before final publish; successor was preserved");await n.beforePublish?.(),await T(i,f,{label:"project config candidate",expected:"file"});try{await Qs(u,s.target)}catch(g){throw new Error("Project config final publish failed; successor was preserved",{cause:g})}let h=await gt(i);if(!h.exists||h.sha256!==a)throw new Error("Project config changed during final publish; successor was preserved");l&&(await io(i,{ownerId:o}),l=!1)}catch(h){if(l)try{await io(i,{ownerId:o})&&(l=!1)}catch{}throw h}finally{l||await TC(i,f).catch(()=>!1)}}async function TC(e,t){let n=await T(e,t,{label:t,expected:"file"});return n.exists?(await Rm.unlink(n.target),!0):!1}var ll=he(()=>{"use strict";Xn();ht();wt();Me();sl()});var lo=he(()=>{"use strict"});var Mm=he(()=>{"use strict"});var dl=he(()=>{"use strict";lo()});var qm=he(()=>{"use strict";lo();dl()});var Dm=he(()=>{"use strict";lo();Xn();Mm();qm();ht();Me();wt();ll();sl();dl()});import{TextDecoder as lk}from"util";function Fm(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function uk(e,t){try{return new lk("utf-8",{fatal:!0}).decode(e.bytes)}catch(n){throw new Error(`${t} is not valid UTF-8`,{cause:n})}}async function ml(e,t,n,i,r={}){try{let s=await Y(e,t,n,{label:i,hooks:r.hooks});return{result:s,text:uk(s,i)}}catch(s){let o=s.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw s}}async function Ct(e,t,n,i,r={}){return(await ml(e,t,n,i,r))?.text??null}async function Xt(e,t,n,i,r,s={}){if(Buffer.byteLength(n,"utf8")>i)throw new Error(`${r} exceeds ${i} bytes`);let o=await ml(e,t,i,r),a=await T(e,t,{label:r,expected:"file"});await qe(a.target,n,{containedRoot:a.projectRoot,beforeCommit:async()=>{await s.beforeCommit?.();let c=await ml(e,t,i,r);if(!(!o&&!c)){if(!o||!c)throw new Error(`${r} changed before commit`);if(o.result.realPath!==c.result.realPath||!Ae(Fm(o.result.stat),Fm(c.result.stat))||o.text!==c.text)throw new Error(`${r} changed before commit`)}}})}async function uo(e,t,n,i,r,s={}){let o=await Ct(e,t,i,r);await Xt(e,t,`${o??""}${n}`,i,r,s)}async function fo(e,t,n,i={}){let r=await T(e,t,{label:n,expected:"file"});return r.exists?tl(r.target,{containedRoot:r.projectRoot,beforeRemove:i.beforeRemove}):!1}var mo=he(()=>{"use strict";Dm();tr()});var Hm={};Ag(Hm,{RUN_STATE_FILE:()=>ho,applyRunStateToDocument:()=>pl,readRunState:()=>ur,removeRunState:()=>hl,runStateFromDocument:()=>po,writeRunState:()=>go});import fk from"path";function lr(e,t){let n=e[t];if(typeof n!="string"||n.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return n}function cr(e,t){let n=lr(e,t);if(fk.isAbsolute(n)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return n}function dk(e){let t=e.run_retries??"{}",n;try{n=typeof t=="string"?JSON.parse(t):t}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(n))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return n}function po(e){if(!e.run_id)return null;let t=lr(e,"run_id"),n=lr(e,"skill"),i=lr(e,"skill_version"),r=lr(e,"skill_hash"),s=cr(e,"pending_ref"),o=cr(e,"trajectory_ref"),a=cr(e,"context_ref"),c=cr(e,"artifacts_ref"),l=cr(e,"checkpoint_ref"),f=Number(e.iteration);if(!Number.isInteger(f)||f<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(e.orchestration!=="deterministic"&&e.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(e.run_status!=="running"&&e.run_status!=="waiting"&&e.run_status!=="completed"&&e.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:t,skill:n,skillVersion:i,skillHash:r,orchestration:e.orchestration,currentStep:Bm(e,"current_step"),iteration:f,pending:Bm(e,"pending"),pendingRef:s,trajectoryRef:o,contextRef:a,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:dk(e)}}function pl(e,t){t?e.run_id=t.runId:delete e.run_id}function mk(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,currentStep:e.currentStep,iteration:e.iteration,pending:e.pending,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,status:e.status,retries:e.retries}}function pk(e){let t={run_id:e.runId,skill:e.skill,skill_version:e.skillVersion,skill_hash:e.skillHash,orchestration:e.orchestration,current_step:e.currentStep,iteration:e.iteration,pending:e.pending,pending_ref:e.pendingRef,trajectory_ref:e.trajectoryRef,context_ref:e.contextRef,artifacts_ref:e.artifactsRef,checkpoint_ref:e.checkpointRef,run_status:e.status,run_retries:JSON.stringify(e.retries)};return po(t)}async function ur(e,t={}){let n=await Ct(e,ho,Wm,"Run state",t);if(n===null)return null;let i=JSON.parse(n);return pk(i)}async function go(e,t,n={}){await Xt(e,ho,JSON.stringify(mk(t),null,2),Wm,"Run state",n)}async function hl(e,t={}){await fo(e,ho,"Run state",t)}var Bm,ho,Wm,fr=he(()=>{"use strict";mo();Bm=(e,t)=>{let n=e[t];return n==null?null:String(n)};ho=".comet/run-state.json",Wm=256*1024});import{pathToFileURL as fx}from"url";import{createHash as _S}from"crypto";import{promises as xS}from"fs";import st from"path";import{spawnSync as WC}from"child_process";function Tg(e){return e.length>0&&/^[A-Za-z0-9@+=:,./\\_-]+$/.test(e)?e:`"${e.replace(/"/g,'""')}"`}function hu(e){return e.map(t=>Tg(t))}import{promises as jC}from"fs";import G from"path";import{promises as gu}from"fs";async function ki(e){try{return await gu.access(e),!0}catch(t){if(jg(t))return!1;throw t}}async function wu(e){try{return await gu.readdir(e)}catch(t){let n=t?.code;if(n==="ENOENT"||n==="ENOTDIR")return[];throw t}}function jg(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}ht();wt();ll();Me();var ir=class extends Error{code="classic-layout-unavailable";constructor(t="Classic artifact layout is unavailable from .comet/config.yaml"){super(t),this.name="ClassicLayoutUnavailableError"}},ul=class extends Error{constructor(n,i,r){let s=N(r,n),o=N(r,i);super(`Classic layout conflict: both ${s}/ and ${o}/ exist; run comet doctor and resolve the conflict before writing`);this.configuredRoot=n;this.alternateRoot=i;this.name="ClassicLayoutConflictError"}configuredRoot;alternateRoot;code="classic-layout-conflict"},_m=".comet/config.yaml";function LC(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function ro(e){await T(e,_m,{label:_m,expected:"file"})}function yt(e,t){let n=G.resolve(e),i=t==="docs"?G.join(n,"docs"):n,r=G.join(i,"openspec"),s=G.join(n,"docs","superpowers");return{projectRoot:n,artifactLayout:t,openSpecBase:i,openSpecRoot:r,changesDir:G.join(r,"changes"),archiveDir:G.join(r,"changes","archive"),specsDir:G.join(r,"specs"),superpowersRoot:s,superpowersSpecsDir:G.join(s,"specs"),superpowersPlansDir:G.join(s,"plans"),superpowersReportsDir:G.join(s,"reports")}}async function Gt(e){await ro(e);let t=await it(e,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!t?.config)throw new ir;if(!(t.config.workflows??[t.config.default_workflow]).includes("classic"))throw new ir("Classic artifact layout is unavailable because Classic is not enabled");return t.classic?.artifact_layout??"legacy"}async function xm(e){await ro(e);let t=(await it(e))?.config;if(!t)throw new Error(".comet/config.yaml must use comet.project.v1 before migration");if(!(t.workflows??[t.default_workflow]).includes("classic"))throw new Error("Classic root move requires the Classic workflow to be enabled")}async function Pm(e,t,n={}){await ro(e);let i=await kn(e,{allowPartialProject:!0}),r=i.document;if(!r)throw new Error(".comet/config.yaml does not exist");let s=r.value.classic;if(!s||typeof s!="object"||Array.isArray(s))throw new Error("classic must be a mapping");let o={...r.value,classic:{...s,artifact_layout:t}},a=Gn(o,r.classic?.language==="zh-CN"||r.native?.language==="zh-CN"?"zh-CN":"en");vn(a,{allowPartialProject:!0}),await cl(e,a,{expectedIdentity:n.expectedIdentity??i.identity,beforeCommit:n.beforeCommit})}async function MC(e,t){return yt(e,t??await Gt(e))}async function qC(e,t){let n=await MC(e,t),i=n.artifactLayout==="legacy"?"docs":"legacy",r=yt(e,i).openSpecRoot,[s,o]=await Promise.all([T(n.projectRoot,N(n.projectRoot,n.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),T(n.projectRoot,N(n.projectRoot,r),{label:"Alternate Classic OpenSpec root",expected:"directory"})]),a=s.exists,c=o.exists;return{paths:n,configuredRootExists:a,alternateRoot:r,alternateRootExists:c,dualRoots:a&&c}}async function DC(e,t){let n=[e.openSpecRoot,e.changesDir,e.archiveDir,e.specsDir,t,e.superpowersRoot,e.superpowersSpecsDir,e.superpowersPlansDir,e.superpowersReportsDir];for(let i of n){let r=N(e.projectRoot,i);await T(e.projectRoot,r,{label:`Classic managed physical path ${r}`,expected:"directory"})}}async function Z(e,t,n={}){let i=await qC(e,t);if(await DC(i.paths,i.alternateRoot),i.dualRoots&&!n.allowAlternateRoot)throw new ul(i.paths.openSpecRoot,i.alternateRoot,i.paths.projectRoot);if(!i.configuredRootExists){let r=N(i.paths.projectRoot,i.paths.openSpecRoot),s=N(i.paths.projectRoot,i.alternateRoot);throw new ir(`Configured Classic OpenSpec root is missing: ${r} (alternate ${s} is ${i.alternateRootExists?"present":"missing"})`)}return i.paths}async function Ee(e,t,n={}){let i=G.join(G.resolve(e),".comet","classic-root-move.json");if(await ki(i))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let r=await Z(e,t,n);if(!await ki(r.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${N(r.projectRoot,r.openSpecRoot)}`);return r}async function ue(e){let t=G.resolve(e),n=null;try{(await jC.lstat(t)).isDirectory()||(t=G.dirname(t))}catch(i){if(!LC(i))throw i}for(;;){G.basename(t)==="openspec"&&(n=G.dirname(t));let i=G.join(t,".comet","config.yaml"),r=!1;if(await ki(i))try{await ro(t);let o=(await it(t))?.value;r=!!o&&typeof o=="object"&&!Array.isArray(o)&&(o.schema==="comet.project.v1"||o.default_workflow!==void 0||o.native!==void 0)}catch{}if(r||await ki(G.join(t,".git")))return t;let s=G.dirname(t);if(s===t)return n??G.resolve(e);t=s}}function N(e,t){return G.relative(G.resolve(e),t).replaceAll("\\","/")}var Om=ft(nt(),1);Me();import FC from"path";var BC=1024*1024;async function $m(e,t){let n=t??await Z(e),i=FC.join(n.openSpecRoot,"config.yaml"),r=N(n.projectRoot,i),s;try{s=(await Y(n.projectRoot,r,BC,{label:"Classic OpenSpec project config",bigint:!0})).bytes.toString("utf8")}catch(l){throw l.code==="ENOENT"?new Error(`Classic OpenSpec root is unhealthy: ${r} 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,Om.parseDocument)(s,{uniqueKeys:!0});if(o.errors.length>0)throw new Error(`Classic OpenSpec root is unhealthy: ${r} 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: ${r} must contain a mapping`);let c=a.schema;if(typeof c!="string"||c.trim()==="")throw new Error(`Classic OpenSpec root is unhealthy: ${r} must declare a non-empty schema`);return{layout:n,configPath:r,schema:c}}function HC(e){return e[0]==="--"?e.slice(1):[...e]}async function fl(e,t=process.cwd()){let n=HC(e);if(n.length===0)return{exitCode:64,stderr:"Usage: comet classic openspec -- <openspec-args...>"};let i=await ue(t),r=await Ee(i);await $m(i,r);let s=process.env.COMET_OPENSPEC||"openspec",o=process.platform==="win32",a=WC(s,o?hu(n):n,{cwd:r.openSpecBase,encoding:"utf8",shell:o,windowsHide:!0});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}}var Im=async e=>fl(e);import{promises as JC}from"fs";import Rn from"path";Xn();ht();Me();import rr from"path";var KC=2*1024*1024;function so(e,t,n){let i=rr.resolve(e),r=rr.isAbsolute(t)?rr.resolve(t):rr.resolve(i,t),s=rr.relative(i,r).replaceAll("\\","/");return{root:i,relative:Ht(s,n),target:r}}async function V(e,t,n){let i=so(e,t,n.label);return T(i.root,i.relative,n)}async function ee(e,t,n){return(await V(e,t,{label:n.label,expected:n.expected??"any"})).exists}async function Sn(e,t,n,i){return await ee(e,t,{label:n,expected:"file"})?(await oo(e,t,{label:n,hooks:i})).byteLength>0:!1}async function B(e,t,n){return(await oo(e,t,n)).toString("utf8")}async function oo(e,t,n){let i=so(e,t,n.label);return(await Y(i.root,i.relative,n.maxBytes??KC,{label:n.label,hooks:n.hooks})).bytes}async function En(e,t,n){let i=so(e,t,n);return Qc(i.root,i.relative,{label:n})}async function Qn(e,t,n,i){let r=so(e,t,i.label);await T(r.root,r.relative,{label:i.label,expected:"file"}),await qe(r.target,n,{containedRoot:r.root,beforeTemporaryOpen:i.beforeTemporaryOpen,beforeCommit:i.beforeCommit,exclusive:i.exclusive})}function ge(e){return e?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e)?e.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${e}'
|
|
167
|
+
Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function zt(e){let t=ge(e);if(t)throw new Error(t)}function UC(e,t){return{label:N(e,t),directory:t}}async function Zn(e,t,n){let i=UC(e,t);if(!(await V(e,t,{label:n,expected:"directory"})).exists)return{change:i,exists:!1,stateExists:!1};let s=await V(e,Rn.join(t,".comet.yaml"),{label:`${n} state`,expected:"file"});return{change:i,exists:!0,stateExists:s.exists}}function Am(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${n}$`,"u").test(e)}async function Nm(e,t,n,i={}){if(!i.skipExactCompatibility){let o=await Zn(e,Rn.join(t,n),`Classic archived change ${n}`);if(o.exists)return o.change}if(!(await V(e,t,{label:"Classic archive directory",expected:"directory"})).exists)return null;let s=[];for(let o of await JC.readdir(t,{withFileTypes:!0})){if(!Am(o.name,n))continue;let a=await Zn(e,Rn.join(t,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 Je(e,t=process.cwd()){zt(e);let n=await Z(t),i=await Zn(n.projectRoot,Rn.join(n.changesDir,e),`Classic active change ${e}`);return{...i.change,exists:i.exists,stateExists:i.stateExists}}async function Tm(e,t=process.cwd()){zt(e);let n=await Ee(t),i=Rn.join(n.changesDir,e),r=await Zn(n.projectRoot,i,`Classic active change ${e}`);return r.exists||await En(n.projectRoot,i,`Classic active change ${e}`),r.change}async function ao(e,t=process.cwd(),n={}){zt(e);let i=await Z(t);if(n.preferredArchiveName!==void 0){let r=n.preferredArchiveName;if(r!==e&&!Am(r,e))throw new Error(`Classic preferred archive name '${r}' does not belong to change '${e}'`);let s=await Zn(i.projectRoot,Rn.join(i.archiveDir,r),`Classic preferred archived change ${r}`);return s.exists&&s.stateExists?s.change:null}return Nm(i.projectRoot,i.archiveDir,e,n)}async function ei(e,t=process.cwd()){zt(e);let n=await Z(t),i=await Zn(n.projectRoot,Rn.join(n.changesDir,e),`Classic active change ${e}`);if(i.exists)return i.change;let r=await Nm(n.projectRoot,n.archiveDir,e);return r||i.change}import{promises as Cp}from"fs";import ve from"path";import{fileURLToPath as Sl}from"url";import{promises as YC}from"fs";import vt from"path";Me();ht();import sr from"path";function VC(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function jm(e,t,n,i){let r=Ht(n,"Classic handoff artifact pointer");if((await T(e,r,{label:"Classic handoff artifact",expected:"file"})).exists)return null;let o=await Z(e),a=`${N(e,o.changesDir)}/`,l=(o.artifactLayout==="docs"?[a,"openspec/changes/"]:[a]).find(y=>r.startsWith(y));if(!l)return null;let f=r.slice(l.length).split("/");if(f.length<4||f[1]!==".comet"||f.slice(2).some(y=>y.length===0))return null;let u=f[0];zt(u);let d=f.slice(2),h=sr.resolve(t);if(sr.dirname(h)!==sr.resolve(o.archiveDir))return null;let g=sr.basename(h),p=/^\d{4}-\d{2}-\d{2}-(.+)$/u.exec(g);if(g!==u&&p?.[1]!==u)return null;await T(e,N(e,h),{label:"Classic archived change directory",expected:"directory"});let m=sr.join(h,".comet",...d),w=N(e,m);try{return await Y(e,w,i,{label:"Historical Classic archived handoff artifact"}),w}catch(y){if(VC(y))return null;throw y}}Me();var Lm=2*1024*1024;function or(e,t){return vt.relative(e,t).split(vt.sep).join("/")}async function ar(e,t,n){if(!n)return{code:t,satisfied:!1};let i=n.replaceAll("\\","/");try{let r=await Ys(e,i,{label:`${t} artifact`});return{code:t,satisfied:r,source:i,...r?{resolvedSource:i}:{}}}catch(r){return{code:t,satisfied:!1,source:i,detail:`unsafe artifact pointer outside the project or through a special path: ${r instanceof Error?r.message:String(r)}`}}}async function GC(e,t,n){try{await Z(e)}catch(r){return{code:"design.handoff",satisfied:!1,...n?{source:n.replaceAll("\\","/")}:{},detail:`Classic layout is unsafe or unavailable for handoff evidence: ${r instanceof Error?r.message:String(r)}`}}let i=await ar(e,"design.handoff",n);if(!n||i.satisfied||i.detail)return i;try{let r=await jm(e,t,n,Lm);return r?{...i,satisfied:!0,resolvedSource:r,detail:`resolved historical legacy pointer from archived change: ${r}`}:i}catch(r){return{...i,satisfied:!1,detail:`unsafe archived handoff fallback: ${r instanceof Error?r.message:String(r)}`}}}async function co(e,t,n){return ar(e,t,or(e,n))}async function zC(e,t){let n=vt.join(t,"specs"),i;try{let o=or(e,n);if(!(await T(e,o,{label:"OpenSpec delta-spec directory",expected:"directory"})).exists)return{code:"openspec.delta-spec",satisfied:!1};i=await YC.readdir(n)}catch(o){return o.code==="ENOENT"?{code:"openspec.delta-spec",satisfied:!1}:{code:"openspec.delta-spec",satisfied:!1,detail:`unsafe delta-spec path: ${o instanceof Error?o.message:String(o)}`}}let r=i.map(o=>vt.join(n,o,"spec.md")),s=(await Promise.all(r.map(async o=>{try{return await Ys(e,or(e,o),{label:"OpenSpec delta spec"})?o:null}catch{return null}}))).filter(o=>o!==null);return{code:"openspec.delta-spec",satisfied:s.length>0,source:s[0]?or(e,s[0]):void 0,detail:`${s.length} delta spec${s.length===1?"":"s"}`}}async function XC(e,t){let n,i=or(e,t);try{n=(await Y(e,i,Lm,{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:i,detail:`unsafe tasks artifact: ${o instanceof Error?o.message:String(o)}`}}let r=[...n.matchAll(/^\s*[-*]\s+\[([ xX])\]\s+/gmu)],s=r.filter(o=>o[1].toLowerCase()==="x").length;return{code:"build.tasks-complete",satisfied:r.length>0&&s===r.length,source:i,detail:`${s} of ${r.length} tasks complete`}}function _n(e,t){return e.some(n=>n.code===t&&n.satisfied)}async function Ue(e,t){let n=await ue(e),i=t.classic,r=vt.join(e,"proposal.md"),s=vt.join(e,"design.md"),o=vt.join(e,"tasks.md"),a=t.run?vt.resolve(e,t.run.checkpointRef):vt.join(e,".comet","checkpoint.json"),c=await Promise.all([co(n,"openspec.proposal",r),co(n,"openspec.design",s),co(n,"openspec.tasks",o),zC(n,e),ar(n,"design.document",i?.designDoc??null),ar(n,"build.plan",i?.plan??null),XC(n,o),ar(n,"verification.report",i?.verificationReport??null),GC(n,e,i?.handoffContext??null),co(n,"run.checkpoint",a)]),l=c.find(f=>f.code==="design.handoff");return l&&!i?.handoffHash&&(l.satisfied=!1,l.detail="handoff hash is missing"),c.push({code:"archive.confirmed",satisfied:i?.archiveConfirmation==="confirmed"}),c}import{createHash as rS,randomUUID as sS}from"crypto";import{promises as kl}from"fs";import kt from"path";function QC(e){return e.classicProfile??e.workflow}function ZC(e){return!e.buildMode||!e.tddMode||!e.isolation||!e.verifyMode?!1:e.buildMode==="subagent-driven-development"?e.subagentDispatch==="confirmed":e.buildMode==="direct"?e.directOverride===!0:!0}function ek(e){return e.buildMode==="direct"&&e.tddMode==="direct"&&e.isolation!==null&&e.verifyMode==="light"}function tk(e,t,n){if(t.verifyResult==="fail")return e==="full"?"full.build.fix":`${e}.build.execute`;if(e==="full"){if(!_n(n,"build.plan"))return"full.build.plan";if(t.buildPause==="plan-ready")return"full.build.plan-ready";if(!ZC(t))return"full.build.configure"}else if(!ek(t))throw new Error(`${e} build configuration is incomplete`);return _n(n,"build.tasks-complete")?`${e}.build.complete`:`${e}.build.execute`}function nk(e,t,n){return t.verifyResult!=="pass"||!_n(n,"verification.report")?`${e}.verify.run`:`${e}.verify.branch`}function ik(e,t){if(t.verifyResult!=="pass")throw new Error("archive requires verify_result=pass");return t.archiveConfirmation==="confirmed"?`${e}.archive.execute`:`${e}.archive.confirm`}function bt(e,t){let n=QC(e);if(e.archived&&e.phase!=="archive")throw new Error("archived=true requires phase=archive");if(e.archived)return"completed";if(n!=="full"&&e.phase==="design")throw new Error(`${n} workflow cannot enter design`);switch(e.phase){case"open":return`${n}.open`;case"design":return _n(t,"design.handoff")?"full.design.document":"full.design.handoff";case"build":return tk(n,e,t);case"verify":return nk(n,e,t);case"archive":return ik(n,e)}}var yo=ft(nt(),1);Xn();Me();import pr from"path";fr();var wl=["full","hotfix","tweak"],Qt=1,Jm=["open","design","build","verify","archive"],hk=["en","zh-CN"],gk=["off","beta"],wk=["subagent-driven-development","executing-plans","direct"],yk=["plan-ready"],vk=["confirmed"],bk=["tdd","direct"],Ck=["off","standard","thorough"],kk=["current","branch","worktree"],Sk=["light","full"],Ek=["pending","pass","fail"],Rk=["pending","handled"],_k=["pending","confirmed"],Zt=["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","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],dr=["run_id"],Um=new Set([...Zt,...dr]),xk=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function Km(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ti(e,t){let n=e[t];if(n==null||n==="")return null;if(typeof n!="string")throw new Error(`Invalid Classic state: ${t} must be a string or null`);return n}function we(e,t,n,i=!0){let r=e[t];if(r==null||r===""){if(i)return null;throw new Error(`Invalid Classic state: ${t} is required`)}if(typeof r!="string"||!n.includes(r))throw new Error(`Invalid Classic state: ${t} must be one of ${n.join(", ")}${i?" or null":""}`);return r}function gl(e,t,n=!0){let i=e[t];if(i==null||i===""){if(n)return null;throw new Error(`Invalid Classic state: ${t} is required`)}if(typeof i!="boolean")throw new Error(`Invalid Classic state: ${t} must be true or false`);return i}function Pk(e,t,n=0){let i=e[t];if(i==null||i==="")return n;if(typeof i!="number"||!Number.isInteger(i)||i<0)throw new Error(`Invalid Classic state: ${t} must be a non-negative integer`);return i}function wo(e,t){let n=ti(e,t);if(n===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(n)||n.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${t} must be a relative repository path`);return n}function Ok(e,t){let n=ti(e,t);if(n!==null&&!/^[a-f0-9]{64}$/u.test(n))throw new Error(`Invalid Classic state: ${t} must be a sha256 hex digest`);return n}function $k(e){let t=e.classic_migration;if(t==null||t==="")return null;if(t!==Qt)throw new Error(`Invalid Classic state: classic_migration must be ${Qt}`);return t}function Ik(e){if(!Zt.some(n=>Km(e,n)))return null;for(let n of xk)if(!Km(e,n))return null;return{workflow:we(e,"workflow",wl,!1),language:we(e,"language",hk),phase:we(e,"phase",Jm,!1),contextCompression:we(e,"context_compression",gk),buildMode:we(e,"build_mode",wk),buildPause:we(e,"build_pause",yk),subagentDispatch:we(e,"subagent_dispatch",vk),tddMode:we(e,"tdd_mode",bk),reviewMode:we(e,"review_mode",Ck),isolation:we(e,"isolation",kk),boundBranch:ti(e,"bound_branch"),verifyMode:we(e,"verify_mode",Sk),autoTransition:gl(e,"auto_transition"),baseRef:ti(e,"base_ref"),designDoc:wo(e,"design_doc"),plan:wo(e,"plan"),verifyResult:we(e,"verify_result",Ek,!1),verifyFailures:Pk(e,"verify_failures"),verificationReport:wo(e,"verification_report"),branchStatus:we(e,"branch_status",Rk),createdAt:ti(e,"created_at"),verifiedAt:ti(e,"verified_at"),archiveConfirmation:we(e,"archive_confirmation",_k),archived:gl(e,"archived",!1),directOverride:gl(e,"direct_override"),handoffContext:wo(e,"handoff_context"),handoffHash:Ok(e,"handoff_hash"),classicProfile:we(e,"classic_profile",wl),classicMigration:$k(e)}}function mr(e,t){let n=t??null;if(n===null&&t===void 0&&e.run_id&&e.skill)try{n=po(e)}catch(i){let r=i instanceof Error?i.message:String(i);throw new Error(r.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:i})}return{classic:Ik(e),run:n,unknownKeys:Object.keys(e).filter(i=>!Um.has(i))}}function Vm(e){let t=e.workflow,n=e.phase,i=e.archived,r=e.design_doc;return{workflow:typeof t=="string"&&wl.includes(t)?t:null,phase:typeof n=="string"&&Jm.includes(n)?n:null,archived:i===!0,designDoc:typeof r=="string"&&r!==""?r:null,unknownKeys:Object.keys(e).filter(s=>!Um.has(s))}}function Ym(e){return{workflow:e.workflow,language:e.language,phase:e.phase,context_compression:e.contextCompression,build_mode:e.buildMode,build_pause:e.buildPause,subagent_dispatch:e.subagentDispatch,tdd_mode:e.tddMode,review_mode:e.reviewMode,isolation:e.isolation,bound_branch:e.boundBranch,verify_mode:e.verifyMode,auto_transition:e.autoTransition,base_ref:e.baseRef,design_doc:e.designDoc,plan:e.plan,verify_result:e.verifyResult,verify_failures:e.verifyFailures,verification_report:e.verificationReport,branch_status:e.branchStatus,created_at:e.createdAt,verified_at:e.verifiedAt,archive_confirmation:e.archiveConfirmation,archived:e.archived,direct_override:e.directOverride,handoff_context:e.handoffContext,handoff_hash:e.handoffHash,classic_profile:e.classicProfile,classic_migration:e.classicMigration}}fr();var Ak=2*1024*1024;function ni(e){let t=e.toJS();if(t===null)return{};if(typeof t!="object"||Array.isArray(t))throw new Error("Invalid Classic state document: root must be a mapping");return t}function Gm(e,t,n){e.get(t)!==n&&e.set(t,n)}function Nk(e,t){if(t.classic)for(let[n,i]of Object.entries(Ym(t.classic)))Gm(e,n,i);else for(let n of Zt)e.delete(n);pl(e.toJS(),t.run),t.run?Gm(e,"run_id",t.run.runId):e.delete("run_id")}function Tk(e){let t=["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 t)e.delete(n)}function jk(e){let t=!1;for(let n of["build_command","verify_command"])e.has(n)&&(e.delete(n),t=!0);return t}async function yl(e){let t;try{t=(await Y(pr.dirname(e),pr.basename(e),Ak,{label:"Classic state document"})).bytes.toString("utf8")}catch(i){if(i.code!=="ENOENT")throw i;return new yo.Document({})}let n=(0,yo.parseDocument)(t);if(n.errors.length>0)throw new Error(`Invalid Classic state document: ${n.errors[0].message}`);return ni(n),n}async function W(e,t={}){let n=t.migrate!==!1,i=pr.join(e,".comet.yaml"),r=await yl(i),s=ni(r),o=jk(r);o&&(s=ni(r));let a=await ur(e);if(!a&&s.run_id&&s.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>(fr(),Hm));a=c(s),a&&n&&(await go(e,a),Tk(r),o=!0)}return o&&n&&await qe(i,r.toString(),{containedRoot:e}),mr(ni(r),a)}async function zm(e){let t=await yl(pr.join(e,".comet.yaml"));return Vm(ni(t))}async function Ne(e,t,n={}){let i=pr.join(e,".comet.yaml"),r=await yl(i);Nk(r,{...t,unknownKeys:t.unknownKeys??[]}),mr(ni(r),t.run??null),await qe(i,r.toString(),{containedRoot:e,beforeCommit:n.beforeCommit}),t.run?await go(e,t.run):await hl(e)}function Xm(e,t,n){return{runId:t,skill:e.definition.metadata.name,skillVersion:e.definition.metadata.version,skillHash:n,orchestration:e.definition.orchestration.mode,currentStep:e.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:{}}}mo();import vo from"path";var rt={trajectory:8*1024*1024,artifacts:1024*1024,context:1024*1024,pendingAction:256*1024,checkpoint:256*1024};function Ve(e,t){if(vo.isAbsolute(t))throw new Error("Run path must stay inside the change directory");let n=vo.resolve(e),i=vo.resolve(n,t);if(i!==n&&!i.startsWith(n+vo.sep))throw new Error("Run path must stay inside the change directory")}async function De(e,t,n,i={}){Ve(e,t),await uo(e,t,`${JSON.stringify(n)}
|
|
168
168
|
`,rt.trajectory,"Run trajectory",i)}async function Te(e,t,n={}){Ve(e,t);let i=await Ct(e,t,rt.trajectory,"Run trajectory",n);return i===null?[]:i.split(/\r?\n/).map((r,s)=>({line:r,number:s+1})).filter(({line:r})=>r.length>0).map(({line:r,number:s})=>{try{return JSON.parse(r)}catch(o){throw new Error(`Invalid Trajectory event at line ${s}`,{cause:o})}})}async function ii(e,t,n={}){Ve(e,t);let i=await Ct(e,t,rt.artifacts,"Run artifacts",n);return i===null?{}:JSON.parse(i)}async function ri(e,t,n,i={}){Ve(e,t),await Xt(e,t,JSON.stringify(n,null,2)+`
|
|
169
|
-
`,rt.artifacts,"Run artifacts",i)}async function
|
|
170
|
-
`,rt.pendingAction,"Run pending action",i)}async function hr(e,t,n={}){Ve(e,t);let i=await Ct(e,t,rt.pendingAction,"Run pending action",n);return i===null?null:JSON.parse(i)}async function
|
|
171
|
-
`,rt.checkpoint,"Run checkpoint",i)}async function
|
|
172
|
-
`}async function
|
|
173
|
-
`),await re.rename(s,r)}catch(o){if(await
|
|
174
|
-
`));let l=await Ro(a);if(l!==t)throw new Error(`calculated hash is ${l}`);return a}catch(r){throw new Error(`Skill snapshot is invalid or missing: ${t}`,{cause:r})}}async function wp(e){try{return await kl.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function yp(e){return nS("sha256").update(e).digest("hex")}function rS(e){return yp(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))))}function sS(e){return e.replaceAll(".","_").replaceAll("-","_")}async function oS(e,t){let n=await ue(e),i=Object.fromEntries(t.filter(o=>o.satisfied&&o.source).map(o=>[sS(o.code),o.source])),r=kt.join(e,"subagent-progress.md");await wp(r)&&(i.subagent_progress=kt.relative(n,r).split(kt.sep).join("/"));let s=t.find(o=>o.code==="design.handoff"&&o.satisfied);return s?.source&&(i.handoff_context=s.source),i}function aS(e,t,n){return[{sequence:1,timestamp:n,type:"run_started",runId:e.runId,data:{skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash}},{sequence:2,timestamp:n,type:"state_migrated",runId:e.runId,data:{kind:"classic",migrationVersion:Qt,profile:t,source:"pre-migration"}}]}async function cS(e){await Promise.all(e.map(t=>kl.rm(t,{recursive:!0,force:!0})))}async function vp(e,t){let n=await W(e);if(!n.classic)throw new Error("Classic migration requires a legacy state projection");let i=n.classic,r=i.classicProfile??i.workflow;if(n.run){if(i.classicMigration!==Qt)throw new Error("Classic Run exists without a supported classic_migration marker");if(n.run.skill!==t.skillPackage.definition.metadata.name)throw new Error(`Classic Run skill mismatch: expected ${t.skillPackage.definition.metadata.name}, got ${n.run.skill}`);if(await Ro(t.skillPackage)!==n.run.skillHash)return await _o(e,n.run.skillHash),{classic:i,run:n.run,evidence:await Ue(e,n),migrated:!1,snapshotDir:kt.join(e,".comet","skill-snapshots",n.run.skillHash)};let d=await Cl(t.skillPackage,e);return{classic:i,run:n.run,evidence:await Ue(e,n),migrated:!1,snapshotDir:d.snapshotDir}}let s=await Ue(e,n),o=bt(i,s);if(!t.skillPackage.definition.orchestration.steps?.some(u=>u.id===o))throw new Error(`Classic Skill package does not define resolved step: ${o}`);let a=await Ro(t.skillPackage),c=kt.join(e,".comet","skill-snapshots",a),l=await wp(c),f=[];try{let u=await Cl(t.skillPackage,e),d=zm(t.skillPackage,t.runId?.()??iS(),u.hash);d.currentStep=o,o==="completed"&&(d.status="completed");let h={...i,classicProfile:r,classicMigration:Qt},g=await oS(e,s),p=await ue(e),m=s.find(k=>k.code==="design.handoff"&&k.satisfied),w=null;m?.source&&(w=await B(p,m.resolvedSource??m.source,{label:"Classic migration handoff context",hooks:t.handoffReadHooks}),await vo(e,d.contextRef,w),f.push(kt.resolve(e,d.contextRef))),await ri(e,d.artifactsRef,g),f.push(kt.resolve(e,d.artifactsRef));let y=(t.now?.()??new Date).toISOString(),C={runId:d.runId,stateVersion:1,trajectoryOffset:2,contextHash:w===null?null:yp(w),artifactsHash:rS(g),createdAt:y};await si(e,d.checkpointRef,C),f.push(kt.resolve(e,d.checkpointRef)),f.push(kt.resolve(e,d.trajectoryRef));for(let k of aS(d,r,y))await De(e,d.trajectoryRef,k);return await Ne(e,{classic:h,run:d,unknownKeys:n.unknownKeys}),{classic:h,run:d,evidence:s,migrated:!0,snapshotDir:u.snapshotDir}}catch(u){throw await cS(f),l||await kl.rm(c,{recursive:!0,force:!0}),u}}async function lS(e){try{return(await bp.stat(e)).isDirectory()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function xo(e){try{return(await bp.stat(e)).isFile()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function uS(e){return await lS(e)?await xo(ve.join(e,"skill.yaml"))?!0:await xo(ve.join(e,"SKILL.md"))&&await xo(ve.join(e,"comet","skill.yaml")):!1}function Cp(e){return{root:e,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.plan"},{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.configure"},{id:"full.build.configure",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{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 kp(){let e=ve.dirname(Sl(import.meta.url)),t=[process.env.COMET_RUNTIME_CLASSIC_ROOT,ve.resolve(e,"..","runtime","classic"),ve.resolve(e,"..","..","comet","runtime","classic"),ve.resolve(e,"..","..","assets","skills","comet","runtime","classic"),ve.resolve("assets","skills","comet","runtime","classic"),process.env.COMET_CLASSIC_SKILL_ROOT,ve.resolve(e,"..","..","comet-classic"),ve.resolve(e,"..","..","assets","skills","comet-classic"),ve.resolve("assets","skills","comet-classic")].filter(n=>!!n);for(let n of t)if(await uS(n))return n;return null}async function Sp(e){return await xo(ve.join(e,"skill.yaml"))?ap(e):op(e)}async function nn(e){let t=await kp();return vp(e,{skillPackage:t?await Sp(t):Cp(ve.dirname(Sl(import.meta.url)))})}async function Ep(e){let t=await W(e),n=Array.from(new Set(t.unknownKeys)).sort();if(n.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${n.join(", ")}`);return nn(e)}async function El(e,t){let n=t??await W(e,{migrate:!1}),i=Array.from(new Set(n.unknownKeys)).sort();if(i.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${i.join(", ")}`);if(!n.classic||!n.run)throw new Error("Classic runtime validation requires synchronized Classic and Run projections");if(n.classic.classicMigration!==Qt)throw new Error("Classic Run exists without a supported classic_migration marker");let r=await kp(),s=r?await Sp(r):Cp(ve.dirname(Sl(import.meta.url)));if(n.run.skill!==s.definition.metadata.name)throw new Error(`Classic Run skill mismatch: expected ${s.definition.metadata.name}, got ${n.run.skill}`);let o=await _o(e,n.run.skillHash);if(o.definition.metadata.name!==n.run.skill)throw new Error(`Classic Run snapshot skill mismatch: expected ${n.run.skill}, got ${o.definition.metadata.name}`);let a=await Ue(e,n),c=bt(n.classic,a);if(n.run.currentStep!==c)throw new Error(`Classic Run step mismatch: expected ${c}, got ${n.run.currentStep}`);return{classic:n.classic,run:n.run,evidence:a,migrated:!1,snapshotDir:ve.join(e,".comet","skill-snapshots",n.run.skillHash)}}async function rn(e,t,n,i){let r=await W(e);if(!r.classic||!r.run)throw new Error("Classic transition requires synchronized Classic and Run projections");let s=await Ue(e,{classic:t,run:n,unknownKeys:r.unknownKeys}),o=bt(t,s),a={...n,currentStep:o,iteration:n.iteration+1,status:o==="completed"?"completed":"running"};await Ne(e,{classic:t,run:a,unknownKeys:r.unknownKeys});let c=await Te(e,a.trajectoryRef);return await De(e,a.trajectoryRef,{sequence:c.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:a.runId,data:{kind:"classic",fromStep:n.currentStep,toStep:o,...i}}),a}fo();import fS from"path";var dS=fS.join(".comet","state-events.jsonl"),mS=8*1024*1024;async function Pn(e,t){let n={schemaVersion:1,timestamp:new Date().toISOString(),...t};return await lo(e,dS,`${JSON.stringify(n)}
|
|
175
|
-
`,
|
|
176
|
-
`,"utf8"),await gr.rename(r,i)}catch(s){throw await gr.rm(r,{force:!0}),s}}async function _l(e){await gr.rm(
|
|
177
|
-
Next: ask the user to confirm — switch back to '${t}', or run \`comet state rebind ${e}\` after explicit confirmation.`}function yr(e,t,n){return`change '${e}' is bound to branch '${t}', but current branch is '${
|
|
169
|
+
`,rt.artifacts,"Run artifacts",i)}async function bo(e,t,n,i={}){Ve(e,t),await Xt(e,t,n,rt.context,"Run context",i)}async function Co(e,t,n={}){return Ve(e,t),Ct(e,t,rt.context,"Run context",n)}async function ko(e,t,n,i={}){Ve(e,t),await Xt(e,t,JSON.stringify(n,null,2)+`
|
|
170
|
+
`,rt.pendingAction,"Run pending action",i)}async function hr(e,t,n={}){Ve(e,t);let i=await Ct(e,t,rt.pendingAction,"Run pending action",n);return i===null?null:JSON.parse(i)}async function So(e,t,n={}){Ve(e,t),await fo(e,t,"Run pending action",n)}async function si(e,t,n,i={}){Ve(e,t),await Xt(e,t,JSON.stringify(n,null,2)+`
|
|
171
|
+
`,rt.checkpoint,"Run checkpoint",i)}async function Qm(e,t,n={}){Ve(e,t);let i=await Ct(e,t,rt.checkpoint,"Run checkpoint",n);return i===null?null:JSON.parse(i)}import{createHash as dp,randomUUID as Zk}from"crypto";import{promises as re}from"fs";import te from"path";var tp=ft(nt(),1);import{promises as vl}from"fs";import Fe from"path";var Lk=["invoke_skill","call_tool","handoff","ask_user","checkpoint"],Mk=["deterministic","adaptive"],qk=["function","mcp","script","agent"],Dk=["none","read","write","external"],Fk=["progress","step","completion"],Bk=["artifact_exists","state_equals"];function xn(e,t,n){return new Error(`${e}: ${t} ${n}`)}function Re(e,t,n="document"){if(e===null||typeof e!="object"||Array.isArray(e))throw xn(t,n,"must be an object")}function en(e,t,n){if(!Array.isArray(e))throw xn(t,n,"must be an array")}function ye(e,t,n){if(typeof e!="string")throw xn(t,n,"must be a string")}function Ye(e,t,n,i){t in e&&ye(e[t],n,`${i}.${t}`)}function np(e,t,n,i){if(t in e&&typeof e[t]!="boolean")throw xn(n,`${i}.${t}`,"must be a boolean")}function tn(e,t,n,i){if(typeof e!="string"||!t.includes(e))throw xn(n,i,`must be one of ${t.join(", ")}`)}function Eo(e,t,n){en(e,t,n),e.forEach((i,r)=>{ye(i,t,`${n}[${r}]`)})}function Zm(e,t,n){Re(e,t,n),ye(e.name,t,`${n}.name`),ye(e.description,t,`${n}.description`),np(e,"required",t,n)}function Wk(e,t,n){Re(e,t,n),ye(e.id,t,`${n}.id`),Ye(e,"source",t,n),Ye(e,"version",t,n)}function Hk(e,t,n){Re(e,t,n),ye(e.id,t,`${n}.id`),ye(e.role,t,`${n}.role`),Ye(e,"instructions",t,n)}function Kk(e,t,n){Re(e,t,n),ye(e.id,t,`${n}.id`),tn(e.kind,qk,t,`${n}.kind`),ye(e.source,t,`${n}.source`),tn(e.sideEffect,Dk,t,`${n}.sideEffect`),np(e,"requiresConfirmation",t,n)}function Jk(e,t,n){Re(e,t,n),tn(e.type,Lk,t,`${n}.type`),Ye(e,"ref",t,n),Ye(e,"prompt",t,n),Ye(e,"question",t,n),"options"in e&&Eo(e.options,t,`${n}.options`)}function Uk(e,t,n){Re(e,t,n),ye(e.id,t,`${n}.id`),Jk(e.action,t,`${n}.action`),Ye(e,"next",t,n),"completionEvals"in e&&Eo(e.completionEvals,t,`${n}.completionEvals`)}function Vk(e,t){let n="goal";Re(e,t,n),ye(e.statement,t,`${n}.statement`),en(e.inputs,t,`${n}.inputs`),e.inputs.forEach((i,r)=>{Zm(i,t,`${n}.inputs[${r}]`)}),en(e.outputs,t,`${n}.outputs`),e.outputs.forEach((i,r)=>{Zm(i,t,`${n}.outputs[${r}]`)}),Eo(e.success,t,`${n}.success`)}function Yk(e,t){let n="orchestration";Re(e,t,n),tn(e.mode,Mk,t,`${n}.mode`),Ye(e,"entry",t,n),"steps"in e&&(en(e.steps,t,`${n}.steps`),e.steps.forEach((i,r)=>{Uk(i,t,`${n}.steps[${r}]`)}))}function ip(e,t){return Re(e,t),tn(e.apiVersion,["comet/v1alpha1"],t,"apiVersion"),tn(e.kind,["Skill"],t,"kind"),Re(e.metadata,t,"metadata"),ye(e.metadata.name,t,"metadata.name"),ye(e.metadata.version,t,"metadata.version"),ye(e.metadata.description,t,"metadata.description"),Vk(e.goal,t),Yk(e.orchestration,t),en(e.skills,t,"skills"),e.skills.forEach((n,i)=>{Wk(n,t,`skills[${i}]`)}),en(e.agents,t,"agents"),e.agents.forEach((n,i)=>{Hk(n,t,`agents[${i}]`)}),en(e.tools,t,"tools"),e.tools.forEach((n,i)=>{Kk(n,t,`tools[${i}]`)}),e}function rp(e,t){Re(e,t);for(let n of["allowedSkills","allowedAgents","allowedTools","confirmationRequiredFor"])n in e&&Eo(e[n],t,n);for(let n of["maxIterations","maxRetriesPerAction"])if(n in e&&(typeof e[n]!="number"||!Number.isFinite(e[n])))throw xn(t,n,"must be a finite number");return e}function Gk(e,t){return Re(e,t),"runtime"in e&&sp(e.runtime,t,"runtime"),e}function sp(e,t,n){return en(e,t,n),e.forEach((i,r)=>{let s=`${n}[${r}]`;Re(i,t,s),ye(i.id,t,`${s}.id`),tn(i.scope,Fk,t,`${s}.scope`),tn(i.type,Bk,t,`${s}.type`),Ye(i,"artifact",t,s),Ye(i,"field",t,s),Ye(i,"equals",t,s)}),e}async function bl(e){let t=await vl.readFile(e,"utf8");try{return(0,tp.parse)(t)}catch(n){let i=n instanceof Error?n.message:String(n);throw xn(e,"document",i)}}async function zk(e){try{return await bl(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}async function ep(e){try{return await vl.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Xk(e){let t=Fe.join(e,"checks.yaml"),n=Fe.join(e,"evals.yaml"),[i,r]=await Promise.all([ep(t),ep(n)]);if(r)throw new Error(`${n}: evals.yaml is no longer supported; use checks.yaml`);return i?{document:Gk(await bl(t),t)}:{document:null}}async function op(e){let t=Fe.resolve(e.root),n=Fe.resolve(e.controlRoot);e.requireSkillMarkdown&&await vl.access(Fe.join(t,"SKILL.md"));let i=Fe.join(n,"skill.yaml"),r=Fe.join(n,"guardrails.yaml"),s=ip(await bl(i),i),o=await zk(r),a=o===null?null:rp(o,r),c=await Xk(n),l={allowedSkills:s.skills.map(f=>f.id),allowedAgents:s.agents.map(f=>f.id),allowedTools:s.tools.map(f=>f.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:s.tools.filter(f=>f.requiresConfirmation).map(f=>f.id)};return{root:t,packageKind:e.packageKind==="runtime"?"runtime":void 0,definition:s,guardrails:{...l,...a},evals:c.document?.runtime??[]}}async function ap(e){let t=Fe.resolve(e);return op({root:t,controlRoot:Fe.join(t,"comet"),packageKind:"skill",requireSkillMarkdown:!0})}async function cp(e){let t=Fe.resolve(e);return op({root:t,controlRoot:t,packageKind:"runtime",requireSkillMarkdown:!1})}function lp(e,t,n=Fe.join(t,"package.json")){Re(e,n);let i=e.packageKind==="runtime"?"runtime":void 0,r=ip(e.definition,n),s=rp(e.guardrails,n),o=sp(e.evals,n,"evals"),a={allowedSkills:r.skills.map(c=>c.id),allowedAgents:r.agents.map(c=>c.id),allowedTools:r.tools.map(c=>c.id),maxIterations:50,maxRetriesPerAction:3,confirmationRequiredFor:r.tools.filter(c=>c.requiresConfirmation).map(c=>c.id)};return{root:Fe.resolve(t),packageKind:i,definition:r,guardrails:{...a,...s},evals:o}}import up from"path";function Qk(e,t,n,i){e.type==="invoke_skill"&&!t.definition.skills.some(r=>r.id===e.ref)&&n.push(`step ${i} references undeclared skill: ${e.ref??"(missing)"}`),e.type==="call_tool"&&!t.definition.tools.some(r=>r.id===e.ref)&&n.push(`step ${i} references undeclared tool: ${e.ref??"(missing)"}`),e.type==="handoff"&&!t.definition.agents.some(r=>r.id===e.ref)&&n.push(`step ${i} references undeclared agent: ${e.ref??"(missing)"}`),e.type==="ask_user"&&!e.question&&n.push(`step ${i} ask_user action requires question`)}function fp(e){let t=[],{definition:n,guardrails:i,evals:r}=e;n.apiVersion!=="comet/v1alpha1"&&t.push("unsupported apiVersion"),n.kind!=="Skill"&&t.push("kind must be Skill"),n.metadata.name||t.push("metadata.name is required"),n.goal.statement||t.push("goal.statement is required"),i.maxIterations<1&&t.push("maxIterations must be at least 1"),i.maxRetriesPerAction<0&&t.push("maxRetriesPerAction must not be negative");let s=n.orchestration.steps??[];if(n.orchestration.mode==="adaptive")(n.orchestration.entry||s.length>0)&&t.push("adaptive orchestration must not define entry or steps");else{let o=new Set;for(let a of s)o.has(a.id)&&t.push(`duplicate step id: ${a.id}`),o.add(a.id),Qk(a.action,e,t,a.id);(!n.orchestration.entry||!o.has(n.orchestration.entry))&&t.push(`orchestration.entry references unknown step: ${n.orchestration.entry??"(missing)"}`);for(let a of s){a.next&&!o.has(a.next)&&t.push(`step ${a.id} has unknown next step: ${a.next}`);for(let c of a.completionEvals??[])r.some(l=>l.id===c)||t.push(`step ${a.id} references unknown eval: ${c}`)}}for(let o of n.tools){if(o.kind!=="script")continue;let a=up.posix.normalize(o.source.replaceAll("\\","/"));(up.isAbsolute(o.source)||a===".."||a.startsWith("../"))&&t.push(`script tool ${o.id} must reference a relative path inside the Skill package`)}for(let o of i.allowedSkills)n.skills.some(a=>a.id===o)||t.push(`guardrails allow undeclared skill: ${o}`);for(let o of i.allowedAgents)n.agents.some(a=>a.id===o)||t.push(`guardrails allow undeclared agent: ${o}`);for(let o of i.allowedTools)n.tools.some(a=>a.id===o)||t.push(`guardrails allow undeclared tool: ${o}`);return t}function Ro(e){return Array.isArray(e)?e.map(Ro):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,Ro(n)])):e}function eS(e){return Ro({...e.packageKind==="runtime"?{packageKind:"runtime"}:{},definition:e.definition,guardrails:e.guardrails,evals:e.evals})}function tS(e){return te.posix.normalize(e.replaceAll("\\","/"))}function oi(e,t,n){let i=te.relative(e,t);if(!(i===""||!te.isAbsolute(i)&&!i.startsWith(`..${te.sep}`)))throw new Error(`${n} resolves outside the Skill package`)}async function mp(e,t,n){let i=tS(t);if(te.posix.isAbsolute(i)||i===".."||i.startsWith("../"))throw new Error(`${n} resolves outside the Skill package`);let r=te.resolve(e,...i.split("/"));oi(e,r,n);let s;try{s=await re.realpath(r)}catch(o){throw o.code==="ENOENT"?new Error(`${n} does not exist: ${t}`,{cause:o}):o}if(oi(e,s,n),!(await re.stat(s)).isFile())throw new Error(`${n} is not a file: ${t}`);return{path:i,content:await re.readFile(s)}}async function nS(e){let t=await re.realpath(e.root),n=e.packageKind==="runtime"?[]:[await mp(t,"SKILL.md","SKILL.md")];for(let i of e.definition.tools)i.kind==="script"&&n.push(await mp(t,i.source,`Script tool ${i.id}`));return n.sort((i,r)=>i.path.localeCompare(r.path))}function iS(e,t){let n=t.map(i=>({path:i.path,sha256:dp("sha256").update(i.content).digest("hex")}));return dp("sha256").update(JSON.stringify(Ro({package:e,files:n}))).digest("hex")}function gp(e){return JSON.stringify(e,null,2)+`
|
|
172
|
+
`}async function wp(e){let t=eS(e),n=await nS(e);return{document:t,files:n,hash:iS(t,n)}}async function _o(e){return(await wp(e)).hash}async function pp(e){try{return await re.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function hp(e,t){try{if((await re.readFile(te.join(e,"sha256"),"utf8")).trim()!==t.hash)throw new Error("hash mismatch");if(await re.readFile(te.join(e,"package.json"),"utf8")!==gp(t.document))throw new Error("package mismatch");for(let r of t.files)if(!(await re.readFile(te.join(e,...r.path.split("/")))).equals(r.content))throw new Error(`file mismatch: ${r.path}`)}catch(n){throw new Error(`Existing Skill snapshot is invalid: ${t.hash}`,{cause:n})}}async function Cl(e,t){let n=await wp(e),i=te.resolve(t,".comet","skill-snapshots"),r=te.join(i,n.hash);if(await re.mkdir(i,{recursive:!0}),await pp(r))return await hp(r,n),{hash:n.hash,snapshotDir:r};let s=te.join(i,`.tmp-${Zk()}`);oi(i,s,"Temporary snapshot"),oi(i,r,"Published snapshot");try{await re.mkdir(s);for(let o of n.files){let a=te.join(s,...o.path.split("/"));oi(s,a,`Snapshot file ${o.path}`),await re.mkdir(te.dirname(a),{recursive:!0}),await re.writeFile(a,o.content)}await re.writeFile(te.join(s,"package.json"),gp(n.document)),await re.writeFile(te.join(s,"sha256"),n.hash+`
|
|
173
|
+
`),await re.rename(s,r)}catch(o){if(await pp(r)){try{await hp(r,n)}finally{await re.rm(s,{recursive:!0,force:!0})}return{hash:n.hash,snapshotDir:r}}throw await re.rm(s,{recursive:!0,force:!0}),o}return{hash:n.hash,snapshotDir:r}}async function xo(e,t){if(!/^[a-f0-9]{64}$/u.test(t))throw new Error(`Invalid Skill snapshot hash: ${t}`);let n=te.resolve(e,".comet","skill-snapshots"),i=te.join(n,t);oi(n,i,"Skill snapshot");try{let r=(await re.readFile(te.join(i,"sha256"),"utf8")).trim();if(r!==t)throw new Error(`stored hash is ${r||"(empty)"}`);let s=te.join(i,"package.json"),o=JSON.parse(await re.readFile(s,"utf8")),a=lp(o,i,s),c=fp(a);if(c.length>0)throw new Error(c.map(f=>` - ${f}`).join(`
|
|
174
|
+
`));let l=await _o(a);if(l!==t)throw new Error(`calculated hash is ${l}`);return a}catch(r){throw new Error(`Skill snapshot is invalid or missing: ${t}`,{cause:r})}}async function yp(e){try{return await kl.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function vp(e){return rS("sha256").update(e).digest("hex")}function oS(e){return vp(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))))}function aS(e){return e.replaceAll(".","_").replaceAll("-","_")}async function cS(e,t){let n=await ue(e),i=Object.fromEntries(t.filter(o=>o.satisfied&&o.source).map(o=>[aS(o.code),o.source])),r=kt.join(e,"subagent-progress.md");await yp(r)&&(i.subagent_progress=kt.relative(n,r).split(kt.sep).join("/"));let s=t.find(o=>o.code==="design.handoff"&&o.satisfied);return s?.source&&(i.handoff_context=s.source),i}function lS(e,t,n){return[{sequence:1,timestamp:n,type:"run_started",runId:e.runId,data:{skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash}},{sequence:2,timestamp:n,type:"state_migrated",runId:e.runId,data:{kind:"classic",migrationVersion:Qt,profile:t,source:"pre-migration"}}]}async function uS(e){await Promise.all(e.map(t=>kl.rm(t,{recursive:!0,force:!0})))}async function bp(e,t){let n=await W(e);if(!n.classic)throw new Error("Classic migration requires a legacy state projection");let i=n.classic,r=i.classicProfile??i.workflow;if(n.run){if(i.classicMigration!==Qt)throw new Error("Classic Run exists without a supported classic_migration marker");if(n.run.skill!==t.skillPackage.definition.metadata.name)throw new Error(`Classic Run skill mismatch: expected ${t.skillPackage.definition.metadata.name}, got ${n.run.skill}`);if(await _o(t.skillPackage)!==n.run.skillHash)return await xo(e,n.run.skillHash),{classic:i,run:n.run,evidence:await Ue(e,n),migrated:!1,snapshotDir:kt.join(e,".comet","skill-snapshots",n.run.skillHash)};let d=await Cl(t.skillPackage,e);return{classic:i,run:n.run,evidence:await Ue(e,n),migrated:!1,snapshotDir:d.snapshotDir}}let s=await Ue(e,n),o=bt(i,s);if(!t.skillPackage.definition.orchestration.steps?.some(u=>u.id===o))throw new Error(`Classic Skill package does not define resolved step: ${o}`);let a=await _o(t.skillPackage),c=kt.join(e,".comet","skill-snapshots",a),l=await yp(c),f=[];try{let u=await Cl(t.skillPackage,e),d=Xm(t.skillPackage,t.runId?.()??sS(),u.hash);d.currentStep=o,o==="completed"&&(d.status="completed");let h={...i,classicProfile:r,classicMigration:Qt},g=await cS(e,s),p=await ue(e),m=s.find(k=>k.code==="design.handoff"&&k.satisfied),w=null;m?.source&&(w=await B(p,m.resolvedSource??m.source,{label:"Classic migration handoff context",hooks:t.handoffReadHooks}),await bo(e,d.contextRef,w),f.push(kt.resolve(e,d.contextRef))),await ri(e,d.artifactsRef,g),f.push(kt.resolve(e,d.artifactsRef));let y=(t.now?.()??new Date).toISOString(),C={runId:d.runId,stateVersion:1,trajectoryOffset:2,contextHash:w===null?null:vp(w),artifactsHash:oS(g),createdAt:y};await si(e,d.checkpointRef,C),f.push(kt.resolve(e,d.checkpointRef)),f.push(kt.resolve(e,d.trajectoryRef));for(let k of lS(d,r,y))await De(e,d.trajectoryRef,k);return await Ne(e,{classic:h,run:d,unknownKeys:n.unknownKeys}),{classic:h,run:d,evidence:s,migrated:!0,snapshotDir:u.snapshotDir}}catch(u){throw await uS(f),l||await kl.rm(c,{recursive:!0,force:!0}),u}}async function fS(e){try{return(await Cp.stat(e)).isDirectory()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Po(e){try{return(await Cp.stat(e)).isFile()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function dS(e){return await fS(e)?await Po(ve.join(e,"skill.yaml"))?!0:await Po(ve.join(e,"SKILL.md"))&&await Po(ve.join(e,"comet","skill.yaml")):!1}function kp(e){return{root:e,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.plan"},{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.configure"},{id:"full.build.configure",action:{type:"invoke_skill",ref:"comet-build"},next:"full.build.execute"},{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 Sp(){let e=ve.dirname(Sl(import.meta.url)),t=[process.env.COMET_RUNTIME_CLASSIC_ROOT,ve.resolve(e,"..","runtime","classic"),ve.resolve(e,"..","..","comet","runtime","classic"),ve.resolve(e,"..","..","assets","skills","comet","runtime","classic"),ve.resolve("assets","skills","comet","runtime","classic"),process.env.COMET_CLASSIC_SKILL_ROOT,ve.resolve(e,"..","..","comet-classic"),ve.resolve(e,"..","..","assets","skills","comet-classic"),ve.resolve("assets","skills","comet-classic")].filter(n=>!!n);for(let n of t)if(await dS(n))return n;return null}async function Ep(e){return await Po(ve.join(e,"skill.yaml"))?cp(e):ap(e)}async function nn(e){let t=await Sp();return bp(e,{skillPackage:t?await Ep(t):kp(ve.dirname(Sl(import.meta.url)))})}async function Rp(e){let t=await W(e),n=Array.from(new Set(t.unknownKeys)).sort();if(n.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${n.join(", ")}`);return nn(e)}async function El(e,t){let n=t??await W(e,{migrate:!1}),i=Array.from(new Set(n.unknownKeys)).sort();if(i.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${i.join(", ")}`);if(!n.classic||!n.run)throw new Error("Classic runtime validation requires synchronized Classic and Run projections");if(n.classic.classicMigration!==Qt)throw new Error("Classic Run exists without a supported classic_migration marker");let r=await Sp(),s=r?await Ep(r):kp(ve.dirname(Sl(import.meta.url)));if(n.run.skill!==s.definition.metadata.name)throw new Error(`Classic Run skill mismatch: expected ${s.definition.metadata.name}, got ${n.run.skill}`);let o=await xo(e,n.run.skillHash);if(o.definition.metadata.name!==n.run.skill)throw new Error(`Classic Run snapshot skill mismatch: expected ${n.run.skill}, got ${o.definition.metadata.name}`);let a=await Ue(e,n),c=bt(n.classic,a);if(n.run.currentStep!==c)throw new Error(`Classic Run step mismatch: expected ${c}, got ${n.run.currentStep}`);return{classic:n.classic,run:n.run,evidence:a,migrated:!1,snapshotDir:ve.join(e,".comet","skill-snapshots",n.run.skillHash)}}async function rn(e,t,n,i){let r=await W(e);if(!r.classic||!r.run)throw new Error("Classic transition requires synchronized Classic and Run projections");let s=await Ue(e,{classic:t,run:n,unknownKeys:r.unknownKeys}),o=bt(t,s),a={...n,currentStep:o,iteration:n.iteration+1,status:o==="completed"?"completed":"running"};await Ne(e,{classic:t,run:a,unknownKeys:r.unknownKeys});let c=await Te(e,a.trajectoryRef);return await De(e,a.trajectoryRef,{sequence:c.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:a.runId,data:{kind:"classic",fromStep:n.currentStep,toStep:o,...i}}),a}mo();import mS from"path";var pS=mS.join(".comet","state-events.jsonl"),hS=8*1024*1024;async function Pn(e,t){let n={schemaVersion:1,timestamp:new Date().toISOString(),...t};return await uo(e,pS,`${JSON.stringify(n)}
|
|
175
|
+
`,hS,"Classic state event log"),n}var _p=["open-complete","design-complete","build-complete","verify-pass","verify-fail","archive-confirm","archive-reopen","archived","preset-escalate"],gS={"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"]}},xp={open:"open-complete",design:"design-complete",build:"build-complete",verify:"verify-pass"};function wS(e){return e.toISOString().slice(0,10)}function j(e,t,n,i){let r=e[n];e[n]=i,r!==i&&t.push({field:n,from:r,to:i})}function ai(e,t,n={}){let i=gS[t];if(e.phase!==i.from)throw new Error(`Cannot apply ${t}: phase is '${e.phase}', expected '${i.from}'`);let r={...e},s=[],o=n.now??new Date;if(t==="open-complete")j(r,s,"phase",r.workflow==="full"?"design":"build");else if(t==="design-complete")j(r,s,"phase","build");else if(t==="build-complete"){let a=r.verifyResult==="fail";j(r,s,"phase","verify"),j(r,s,"verifyResult","pending"),j(r,s,"branchStatus","pending"),a||j(r,s,"verificationReport",null)}else if(t==="verify-pass")j(r,s,"verifyResult","pass"),j(r,s,"verifyFailures",0),j(r,s,"phase","archive"),j(r,s,"verifiedAt",wS(o)),j(r,s,"archiveConfirmation","pending"),j(r,s,"branchStatus","pending");else if(t==="verify-fail")j(r,s,"verifyResult","fail"),j(r,s,"verifyFailures",r.verifyFailures+1),j(r,s,"phase","build"),j(r,s,"branchStatus","pending");else if(t==="preset-escalate"){if(r.workflow!=="hotfix"&&r.workflow!=="tweak")throw new Error(`Cannot apply ${t}: workflow must be hotfix or tweak, got '${r.workflow}'`);j(r,s,"workflow","full"),j(r,s,"classicProfile","full"),j(r,s,"phase","design"),j(r,s,"designDoc",null),j(r,s,"buildPause",null),j(r,s,"buildMode",null),j(r,s,"subagentDispatch",null),j(r,s,"tddMode",null),j(r,s,"reviewMode",null),j(r,s,"isolation",null),j(r,s,"boundBranch",null),j(r,s,"verifyMode",null),j(r,s,"directOverride",null)}else if(t==="archive-confirm"){if(r.verifyResult!=="pass")throw new Error(`Cannot apply ${t}: verifyResult must be pass`);if(r.archived)throw new Error(`Cannot apply ${t}: already archived`);j(r,s,"archiveConfirmation","confirmed")}else if(t==="archive-reopen"){if(r.archived)throw new Error(`Cannot apply ${t}: already archived`);j(r,s,"verifyResult","pending"),j(r,s,"verifyFailures",0),j(r,s,"phase","verify"),j(r,s,"verifiedAt",null),j(r,s,"archiveConfirmation",null),j(r,s,"branchStatus","pending")}else{if(r.verifyResult!=="pass")throw new Error(`Cannot apply ${t}: verifyResult must be pass`);if(r.archiveConfirmation!=="confirmed")throw new Error(`Cannot apply ${t}: archiveConfirmation must be confirmed`);j(r,s,"archived",!0)}return{classic:r,effects:s,definition:i}}Gc();import{randomUUID as yS}from"crypto";import{promises as gr}from"fs";import Op from"path";var Rl="comet.selection.v2",vS=16*1024;function Oo(e){return Op.join(e,".comet","current-change.json")}function bS(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Pp(e){return e===null||typeof e=="string"}function $p(e){let t;try{t=JSON.parse(e)}catch(n){throw new Error(`current change selection contains invalid JSON: ${n instanceof Error?n.message:String(n)}`,{cause:n})}if(!bS(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!Pp(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Rl,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Rl)throw new Error(`current change selection schema must be ${Rl}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Pp(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function $o(e){let t;try{let i=Oo(e),{bytes:r}=await Us(i,vS,{label:"current change selection"});t=r.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...$p(t)}}async function Ip(e,t){let n=$p(JSON.stringify(t));if(n.legacy)throw new Error("cannot write a legacy current change selection");let i=Oo(e),r=`${i}.${yS()}.tmp`;await gr.mkdir(Op.dirname(i),{recursive:!0});try{await gr.writeFile(r,`${JSON.stringify(n.selection,null,2)}
|
|
176
|
+
`,"utf8"),await gr.rename(r,i)}catch(s){throw await gr.rm(r,{force:!0}),s}}async function _l(e){await gr.rm(Oo(e),{force:!0})}async function Ap(e,t,n){let i=await $o(e);return i.status!=="selected"||i.selection.workflow!==t||i.selection.change!==n?!1:(await _l(e),!0)}var Np=null;function Tp(e,t){let n=e;for(let i of t)n+="\0"+(typeof i=="string"?i:JSON.stringify(i));return n}function Io(e,t){return(...n)=>{let i=Np;if(i===null)return t(...n);let r=Tp(`async:${e}`,n),s=i.entries.get(r);if(s)return s.value;let o=t(...n).catch(a=>{throw i.entries.delete(r),a});return i.entries.set(r,{value:o}),o}}function xl(e,t){return(...n)=>{let i=Np;if(i===null)return t(...n);let r=Tp(`sync:${e}`,n),s=i.entries.get(r);if(s)return s.value;let o=t(...n);return i.entries.set(r,{value:o}),o}}var Pl=ft(nt(),1);import{execFileSync as jp}from"child_process";import{randomUUID as CS}from"crypto";import{promises as wr}from"fs";import Lp from"path";function Ao(e){try{let t=jp("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return t&&t!=="HEAD"?t:null}catch{return null}}var kS=xl("liveGitBranch",e=>Ao(e));function Ol(e){try{return jp("git",["rev-parse","--is-inside-work-tree"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()==="true"}catch{return!1}}var SS=xl("isGitWorkTree",e=>Ol(e)),ES=["current","branch","worktree"];function No(e){return ES.includes(e)}function $l(e){return No(e.isolation)?e.boundBranch===null&&e.currentBranch===null&&e.gitWorkTree===!1?{status:"not-applicable"}:e.boundBranch===null?e.currentBranch===null?{status:"unbound-detached"}:{status:"needs-heal",branch:e.currentBranch}:e.currentBranch===e.boundBranch?{status:"ok"}:{status:"drift",boundBranch:e.boundBranch,currentBranch:e.currentBranch}:{status:"not-applicable"}}async function St(e,t){let n=Lp.join(e,".comet.yaml"),i=(0,Pl.parseDocument)(await wr.readFile(n,"utf8"),{uniqueKeys:!1});if(i.errors.length>0)throw new Error(`Invalid .comet.yaml: ${i.errors[0].message}`);let r=i.toJS()??{},s=typeof r.isolation=="string"?r.isolation:null,o=typeof r.bound_branch=="string"&&r.bound_branch!==""?r.bound_branch:null,a=No(s),c=kS(t.cwd),l=a&&o===null&&c===null?SS(t.cwd):!0,f=$l({isolation:s,boundBranch:o,currentBranch:c,gitWorkTree:l});return f.status==="needs-heal"&&t.heal?(await Il(e,f.branch),{status:"healed",branch:f.branch,bindingRequired:a,currentBranch:c}):{...f,bindingRequired:a,currentBranch:c}}async function Il(e,t){let n=Lp.join(e,".comet.yaml"),i=(0,Pl.parseDocument)(await wr.readFile(n,"utf8"),{uniqueKeys:!1});i.set("bound_branch",t);let r=`${n}.${CS()}.tmp`;try{await wr.writeFile(r,i.toString(),"utf8"),await wr.rename(r,n)}catch(s){throw await wr.rm(r,{force:!0}),s}}function Mp(e){return e??"detached HEAD"}function To(e,t,n){return`change '${e}' is bound to branch '${t}', but current branch is '${Mp(n)}'.
|
|
177
|
+
Next: ask the user to confirm — switch back to '${t}', or run \`comet state rebind ${e}\` after explicit confirmation.`}function yr(e,t,n){return`change '${e}' is bound to branch '${t}', but current branch is '${Mp(n)}'`}function Et(e){return`change '${e}' uses a branch-bound workspace mode but has no bound branch and HEAD is detached; checkout a branch first before continuing.`}var RS=Io("readCometCurrentSelection",e=>$o(e));async function qp(e,t){zt(t);let n=await Je(t,e);if(!n.stateExists)throw new Error(`Cannot select current change '${t}': active change state not found`);let i=await W(n.directory,{migrate:!1});if(!i.classic)throw new Error(`Cannot select current change '${t}': Classic state is incomplete`);if(i.classic.archived)throw new Error(`Cannot select current change '${t}': change is archived`);return n.directory}async function Dp(e,t){let n=await qp(e,t),i=await St(n,{heal:!0,cwd:e});if(i.status==="drift")throw new Error(yr(t,i.boundBranch,i.currentBranch));if(i.status==="unbound-detached")throw new Error(Et(t));let r={schema:"comet.selection.v2",workflow:"classic",change:t,branch:i.currentBranch};return await Ip(e,r),r}async function jo(e){let t;try{t=await RS(e)}catch(s){return{status:"stale",reason:s instanceof Error?s.message:String(s)}}if(t.status==="missing")return{status:"missing"};if(t.selection.workflow!=="classic")return{status:"stale",reason:`current change '${t.selection.change}' belongs to Native, not Classic`};let n=t.selection,i;try{i=await qp(e,n.change)}catch(s){return{status:"stale",reason:s instanceof Error?s.message:String(s)}}let r=await St(i,{heal:!1,cwd:e});return r.status==="drift"?{status:"stale",reason:yr(n.change,r.boundBranch,r.currentBranch)}:r.status==="unbound-detached"?{status:"stale",reason:Et(n.change)}:r.status==="ok"?{status:"selected",selection:n}:n.branch!==null&&r.currentBranch!==n.branch?{status:"stale",reason:`current change '${n.change}' was selected on branch '${n.branch}', current branch is '${r.currentBranch??"detached HEAD"}'`}:{status:"selected",selection:n}}async function Fp(e){let t;try{t=await $o(e)}catch{return}t.status==="selected"&&t.selection.workflow==="classic"&&await _l(e)}async function Bp(e,t){return Ap(e,"classic",t)}var PS="\x1B[32m",OS="\x1B[31m",$S="\x1B[33m",Nl="\x1B[0m";function Be(e){return`${PS}${e}${Nl}`}function _e(e){return`${OS}${e}${Nl}`}function vr(e){return`${$S}${e}${Nl}`}var fe=class extends Error{constructor(n,i=1){super(n);this.exitCode=i}exitCode},Al=class{stderr=[];openSpecStdout=[];openSpecStderr=[];stepsOk=0;stepsTotal=0;captureOpenSpec(t){t.stdout&&this.openSpecStdout.push(t.stdout),t.stderr&&this.openSpecStderr.push(t.stderr)}toResult(t=0){let n=this.stderr.length>0?this.stderr.join(`
|
|
178
178
|
`)+`
|
|
179
179
|
`:"",i=this.openSpecStderr.join(""),r=i&&n&&!i.endsWith(`
|
|
180
180
|
`)?`
|
|
181
|
-
`:"";return{exitCode:t,...this.openSpecStdout.length>0?{stdout:this.openSpecStdout.join("")}:{},...i||n?{stderr:`${i}${r}${n}`}:{}}}};function
|
|
182
|
-
`}function
|
|
181
|
+
`:"";return{exitCode:t,...this.openSpecStdout.length>0?{stdout:this.openSpecStdout.join("")}:{},...i||n?{stderr:`${i}${r}${n}`}:{}}}};function IS(e){let t=ge(e);if(t)throw new fe(_e(`FATAL: ${t}`))}function Hp(e){return _S("sha256").update(e).digest("hex")}function AS(e){return Hp(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))))}function NS(e,t){let n=st.relative(e,t);return n!==""&&!st.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${st.sep}`)}function br(e,t,n,i){if(!i)return i;let r=st.resolve(e,i);return NS(t,r)?N(e,st.join(n,st.relative(t,r))):i}function TS(e,t,n,i){let r={...i};for(let s of["handoff_context","handoff_markdown"]){let o=r[s];o&&(r[s]=br(e,t,n,o)??o)}return r}async function jS(e,t){let n=await W(t);if(!n.classic||!n.run||!n.classic.archived)throw new fe(_e(" [FAIL] Final archived state is incomplete"));let i=[["design_doc",n.classic.designDoc],["plan",n.classic.plan],["verification_report",n.classic.verificationReport],["handoff_context",n.classic.handoffContext]],r=await ii(t,n.run.artifactsRef),s=[["artifacts.handoff_context",r.handoff_context],["artifacts.handoff_markdown",r.handoff_markdown]];for(let[o,a]of[...i,...s])if(a&&!await ee(e,st.resolve(e,a),{label:`Classic archived ${o}`,expected:"file"}))throw new fe(_e(` [FAIL] Final archived ${o} does not exist: ${a}`))}function Wp(e){return`${e.replace(/\n+$/u,"")}
|
|
182
|
+
`}function LS(e,t,n){let i=e.replace(/\r\n/gu,`
|
|
183
183
|
`),r=i.split(`
|
|
184
|
-
`),s=r[0]==="---"?r.indexOf("---",1):-1,o=n.match(/^([^:\n]+):/u)?.[1]?.trim();if(s!==-1){let c=r.slice(1,s).filter(l=>{let f=l.match(/^([^:\n]+):/u)?.[1]?.trim();return f===void 0?!0:f!=="archived-with"&&f!==o});return c.push(`archived-with: ${t}`),n&&c.push(n),
|
|
185
|
-
`))}let a=["---",`archived-with: ${t}`];return n&&a.push(n),o!=="status"&&a.push("status: final"),a.push("---"),
|
|
186
|
-
`))}async function
|
|
184
|
+
`),s=r[0]==="---"?r.indexOf("---",1):-1,o=n.match(/^([^:\n]+):/u)?.[1]?.trim();if(s!==-1){let c=r.slice(1,s).filter(l=>{let f=l.match(/^([^:\n]+):/u)?.[1]?.trim();return f===void 0?!0:f!=="archived-with"&&f!==o});return c.push(`archived-with: ${t}`),n&&c.push(n),Wp(["---",...c,"---",...r.slice(s+1)].join(`
|
|
185
|
+
`))}let a=["---",`archived-with: ${t}`];return n&&a.push(n),o!=="status"&&a.push("status: final"),a.push("---"),Wp([...a,i].join(`
|
|
186
|
+
`))}async function MS(e,t,n){let i=await Te(e,t.trajectoryRef);i.some(r=>r.type==="recovery_reconciled"&&r.data.kind==="classic-archive"&&r.data.actionId===n)||await De(e,t.trajectoryRef,{sequence:i.length+1,timestamp:new Date().toISOString(),type:"recovery_reconciled",runId:t.runId,data:{kind:"classic-archive",actionId:n}})}async function Lo(e,t,n,i,r,s){if(!await ee(t,n,{label:"Classic archive annotation target",expected:"file"}))return;if(s){e.stderr.push(vr(` [DRY-RUN] Would annotate: ${n}`)),e.stepsOk+=1,e.stepsTotal+=1;return}let o=await B(t,n,{label:"Classic archive annotation target"}),a=LS(o,i,r);await Qn(t,n,a,{label:"Classic archive annotation target"}),e.stderr.push(Be(` [OK] Annotated: ${n}`)),e.stepsOk+=1,e.stepsTotal+=1}async function qS(e,t){if(!(await V(e,t,{label:"Classic main specs directory",expected:"directory"})).exists)return;let i=!1,r=await xS.readdir(t,{withFileTypes:!0});for(let s of r){if(!s.isDirectory()&&!s.isSymbolicLink())continue;let o=`${t}/${s.name}/spec.md`,a=await(async()=>await ee(e,o,{label:`Classic main spec ${s.name}`,expected:"file"})?B(e,o,{label:`Classic main spec ${s.name}`}):null)();if(a===null)continue;let c=a.split(/\r?\n/u).map((l,f)=>({line:l,number:f+1})).filter(l=>/^## (ADDED|MODIFIED|REMOVED|RENAMED) Requirements$/u.test(l.line));if(c.length>0){i=!0,process.stderr.write(_e(`FATAL: delta-only section heading leaked into main spec: ${o}`)+`
|
|
187
187
|
`);for(let l of c)process.stderr.write(`${l.number}:${l.line}
|
|
188
|
-
`)}}if(i)throw new fe("")}var
|
|
189
|
-
`))t.stderr.push(s);return t.toResult(r.exitCode)}throw r}};var
|
|
188
|
+
`)}}if(i)throw new fe("")}var Kp=async e=>{let t=new Al,n=e[0],i=e[1]==="--dry-run";try{IS(n);let r=await ue(process.cwd()),s=await Ee(r),o=await Je(n,s.projectRoot),a=o.directory,c=N(s.projectRoot,a),f=`${new Date().toISOString().slice(0,10)}-${n}`,u=st.join(s.archiveDir,f);t.stderr.push(`=== Comet Archive: ${n} ===`);let d=o.stateExists,h=d?null:await ao(n,s.projectRoot),g=d?a:h?.directory;if(!g||!await ee(s.projectRoot,`${g}/.comet.yaml`,{label:`Classic change ${n} state`,expected:"file"}))throw new fe(_e(`FATAL: .comet.yaml not found in ${c}/`));h&&(u=h.directory,f=st.basename(h.directory));let p=await W(g);if(!p.classic)throw new fe(_e("FATAL: archive requires Classic state"));let m=p.classic,w=m.designDoc,y=m.plan;if(m.phase!=="archive")throw new fe(_e(`FATAL: phase is '${m.phase}', expected 'archive'`));if(m.verifyResult!=="pass")throw new fe(_e(`FATAL: verify_result is '${m.verifyResult}', expected 'pass'. Run comet-verify first.`));t.stderr.push(Be(" [OK] Entry state verified")),t.stepsOk+=1,t.stepsTotal+=1;let C=await V(s.projectRoot,u,{label:`Classic archive target ${f}`,expected:"directory"});if(d&&C.exists)throw new fe(_e(`FATAL: archive target already exists: ${u}`));if(t.stderr.push(Be(" [OK] Archive target available")),t.stepsOk+=1,t.stepsTotal+=1,i)t.stderr.push(vr(` [DRY-RUN] Would run OpenSpec archive: ${n}`)),t.stepsOk+=1,t.stepsTotal+=1;else if(!m.archived||p.run?.pending){await En(s.projectRoot,`${g}/.comet`,"Classic change runtime directory");let k=await nn(g),E=`classic-archive:${n}`,R=await hr(g,k.run.pendingRef),I=!!h||R?.id===E&&R.type==="checkpoint"&&R.ref===n;if(k.run.pending&&k.run.pending!==E)throw new fe(_e(`FATAL: another action is pending: ${k.run.pending}`));if(!I&&!m.archived&&m.archiveConfirmation!=="confirmed")throw new fe(_e(`FATAL: archive_confirmation is '${m.archiveConfirmation??"null"}', expected 'confirmed'. Run final archive confirmation first.`));if(!I){let fn={id:E,stepId:k.run.currentStep,type:"checkpoint",ref:n};await ko(g,k.run.pendingRef,fn),await Ne(g,{classic:k.classic,run:{...k.run,pending:E,status:"waiting"},unknownKeys:(await W(g)).unknownKeys})}if(!h){let fn=await fl(["archive",n,"--yes"],s.projectRoot);if(t.captureOpenSpec(fn),fn.exitCode!==0)throw new fe("",fn.exitCode)}let b=await ao(n,s.projectRoot,{preferredArchiveName:f});if(!b&&!h&&(b=await ao(n,s.projectRoot,{skipExactCompatibility:!0})),!b)return t.stderr.push(_e(" [FAIL] OpenSpec archive output not found")),t.stepsTotal+=1,t.stderr.push(""),t.stderr.push(Be(`Archive complete. ${t.stepsOk}/${t.stepsTotal} steps succeeded.`)),t.toResult(1);u=b.directory,f=st.basename(b.directory),t.stderr.push(Be(` [OK] OpenSpec archive completed: ${u}`)),t.stepsOk+=1,t.stepsTotal+=1,await qS(s.projectRoot,s.specsDir),t.stderr.push(Be(" [OK] Main specs verified clean")),t.stepsOk+=1,t.stepsTotal+=1,w&&await Lo(t,s.projectRoot,w,f,"status: final",!1),y&&await Lo(t,s.projectRoot,y,f,"",!1);let L=await W(u);if(!L.classic||!L.run)throw new fe(_e(" [FAIL] archived state projection is incomplete"));let Ie={...TS(s.projectRoot,a,u,await ii(u,L.run.artifactsRef)),archive_directory:N(s.projectRoot,u)};await ri(u,L.run.artifactsRef,Ie);let z=ai(I&&L.classic.archiveConfirmation!=="confirmed"?{...L.classic,archiveConfirmation:"confirmed"}:L.classic,"archived"),K={...z.classic,designDoc:br(s.projectRoot,a,u,z.classic.designDoc),plan:br(s.projectRoot,a,u,z.classic.plan),verificationReport:br(s.projectRoot,a,u,z.classic.verificationReport),handoffContext:br(s.projectRoot,a,u,z.classic.handoffContext)},Ce=L.run;(L.run.currentStep!=="completed"||L.run.status!=="completed")&&(Ce=await rn(u,K,L.run,{actionId:E,archiveDirectory:N(s.projectRoot,u),event:"archived",source:"comet-archive"})),I&&await MS(u,Ce,E);let Dr=await Te(u,Ce.trajectoryRef),la=await Co(u,Ce.contextRef),ut={runId:Ce.runId,stateVersion:Ce.iteration,trajectoryOffset:Dr.length,contextHash:la===null?null:Hp(la),artifactsHash:AS(Ie),createdAt:new Date().toISOString()};await si(u,Ce.checkpointRef,ut);let Fr={...Ce,pending:null,status:"completed"};await Ne(u,{classic:K,run:Fr,unknownKeys:L.unknownKeys}),await Pn(u,{change:f,event:"archived",source:"comet-archive",from:L.classic,to:K,effects:z.effects}),await So(u,Fr.pendingRef),t.stderr.push(Be(" [OK] archived: true")),t.stepsOk+=1,t.stepsTotal+=1}else{if(!p.run)throw new fe(_e("FATAL: archived Classic state is missing its Run projection"));t.stderr.push(Be(` [OK] OpenSpec archive completed: ${u}`)),t.stepsOk+=1,t.stepsTotal+=1,t.stderr.push(Be(" [OK] Main specs verified clean")),t.stepsOk+=1,t.stepsTotal+=1,t.stderr.push(Be(" [OK] archived: true")),t.stepsOk+=1,t.stepsTotal+=1}return i?(w&&await Lo(t,s.projectRoot,w,f,"status: final",!0),y&&await Lo(t,s.projectRoot,y,f,"",!0),t.stderr.push(vr(` [DRY-RUN] Would set archived: true in ${u}/.comet.yaml`)),t.stepsOk+=1,t.stepsTotal+=1,t.stderr.push(vr(" [DRY-RUN] Would verify final archive integrity")),t.stepsOk+=1,t.stepsTotal+=1):(await jS(s.projectRoot,u),t.stderr.push(Be(" [OK] Final archive integrity verified")),t.stepsOk+=1,t.stepsTotal+=1),i||await Bp(s.projectRoot,n),t.stderr.push(""),t.stderr.push(i?vr(`Dry run complete. ${t.stepsOk}/${t.stepsTotal} steps would succeed.`):Be(`Archive complete. ${t.stepsOk}/${t.stepsTotal} steps succeeded.`)),t.toResult(t.stepsOk<t.stepsTotal?1:0)}catch(r){if(r instanceof fe){if(r.message)for(let s of r.message.split(`
|
|
189
|
+
`))t.stderr.push(s);return t.toResult(r.exitCode)}throw r}};var nh=ft(nt(),1);import{spawnSync as ZS}from"child_process";import{createHash as th}from"crypto";import{promises as eE}from"fs";import J from"path";import Mo from"path";function Jp(e){if(e!=="build"&&e!=="verify")throw new Error(`Invalid command check scope: '${String(e)}'`)}function Up(e,t="."){if(t.trim().length===0)throw new Error("Command check cwd cannot be blank");let n=Mo.resolve(e),i=Mo.resolve(n,t);if(i!==n&&!i.startsWith(n+Mo.sep))throw new Error(`Command check cwd must resolve within the project root: '${t}'`);return Mo.relative(n,i).replaceAll("\\","/")||"."}function DS(e,t){if(t.type!=="command_check_recorded")return null;let n=t.data;if(typeof n!="object"||n===null||Array.isArray(n))return null;let{scope:i,command:r,exitCode:s,cwd:o}=n;if(i!=="build"&&i!=="verify"||typeof r!="string"||r.trim().length===0||!Number.isInteger(s)||typeof o!="string")return null;let a;try{a=Up(e,o)}catch{return null}return{sequence:t.sequence,timestamp:t.timestamp,runId:t.runId,scope:i,command:r,exitCode:s,cwd:a}}async function Vp(e,t,n,i){if(Jp(i.scope),typeof i.command!="string"||i.command.trim().length===0)throw new Error("Command check command cannot be blank");if(!Number.isInteger(i.exitCode))throw new Error("Command check exitCode must be an integer");let s={sequence:(await Te(t,n.trajectoryRef)).reduce((o,a)=>Math.max(o,a.sequence),0)+1,timestamp:new Date().toISOString(),runId:n.runId,scope:i.scope,command:i.command,exitCode:i.exitCode,cwd:Up(e,i.cwd)};return await De(t,n.trajectoryRef,{sequence:s.sequence,timestamp:s.timestamp,type:"command_check_recorded",runId:s.runId,data:{scope:s.scope,command:s.command,exitCode:s.exitCode,cwd:s.cwd}}),s}async function Yp(e,t,n,i){Jp(i);let r=await Te(t,n.trajectoryRef);for(let s=r.length-1;s>=0;s-=1){let o=r[s];if(o.runId!==n.runId)continue;let a=DS(e,o);if(a?.scope===i)return a}return null}var Gp={"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 FS(e){return Gp[e]?Gp[e]:e.endsWith(".open")?["openspec.proposal","openspec.tasks"]:e.endsWith(".build.execute")?[]:e.endsWith(".build.complete")?["build.tasks-complete"]:e.endsWith(".verify.run")?["build.tasks-complete"]:e.endsWith(".verify.branch")?["verification.report"]:e.endsWith(".archive.confirm")?["verification.report"]:e.endsWith(".archive.execute")?["archive.confirmed"]:[]}function zp(e,t){let n=FS(e),i=n.filter(r=>!_n(t,r));return{stepId:e,passed:i.length===0,requiredEvidence:n,missingEvidence:i}}function BS(e){switch(e){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 Xp(e,t){try{let n=await Rp(e),i=await Ue(e,{classic:n.classic,run:n.run,unknownKeys:[]}),r=bt(n.classic,i);return{name:t,valid:!0,workflow:n.classic.workflow,phase:n.classic.phase,currentStep:r,nextCommand:BS(n.classic.phase),runtimeMode:"engine-projection",runtimeEval:zp(r,i),evidence:i}}catch(n){return{name:t,valid:!1,workflow:"unknown",phase:"invalid",currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:n instanceof Error?n.message:String(n)}}}var Er=ft(nt(),1);import Zp from"path";import{AsyncLocalStorage as WS}from"async_hooks";import{promises as Qp}from"fs";import Cr from"path";var qo=new WS;function HS(e,t){let n=Cr.relative(e,t);return n===""||!Cr.isAbsolute(n)&&n!==".."&&!n.startsWith(`..${Cr.sep}`)}async function KS(e){let t=Cr.resolve(e.invocationCwd??process.cwd()),n=Cr.resolve(e.projectRoot??await ue(t)),[i,r]=await Promise.all([Qp.realpath(t),Qp.realpath(n)]);if(!HS(r,i))throw new Error(`Classic command invocation cwd is outside the discovered project: ${t}`);return{invocationCwd:t,projectRoot:n}}async function ot(e,t){let n=qo.getStore();if(n)return t(n);let i=await KS(e);return qo.run(i,()=>t(i))}function P(){let e=qo.getStore();if(!e)throw new Error("Classic command project context is unavailable");return e.projectRoot}function Rt(){let e=qo.getStore();if(!e)throw new Error("Classic command invocation context is unavailable");return e.invocationCwd}var JS="\x1B[32m",kr="\x1B[31m",US="\x1B[33m",VS="\x1B[0m",YS=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"],GS={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"],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"]},zS=new Set([...Zt,...dr,"classic_profile","classic_migration"]);function On(e,t){return`${e}${t}${VS}`}function Sr(e){return e==null?"":typeof e=="object"?JSON.stringify(e):String(e)}var Do=async(e,t)=>ot(t,async()=>{let n=e[0],i=ge(n);if(i)return{exitCode:1,stderr:On(kr,`ERROR: ${i}`)};let r=P(),{directory:s,label:o}=await ei(n,r),a=Zp.join(s,".comet.yaml"),c=[`[VALIDATE] ${o}/.comet.yaml`],l=0,f=0,u=m=>{l+=1,c.push(On(kr,` FAIL: ${m}`))},d=m=>{f+=1,c.push(On(US,` WARN: ${m}`))},h;try{h=await B(r,a,{label:`Classic state ${o}/.comet.yaml`})}catch(m){if(m.code==="ENOENT")return u(".comet.yaml does not exist"),c.push("",On(kr,`${l} error(s), ${f} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(`
|
|
190
190
|
`)};throw m}let g=(0,Er.parseDocument)(h);if(g.errors.length>0||!(0,Er.isMap)(g.contents)){for(let m of g.errors)u(m.message);return(0,Er.isMap)(g.contents)||u("document root must be a mapping"),c.push("",On(kr,`${l} error(s), ${f} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(`
|
|
191
|
-
`)}}let p=g.toJS();for(let m of
|
|
192
|
-
`)}):(c.push(On(
|
|
193
|
-
`)})});wt();import
|
|
191
|
+
`)}}let p=g.toJS();for(let m of YS)Object.prototype.hasOwnProperty.call(p,m)||u(`missing required field '${m}'`);for(let[m,w]of Object.entries(GS)){if(!Object.prototype.hasOwnProperty.call(p,m))continue;let y=Sr(p[m]);if(!y){m==="auto_transition"&&u(`${m}='' is not valid. Expected: ${w.join(" ")}`);continue}w.includes(y)||u(`${m}='${y}' is not valid. Expected: ${w.join(" ")}`)}if(Object.prototype.hasOwnProperty.call(p,"bound_branch")){let m=p.bound_branch;m!==null&&typeof m!="string"&&u(`bound_branch='${Sr(m)}' is not a string or null`)}if(Object.prototype.hasOwnProperty.call(p,"verify_failures")){let m=p.verify_failures;(typeof m!="number"||!Number.isInteger(m)||m<0)&&u(`verify_failures='${Sr(m)}' is not a non-negative integer`)}for(let m of["design_doc","plan","handoff_context","verification_report"]){let w=Sr(p[m]);if(w){if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(w)||w.split(/[\\/]/u).includes("..")){u(`${m}='${w}' must be a relative repository path`);continue}try{await ee(r,Zp.resolve(r,w),{label:`${m} artifact pointer`,expected:"file"})||u(`${m}='${w}' does not exist on disk`)}catch(y){u(`${m}='${w}' is unsafe: ${y instanceof Error?y.message:String(y)}`)}}}for(let m of["handoff_hash"]){let w=Sr(p[m]);w&&!/^[a-f0-9]{64}$/u.test(w)&&u(`${m}='${w}' is not a sha256 hex digest`)}for(let m of Object.keys(p))zS.has(m)||d(`unknown field '${m}' found`);return c.push(""),l>0?(c.push(On(kr,`${l} error(s), ${f} warning(s) — validation FAILED`)),{exitCode:1,stderr:c.join(`
|
|
192
|
+
`)}):(c.push(On(JS,`0 errors, ${f} warning(s) — validation PASSED`)),{exitCode:0,stderr:c.join(`
|
|
193
|
+
`)})});wt();import XS from"os";import Fo from"path";function QS(e={}){let t=e.cwd??process.cwd(),n=e.homeDir??XS.homedir(),i=[{file:Fo.resolve(t,".comet","config.yaml"),source:".comet/config.yaml"},{file:Fo.resolve(n,".comet","config.yaml"),source:"~/.comet/config.yaml"}];return i.filter((r,s)=>i.findIndex(o=>o.file===r.file)===s)}async function Rr(e,t={}){for(let n of QS(t)){let i=await it(Fo.dirname(Fo.dirname(n.file)),{allowPartialProject:!0});if(!i)continue;let r=i.value.classic;if(!r||typeof r!="object"||Array.isArray(r))continue;let s=r[e];if(s!=null)return{value:String(s),source:n.source}}return null}wt();var tE="\x1B[32m",nE="\x1B[31m",iE="\x1B[33m",Ml="\x1B[0m",rE=["open","design","build","verify","archive"],sE={open:"=== Guard: open → next ===",design:"=== Guard: design → build ===",build:"=== Guard: build → verify ===",verify:"=== Guard: verify → archive ===",archive:"=== Guard: archive completeness ==="},oE={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"},aE={branchStatus:"branch_status",phase:"phase",verificationReport:"verification_report",verifiedAt:"verified_at",verifyResult:"verify_result"};function ci(e){return`${tE}${e}${Ml}`}function _t(e){return`${nE}${e}${Ml}`}function cE(e){return`${iE}${e}${Ml}`}function lE(e){return aE[e]??String(e)}function uE(e){return e===null?"null":e===void 0?"":typeof e=="object"?JSON.stringify(e):String(e)}var Ge=class extends Error{constructor(n,i=1){super(n);this.exitCode=i}exitCode},Ll=class{stderr=[];diagnostics;toResult(t=0){return{exitCode:t,...this.diagnostics?{stdout:JSON.stringify({diagnostics:this.diagnostics})+`
|
|
194
194
|
`}:{},...this.stderr.length>0?{stderr:this.stderr.join(`
|
|
195
195
|
`)+`
|
|
196
|
-
`}:{}}}};async function se(e){let t=P();return
|
|
197
|
-
`)}function
|
|
196
|
+
`}:{}}}};async function se(e){let t=P();return ee(t,e,{label:`Classic guard path ${J.relative(t,J.resolve(t,e)).replaceAll("\\","/")}`})}async function de(e){let t=P();return Sn(t,e,`Classic guard file ${J.relative(t,J.resolve(t,e)).replaceAll("\\","/")}`)}function fE(e){let t=ge(e);if(t)throw new Ge(_t(`ERROR: ${t}`))}async function dE(e){return(await ei(e,P())).directory}async function H(e,t){let n=J.join(e,".comet.yaml"),i=(0,nh.parseDocument)(await B(P(),n,{label:`Classic state ${e}/.comet.yaml`}),{uniqueKeys:!1});if(i.errors.length>0)throw new Ge(`ERROR: Invalid .comet.yaml: ${i.errors[0].message}`);let s=i.toJS()[t];return s==null?"":typeof s=="object"?JSON.stringify(s):String(s)}async function mE(e,t){let n=await H(t,e);return n&&n!=="null"?n:(await Rr(e,{cwd:P()}))?.value??""}async function pE(e){let t=await mE("language",e);if(!t)return"en";if(t==="en"||t==="zh-CN")return t;throw new Error(`configured language '${t}' is invalid; expected en or zh-CN.`)}function hE(e){let t=[],n=!1;for(let i of e.split(/\r?\n/u)){if(/^\s*```/u.test(i)){n=!n;continue}n||t.push(i)}return t.join(`
|
|
197
|
+
`)}function gE(e){return e.match(/[\u4e00-\u9fff]/gu)?.length??0}function wE(e){return e.match(/[A-Za-z][A-Za-z0-9_-]{2,}/gu)?.length??0}async function at(e,t){let n=await pE(e),i=hE(await B(P(),t,{label:`Classic language-check artifact ${t}`})),r=gE(i),s=wE(i);return n==="zh-CN"&&r<20&&s>=20?x(`configured language is zh-CN, but ${t} appears to be English-dominant (cjk_chars=${r}, english_words=${s}).
|
|
198
198
|
Next: regenerate or rewrite this artifact in Chinese while preserving necessary technical terms.`):n==="en"&&r>20&&r>s?x(`configured language is en, but ${t} appears to be Chinese-dominant (cjk_chars=${r}, english_words=${s}).
|
|
199
|
-
Next: regenerate or rewrite this artifact in English while preserving necessary technical terms.`):A()}async function
|
|
200
|
-
`)).digest("hex")}async function
|
|
199
|
+
Next: regenerate or rewrite this artifact in English while preserving necessary technical terms.`):A()}async function ih(e){return th("sha256").update(await oo(P(),e,{label:`Classic handoff source ${e}`})).digest("hex")}async function ql(e){let t=N(P(),e),n=[`${t}/proposal.md`,`${t}/design.md`,`${t}/tasks.md`],i=`${t}/specs`;if(await se(i)){await V(P(),i,{label:`Classic delta-spec directory ${i}`,expected:"directory"});for(let r of(await eE.readdir(i)).sort()){let s=`${i}/${r}/spec.md`;await se(s)&&n.push(s)}}return n}async function yE(e){let t=[];for(let n of await ql(e))await se(n)&&t.push(`path:${n}`,`sha256:${await ih(n)}`);return th("sha256").update(t.join(`
|
|
200
|
+
`)).digest("hex")}async function vE(e,t){if(!await se(e))throw new Ge(_t(`FATAL: change directory not found: ${e}`));if(!await se(J.join(e,".comet.yaml")))throw new Ge(_t(`FATAL: .comet.yaml not found in ${e}`));await V(P(),J.join(e,".comet"),{label:`Classic runtime directory for ${t}`,expected:"directory"});let n=await Do([t],{json:!1});if(n.exitCode!==0)throw n.stderr&&process.stderr.write(n.stderr.endsWith(`
|
|
201
201
|
`)?n.stderr:`${n.stderr}
|
|
202
|
-
`),new Ge(_t("FATAL: .comet.yaml schema validation failed"));let i=await W(e),r=Array.from(new Set(i.unknownKeys)).sort();if(r.length>0)throw new Ge(_t(`FATAL: .comet.yaml has unknown field(s): ${r.join(", ")}`))}function
|
|
202
|
+
`),new Ge(_t("FATAL: .comet.yaml schema validation failed"));let i=await W(e),r=Array.from(new Set(i.unknownKeys)).sort();if(r.length>0)throw new Ge(_t(`FATAL: .comet.yaml has unknown field(s): ${r.join(", ")}`))}function bE(e,t){if(t.passed){if(e.stderr.push(ci(` [PASS] ${t.description}`)),t.detail)for(let n of t.detail.split(`
|
|
203
203
|
`))e.stderr.push(ci(` ${n}`))}else if(e.stderr.push(_t(` [FAIL] ${t.description}`)),t.detail)for(let n of t.detail.split(`
|
|
204
|
-
`))e.stderr.push(_t(` ${n}`))}function $(e,t){return async()=>{try{let n=await t();return{description:e,passed:n.passed,detail:("detail"in n?n.detail:"")??""}}catch(n){return{description:e,passed:!1,detail:n instanceof Error?n.message:String(n)}}}}function A(e){return{passed:!0,...e?{detail:e}:{}}}function x(e){return{passed:!1,detail:e}}async function li(e,t){let n=!1;for(let i of t){let r=await i();
|
|
205
|
-
${
|
|
204
|
+
`))e.stderr.push(_t(` ${n}`))}function $(e,t){return async()=>{try{let n=await t();return{description:e,passed:n.passed,detail:("detail"in n?n.detail:"")??""}}catch(n){return{description:e,passed:!1,detail:n instanceof Error?n.message:String(n)}}}}function A(e){return{passed:!0,...e?{detail:e}:{}}}function x(e){return{passed:!1,detail:e}}async function li(e,t){let n=!1;for(let i of t){let r=await i();bE(e,r),r.passed||(n=!0)}return n}var CE=["package.json with a build script","pom.xml","Cargo.toml"];async function kE(e){try{let t=await it(P(),{allowPartialProject:!0});return t?Object.prototype.hasOwnProperty.call(t.value,e):!1}catch(t){throw new Error(`.comet/config.yaml is invalid YAML (${t instanceof Error?t.message:String(t)}); cannot check for removed "${e}" field. Fix the config and retry.`,{cause:t})}}function SE(e){return{status:1,output:`${e} has been removed from .comet/config.yaml. Delete this field and run any required ${e==="build_command"?"build":"verification"} command manually before retrying.`}}function EE(e){let t=ZS(e,{shell:!0,cwd:Rt(),encoding:"utf8",timeout:3e5});return{status:t.status??1,output:`${t.stdout??""}${t.stderr??""}`.replace(/\n+$/u,"")}}function _r(e){return J.resolve(Rt(),e)}async function RE(){let e=_r("package.json");return await se(e)&&typeof JSON.parse(await B(P(),e,{label:"package.json"})).scripts?.build=="string"?"npm run build":await se(_r("pom.xml"))?process.platform==="win32"?await se(_r("mvnw.cmd"))?"mvnw.cmd compile -q":"mvn.cmd compile -q":await se(_r("mvnw"))?"./mvnw compile -q":"mvn compile -q":await se(_r("Cargo.toml"))?"cargo build":null}function eh(e){return`Evidence: recorded command-check at ${e.timestamp}; command: ${e.command}; cwd: ${e.cwd}`}function Tl(e,t,n){return`comet state record-check ${e} ${t} --command "${n}" --exit-code 0`}async function rh(e,t,n,i){if(process.env.COMET_SKIP_BUILD==="1")return{status:0,output:"SKIPPED via COMET_SKIP_BUILD=1"};let r=i==="build"?["build_command"]:["verify_command","build_command"];for(let a of r)if(await kE(a))return SE(a);let s=i==="build"?await RE():null;if(s)return EE(s);let o=await Yp(P(),e,n,i);return o?o.exitCode!==0?{status:o.exitCode,output:`Latest recorded ${i} check failed with exit code ${o.exitCode}.
|
|
205
|
+
${eh(o)}
|
|
206
206
|
Next: rerun the command successfully, then record it with:
|
|
207
|
-
${Tl(t,i,o.command)}`}:{status:0,output:
|
|
207
|
+
${Tl(t,i,o.command)}`}:{status:0,output:eh(o)}:{status:1,output:i==="build"?`No inferred build command or recorded build check. Detection searched: ${CE.join(", ")}.
|
|
208
208
|
Next: run the required command, then record it with:
|
|
209
209
|
${Tl(t,i,"<command>")}`:`No recorded verify check.
|
|
210
210
|
Next: run the required verification command, then record it with:
|
|
@@ -213,83 +213,83 @@ Next: restore or create tasks.md for this change before leaving build.`);let n=a
|
|
|
213
213
|
Next: complete implementation tasks and mark them with '- [x]'.`);let i=n.split(/\r?\n/u).map((r,s)=>({line:r,number:s+1})).filter(r=>/^- \[ \]/u.test(r.line));return i.length>0?x(`Unfinished tasks:
|
|
214
214
|
${i.map(r=>`${r.number}:${r.line}`).join(`
|
|
215
215
|
`)}
|
|
216
|
-
Next: complete or explicitly remove unfinished tasks, then mark tasks.md with '- [x]'.`):A()}async function
|
|
216
|
+
Next: complete or explicitly remove unfinished tasks, then mark tasks.md with '- [x]'.`):A()}async function _E(e){let t=J.join(e,"tasks.md");return await se(t)?/- \[/u.test(await B(P(),t,{label:`Classic tasks ${t}`})):!1}async function xE(e){let t=await H(e,"plan");if(!t||t==="null")return A();if(!await se(t))return x(`plan file is missing at ${t}
|
|
217
217
|
Next: restore the Superpowers plan file or update .comet.yaml plan before leaving build.`);let i=(await B(P(),t,{label:`Classic plan ${t}`})).split(/\r?\n/u).map((r,s)=>({line:r,number:s+1})).filter(r=>/^\s*- \[ \]/u.test(r.line));return i.length>0?x(`Unfinished Superpowers plan tasks:
|
|
218
218
|
${i.map(r=>`${r.number}:${r.line}`).join(`
|
|
219
219
|
`)}
|
|
220
|
-
Next: check off corresponding completed plan tasks, then commit the plan update.`):A()}async function Fl(e,t){let n;try{n=await St(e,{heal:!0,cwd:Rt()})}catch(i){throw new Ge(`ERROR: ${i instanceof Error?i.message:String(i)}`)}switch(n.status){case"drift":return x(
|
|
220
|
+
Next: check off corresponding completed plan tasks, then commit the plan update.`):A()}async function Fl(e,t){let n;try{n=await St(e,{heal:!0,cwd:Rt()})}catch(i){throw new Ge(`ERROR: ${i instanceof Error?i.message:String(i)}`)}switch(n.status){case"drift":return x(To(t,n.boundBranch,n.currentBranch));case"unbound-detached":return x(Et(t));case"healed":return A(`bound_branch lazily set to ${n.branch}`);case"needs-heal":case"ok":case"not-applicable":return A();default:{let i=n;throw new Error(`unhandled branch binding status: ${JSON.stringify(i)}`)}}}async function PE(e,t){let n=await H(e,"isolation");return n==="current"||n==="branch"||n==="worktree"?A():x(`isolation must be current, branch, or worktree, got '${n||"null"}'
|
|
221
221
|
Next: choose a valid workspace mode, prepare it when needed, then run:
|
|
222
|
-
comet state set ${t} isolation <current|branch|worktree>`)}async function
|
|
222
|
+
comet state set ${t} isolation <current|branch|worktree>`)}async function OE(e,t){let n=await H(e,"build_mode");return["subagent-driven-development","executing-plans","direct"].includes(n)?A():x(`build_mode must be selected before leaving build, got '${n||"null"}'
|
|
223
223
|
Next: ask the user to choose an execution mode, then run:
|
|
224
|
-
comet state set ${t} build_mode <subagent-driven-development|executing-plans>`)}async function
|
|
225
|
-
Next: choose executing-plans or subagent-driven-development, or stop and ask the user for an explicit direct override.`)}async function
|
|
224
|
+
comet state set ${t} build_mode <subagent-driven-development|executing-plans>`)}async function $E(e){let t=await H(e,"workflow"),n=await H(e,"build_mode"),i=await H(e,"direct_override");return n!=="direct"||t==="hotfix"||t==="tweak"||i==="true"?A():x(`build_mode=direct is only allowed for hotfix/tweak unless direct_override: true is recorded
|
|
225
|
+
Next: choose executing-plans or subagent-driven-development, or stop and ask the user for an explicit direct override.`)}async function IE(e,t){let n=await H(e,"build_mode"),i=await H(e,"subagent_dispatch");return n!=="subagent-driven-development"||i==="confirmed"?A():x(`subagent_dispatch must be confirmed before using build_mode=subagent-driven-development
|
|
226
226
|
Next: record the selected subagent-driven execution, then run:
|
|
227
|
-
comet state set ${t} subagent_dispatch confirmed`)}async function
|
|
227
|
+
comet state set ${t} subagent_dispatch confirmed`)}async function AE(e,t){let n=await H(e,"workflow");if(n==="hotfix"||n==="tweak")return A();let i=await H(e,"tdd_mode");return i==="tdd"||i==="direct"?A():x(`tdd_mode must be tdd or direct for full workflow, got '${i||"null"}'
|
|
228
228
|
Next: ask the user to choose TDD enforcement level, then run:
|
|
229
|
-
comet state set ${t} tdd_mode <tdd|direct>`)}async function
|
|
229
|
+
comet state set ${t} tdd_mode <tdd|direct>`)}async function NE(e,t){let n=await H(e,"workflow");if(n==="hotfix"||n==="tweak")return A();let i=await H(e,"review_mode");return i==="off"||i==="standard"||i==="thorough"?A():x(`review_mode must be off, standard, or thorough before leaving build, got '${i||"null"}'
|
|
230
230
|
Next: ask the user to choose review strength, then run:
|
|
231
|
-
comet state set ${t} review_mode <off|standard|thorough>`)}async function
|
|
232
|
-
Next: create the Design Doc and run: comet state set ${t} design_doc <path>`)}async function
|
|
231
|
+
comet state set ${t} review_mode <off|standard|thorough>`)}async function TE(e){let t=await H(e,"verification_report");return!!t&&t!=="null"&&await se(t)}async function jE(e){return await H(e,"branch_status")==="handled"}async function LE(e){return await H(e,"archived")==="true"}async function jl(e,t,n){let i=(await B(P(),e,{label:`Classic Design Doc ${e}`})).replace(/^\uFEFF/u,""),r=!1;for(let s of i.split(/\r?\n/u)){if(!r){s==="---"&&(r=!0);continue}if(s==="---")break;if(new RegExp(`^${t}: ['"]?${n}['"]?\\s*$`,"u").test(s))return!0}return!1}async function ME(e,t){let n=await H(e,"design_doc");return n&&n!=="null"&&await se(n)?A():x(`design_doc must point to an existing Superpowers Design Doc for full workflow before leaving design.
|
|
232
|
+
Next: create the Design Doc and run: comet state set ${t} design_doc <path>`)}async function qE(e,t){let n=await H(e,"handoff_context"),i=await H(e,"handoff_hash");if(!n||n==="null")return x(`handoff_context is missing from .comet.yaml
|
|
233
233
|
Next: run node "$COMET_HANDOFF" ${t} design --write before invoking Superpowers.`);if(!await de(n))return x(`handoff_context does not point to a non-empty file: ${n}
|
|
234
234
|
Next: regenerate the design handoff with comet handoff ${t} design --write.`);if(!/^[a-f0-9]{64}$/u.test(i))return x(`handoff_hash is missing or invalid: ${i||"null"}
|
|
235
|
-
Next: regenerate the design handoff with comet handoff ${t} design --write.`);let r=await
|
|
235
|
+
Next: regenerate the design handoff with comet handoff ${t} design --write.`);let r=await yE(e);if(r!==i)return x(`OpenSpec artifacts changed after handoff was generated.
|
|
236
236
|
Expected handoff_hash: ${i}
|
|
237
237
|
Actual handoff_hash: ${r}
|
|
238
238
|
Next: run comet handoff ${t} design --write so Superpowers receives the current OpenSpec context.`);let s=`${n.replace(/\.json$/u,"")}.md`;return await de(s)?A():x(`design handoff markdown is missing or empty: ${s}
|
|
239
|
-
Next: regenerate the design handoff with comet handoff ${t} design --write.`)}async function
|
|
240
|
-
`))}async function
|
|
241
|
-
`))}async function
|
|
242
|
-
Valid phases: open, design, build, verify, archive`);await Ee(P());let o=await
|
|
243
|
-
`))n.stderr.push(a);return n.toResult(o.exitCode)}throw o}});var
|
|
239
|
+
Next: regenerate the design handoff with comet handoff ${t} design --write.`)}async function DE(e){let t=await H(e,"handoff_context");if(!t||t==="null")return x("handoff_context is missing from .comet.yaml");let n=`${t.replace(/\.json$/u,"")}.md`;if(!await de(n))return x(`design handoff markdown is missing or empty: ${n}`);let i=await B(P(),n,{label:`Classic handoff markdown ${n}`}),r=new Set(i.split(/\r?\n/u)),s=[];/^Generated-by: comet-handoff\.sh$/mu.test(i)||s.push("handoff markdown is missing Generated-by marker"),/^- Mode: (compact|full|beta)$/mu.test(i)||s.push("handoff markdown is missing Mode marker");for(let o of await ql(e))await se(o)&&(r.has(`- Source: ${o}`)||s.push(`handoff markdown is missing source reference: ${o}`),r.has(`- SHA256: ${await ih(o)}`)||s.push(`handoff markdown is missing current sha256 for: ${o}`));return s.length===0?A():x(s.join(`
|
|
240
|
+
`))}async function sh(e){return await H(e,"context_compression")||"off"}async function FE(e){if(await sh(e)!=="beta")return A();let t=await H(e,"handoff_context");if(!t||t==="null")return x("handoff_context is missing from .comet.yaml");if(!await de(t))return x(`spec-context.json is missing or empty: ${t}`);let n=await B(P(),t,{label:`Classic handoff context ${t}`}),i=[],r;try{r=JSON.parse(n)}catch(a){return x(`spec-context.json invalid JSON: ${a instanceof Error?a.message:String(a)}`)}if(!r||typeof r!="object"||Array.isArray(r))return x("spec-context.json root must be an object");let s=r;typeof s.change!="string"&&i.push("spec-context.json missing 'change' field"),typeof s.phase!="string"&&i.push("spec-context.json missing 'phase' field"),s.mode!=="beta"&&i.push("spec-context.json mode is not beta"),typeof s.context_hash!="string"&&i.push("spec-context.json missing 'context_hash' field"),Array.isArray(s.files)||i.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 ql(e))await se(a)&&(o.some(c=>c.path===a&&typeof c.sha256=="string")||i.push(`spec-context.json missing source file reference: ${a}`));return i.length===0?A():x(i.join(`
|
|
241
|
+
`))}async function BE(e,t){let n=await H(t,"workflow"),i=[$("proposal.md exists and non-empty",async()=>await de(J.join(t,"proposal.md"))?A():x("")),$("proposal.md matches configured language",()=>at(t,J.join(t,"proposal.md"))),$("tasks.md exists and non-empty",async()=>await de(J.join(t,"tasks.md"))?A():x("")),$("tasks.md matches configured language",()=>at(t,J.join(t,"tasks.md"))),$("tasks.md has at least one task",async()=>await _E(t)?A():x(""))];return n==="full"&&i.splice(1,0,$("design.md exists and non-empty",async()=>await de(J.join(t,"design.md"))?A():x("")),$("design.md matches configured language",()=>at(t,J.join(t,"design.md")))),li(e,i)}async function WE(e,t,n){let i=await H(t,"design_doc"),r=await H(t,"workflow"),s=[$("proposal.md exists",async()=>await de(J.join(t,"proposal.md"))?A():x("")),$("proposal.md matches configured language",()=>at(t,J.join(t,"proposal.md"))),$("design.md exists",async()=>await de(J.join(t,"design.md"))?A():x("")),$("design.md matches configured language",()=>at(t,J.join(t,"design.md"))),$("tasks.md exists",async()=>await de(J.join(t,"tasks.md"))?A():x("")),$("tasks.md matches configured language",()=>at(t,J.join(t,"tasks.md"))),$("design handoff context exists",()=>qE(t,n)),$("design handoff markdown is traceable",()=>DE(t))];await sh(t)==="beta"&&s.push($("beta spec-context.json is structurally valid",()=>FE(t))),r==="full"&&s.push($("design_doc is recorded for full workflow",()=>ME(t,n)));let o=await li(e,s);return i&&i!=="null"?o=await li(e,[$(`Design Doc (${i}) exists`,async()=>await de(i)?A():x("")),$("Design Doc matches configured language",()=>at(t,i)),$("Design Doc frontmatter links current change",async()=>await de(i)&&await jl(i,"comet_change",n)?A():x("")),$("Design Doc declares technical design role",async()=>await de(i)&&await jl(i,"role","technical-design")?A():x("")),$("Design Doc declares OpenSpec as canonical spec",async()=>await de(i)&&await jl(i,"canonical_spec","openspec")?A():x(""))])||o:r!=="full"&&e.stderr.push(cE(" [WARN] No design_doc recorded in .comet.yaml (optional for hotfix/tweak)")),o}async function HE(e,t,n,i){return li(e,[$("bound branch matches workspace mode",()=>Fl(t,n)),$("isolation selected",()=>PE(t,n)),$("build_mode selected",()=>OE(t,n)),$("build_mode allowed for workflow",()=>$E(t)),$("subagent dispatch confirmed",()=>IE(t,n)),$("tdd_mode selected",()=>AE(t,n)),$("review_mode selected",()=>NE(t,n)),$("tasks.md all tasks checked",()=>Dl(t)),$("Superpowers plan all tasks checked",()=>xE(t)),$("proposal.md exists",async()=>await de(J.join(t,"proposal.md"))?A():x("")),$("proposal.md matches configured language",()=>at(t,J.join(t,"proposal.md"))),$("Superpowers plan matches configured language",async()=>{let r=await H(t,"plan");return!r||r==="null"||!await se(r)?A():at(t,r)}),$("Build passes",async()=>{let r=await rh(t,n,i,"build");return r.status===0?A(r.output):x(r.output)})])}async function KE(e,t,n,i){return li(e,[$("bound branch matches workspace mode",()=>Fl(t,n)),$("tasks.md all tasks checked",()=>Dl(t)),$("Verification passes",async()=>{let r=await rh(t,n,i,"verify");return r.status===0?A(r.output):x(r.output)}),$("verification_report exists",async()=>await TE(t)?A():x("")),$("verification_report matches configured language",async()=>{let r=await H(t,"verification_report");return!r||r==="null"||!await se(r)?A():at(t,r)})])}async function JE(e,t,n){return li(e,[$("bound branch matches workspace mode",()=>Fl(t,n)),$("archived is true",async()=>await LE(t)?A():x("")),$("proposal.md exists",async()=>await de(J.join(t,"proposal.md"))?A():x("")),$("design.md exists",async()=>await de(J.join(t,"design.md"))?A():x("")),$("tasks.md all tasks checked",()=>Dl(t)),$("branch_status=handled",async()=>await jE(t)?A():x(""))])}async function UE(e,t,n,i){let r=xp[i];if(!r)return;let s=await nn(n),o=ai(s.classic,r);await rn(n,o.classic,s.run,{event:r,phase:i,source:"comet-guard"}),await Pn(n,{change:t,event:r,source:"comet-guard",from:s.classic,to:o.classic,effects:o.effects});for(let l of o.effects)e.stderr.push(ci(`[SET] ${lE(l.field)}=${uE(l.to)}`));e.stderr.push(ci(`[TRANSITION] ${r}`));let a=oE[i],c=i==="open"?a.replace("PLACEHOLDER",o.classic.phase):a;e.stderr.push(ci(c))}var oh=async(e,t)=>ot(t,async()=>{let n=new Ll,[i,r,s]=e;try{if(fE(i),!r||!rE.includes(r))throw new Ge(`${_t(`Unknown phase: ${r??""}`)}
|
|
242
|
+
Valid phases: open, design, build, verify, archive`);await Ee(P());let o=await dE(i);await vE(o,i);let a=await nn(o),c=await Xp(o,i);t.json&&(n.diagnostics={change:i,phase:r,currentStep:c.currentStep,runtimeEval:c.runtimeEval}),n.stderr.push(sE[r]);let l;return r==="open"?l=await BE(n,o):r==="design"?l=await WE(n,o,i):r==="build"?l=await HE(n,o,i,a.run):r==="verify"?l=await KE(n,o,i,a.run):l=await JE(n,o,i),l?(n.stderr.push(""),n.stderr.push(_t("BLOCKED — fix failing checks before proceeding to next phase")),n.toResult(1)):(n.stderr.push(""),n.stderr.push(ci("ALL CHECKS PASSED — ready for next phase")),s==="--apply"&&await UE(n,i,o,r),n.toResult(0))}catch(o){if(o instanceof Ge){for(let a of o.message.split(`
|
|
243
|
+
`))n.stderr.push(a);return n.toResult(o.exitCode)}throw o}});var mh=ft(nt(),1);import{createHash as uh}from"crypto";import{promises as fh}from"fs";import dh from"path";var VE="\x1B[32m",YE="\x1B[31m",GE="\x1B[33m",Wl="\x1B[0m";function sn(e){return`${VE}${e}${Wl}`}function xe(e){return`${YE}${e}${Wl}`}function zE(e){return`${GE}${e}${Wl}`}var me=class extends Error{constructor(n,i=1){super(n);this.exitCode=i}exitCode},Bl=class{stdout=[];stderr=[];toResult(t=0){return{exitCode:t,...this.stdout.length>0?{stdout:this.stdout.join(`
|
|
244
244
|
`)+`
|
|
245
245
|
`}:{},...this.stderr.length>0?{stderr:this.stderr.join(`
|
|
246
246
|
`)+`
|
|
247
|
-
`}:{}}}};async function on(e,t,n){return await
|
|
248
|
-
`)).digest("hex")}function
|
|
249
|
-
`&&(n+=1,n===t))return e.slice(0,i+1);return e}async function
|
|
250
|
-
`),"Classic handoff markdown output")}async function
|
|
251
|
-
`),l=["{",` "change": "${
|
|
252
|
-
`);await
|
|
253
|
-
`),"Classic handoff spec markdown output")}async function
|
|
254
|
-
`,"Classic handoff spec JSON output")}async function
|
|
255
|
-
`));let m=N(a.projectRoot,g),w=N(a.projectRoot,p),y=await
|
|
256
|
-
`))n.stderr.push(c);return n.toResult(a.exitCode)}throw a}});import{promises as
|
|
257
|
-
`}}function Pt(e){return cn(0,`[COMET-HOOK] allowed: ${e}`)}function
|
|
258
|
-
`))}function
|
|
259
|
-
`))}function
|
|
260
|
-
`))}function
|
|
247
|
+
`}:{}}}};async function on(e,t,n){return await ee(e,t,{label:n,expected:"file"})?B(e,t,{label:n}):null}async function Bo(e,t,n,i){await Qn(e,t,n,{label:i})}function XE(e){let t=ge(e);if(t)throw new me(xe(`ERROR: ${t}`))}function xt(e){return uh("sha256").update(e).digest("hex")}function ph(e){return xt(JSON.stringify(Object.fromEntries(Object.entries(e).sort(([t],[n])=>t.localeCompare(n)))))}async function xr(e,t){let n=[`${t}/proposal.md`,`${t}/design.md`,`${t}/tasks.md`],i=`${t}/specs`;if((await V(e,i,{label:"Classic handoff specs directory",expected:"directory"})).exists){let s=(await fh.readdir(i,{withFileTypes:!0})).sort((o,a)=>o.name.localeCompare(a.name));for(let o of s){if(!o.isDirectory()&&!o.isSymbolicLink())continue;let a=`${i}/${o.name}/spec.md`;(await V(e,`${i}/${o.name}`,{label:`Classic handoff spec directory ${o.name}`,expected:"directory"})).exists&&await ee(e,a,{label:`Classic handoff spec ${o.name}`,expected:"file"})&&n.push(a)}}return n}function ui(e,t,n){let i=dh.relative(e,n).replaceAll("\\","/");return`${t}/${i}`}async function ah(e,t,n){let i=[];for(let r of await xr(e,t)){let s=ui(t,n,r),o=await on(e,r,`Classic handoff source ${s}`);o!==null&&i.push(`path:${s}`,`sha256:${xt(o)}`)}return uh("sha256").update(i.join(`
|
|
248
|
+
`)).digest("hex")}function ch(e){return e.replace(/\\/gu,"\\\\").replace(/"/gu,'\\"')}function hh(e){return(e.match(/\n/gu)??[]).length}function QE(e,t){let n=0;for(let i=0;i<e.length;i+=1)if(e[i]===`
|
|
249
|
+
`&&(n+=1,n===t))return e.slice(0,i+1);return e}async function ZE(e,t,n,i,r,s,o){let a=["# Comet Design Handoff","",`- Change: ${i}`,"- Phase: design",`- Mode: ${r}`,`- Context hash: ${s}`,"","Generated-by: comet-handoff.sh","","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 xr(e,t)){let l=ui(t,n,c),f=await on(e,c,`Classic handoff source ${l}`);if(f===null)continue;let u=hh(f);a.push(`## ${l}`,"",`- Source: ${l}`,`- Lines: 1-${u}`,`- SHA256: ${xt(f)}`,""),r==="full"||u<=80?a.push("```md",f,"```"):a.push("[TRUNCATED]","","```md",QE(f,80),"```","",`Full source: ${l}`),a.push("")}await Bo(e,o,a.join(`
|
|
250
|
+
`),"Classic handoff markdown output")}async function eR(e,t,n,i,r,s,o){let a=[];for(let f of await xr(e,t)){let u=ui(t,n,f),d=await on(e,f,`Classic handoff source ${u}`);d!==null&&a.push(` { "path": "${ch(u)}", "sha256": "${xt(d)}" }`)}let c=a.join(`,
|
|
251
|
+
`),l=["{",` "change": "${ch(i)}",`,' "phase": "design",',` "mode": "${r}",`,' "canonical_spec": "openspec",',' "generated_by": "comet-handoff.sh",',` "context_hash": "${s}",`,' "files": [',c," ]","}",""].join(`
|
|
252
|
+
`);await Bo(e,o,l,"Classic handoff JSON output")}async function tR(e,t){return[`## ${e}`,"",`- Source: ${e}`,`- Lines: 1-${hh(t)}`,`- SHA256: ${xt(t)}`,"","```md",t,"```",""]}async function nR(e,t,n,i,r,s){let o=["# Comet Spec Context","",`- Change: ${i}`,"- Phase: design","- Mode: beta",`- Context hash: ${r}`,"","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 f of await xr(e,t)){let u=ui(t,n,f),d=await on(e,f,`Classic handoff source ${u}`);d!==null&&o.push(`- Source: ${u}`,`- SHA256: ${xt(d)}`)}o.push("","## Acceptance Projection","");let a=`${t}/specs`,c=!1;if((await V(e,a,{label:"Classic handoff specs directory",expected:"directory"})).exists){let f=(await fh.readdir(a,{withFileTypes:!0})).sort((u,d)=>u.name.localeCompare(d.name));for(let u of f){if(!u.isDirectory()&&!u.isSymbolicLink())continue;let d=`${a}/${u.name}/spec.md`,h=await on(e,d,`Classic handoff spec ${u.name}`);h!==null&&(c=!0,o.push(...await tR(ui(t,n,d),h)))}}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."),await Bo(e,s,o.join(`
|
|
253
|
+
`),"Classic handoff spec markdown output")}async function iR(e,t,n,i,r,s){let o=[];for(let a of await xr(e,t)){let c=ui(t,n,a),l=await on(e,a,`Classic handoff source ${c}`);if(l===null)continue;let f=/\/specs\/[^/]+\/spec\.md$/u.test(c)?"spec":"supporting";o.push({path:c,sha256:xt(l),role:f})}await Bo(e,s,`${JSON.stringify({change:i,phase:"design",mode:"beta",canonical_spec:"openspec",generated_by:"comet-handoff.sh",context_hash:r,files:o},null,2)}
|
|
254
|
+
`,"Classic handoff spec JSON output")}async function lh(e,t,n){let i=dh.join(t,".comet.yaml"),r=(0,mh.parseDocument)(await B(e,i,{label:"Classic change state"}),{uniqueKeys:!1});if(r.errors.length>0)throw new me(`ERROR: Invalid .comet.yaml: ${r.errors[0].message}`);let o=r.toJS()[n];return o==null?"":typeof o=="object"?JSON.stringify(o):String(o)}async function rR(e,t,n){let i=await Te(e,t.trajectoryRef);i.some(s=>s.type==="recovery_reconciled"&&s.data.kind==="classic-handoff"&&s.data.actionId===n)||await De(e,t.trajectoryRef,{sequence:i.length+1,timestamp:new Date().toISOString(),type:"recovery_reconciled",runId:t.runId,data:{kind:"classic-handoff",actionId:n}})}async function sR(e,t,n,i,r,s,o,a){let[c,l,f]=await Promise.all([Co(t,n.contextRef),ii(t,n.artifactsRef),Qm(t,n.checkpointRef)]),[u,d]=await Promise.all([on(e,r,"Classic handoff JSON output"),on(e,s,"Classic handoff markdown output")]);return u===null||d===null||c!==d||l.handoff_context!==o||l.handoff_markdown!==a?!1:f?.runId===n.runId&&f.contextHash===(c===null?null:xt(c))&&f.artifactsHash===ph(l)&&i.length===64}var gh=async(e,t)=>ot(t,async()=>{let n=new Bl,[i,r,s,o]=e;try{XE(i);let a=await Ee(P()),c=await Je(i,a.projectRoot),l=c.directory,f=N(a.projectRoot,l);if(r==="--hash-only"){if(!c.exists)throw new me(xe(`ERROR: change directory not found: ${f}`));for(let dn of["proposal.md","design.md","tasks.md"])if(!await Sn(a.projectRoot,`${l}/${dn}`,`Classic handoff source ${dn}`))throw new me(xe(`ERROR: required file missing or empty: ${f}/${dn}`));return n.stdout.push(await ah(a.projectRoot,l,f)),n.toResult(0)}if(r!=="design"||s!=="--write")throw new me(xe("Usage: comet-handoff.mjs <change-name> design --write [--full]"));let u;if(o===void 0||o==="")u="compact";else if(o==="--full")u="full";else throw new me(xe("Usage: comet-handoff.mjs <change-name> design --write [--full]"));if(!c.exists)throw new me(xe(`ERROR: change directory not found: ${f}`));if(!c.stateExists)throw new me(xe(`ERROR: .comet.yaml not found at ${f}/.comet.yaml`));if(await lh(a.projectRoot,l,"phase")!=="design")throw new me(xe("ERROR: design handoff requires phase: design"));for(let dn of["proposal.md","design.md","tasks.md"])if(!await Sn(a.projectRoot,`${l}/${dn}`,`Classic handoff source ${dn}`))throw new me(xe(`ERROR: required OpenSpec artifact missing or empty: ${f}/${dn}`));let d=`${l}/.comet/handoff`;await V(a.projectRoot,`${l}/.comet`,{label:"Classic change runtime directory",expected:"directory"}),await V(a.projectRoot,d,{label:"Classic handoff directory",expected:"directory"});let h=await lh(a.projectRoot,l,"context_compression")||"off",g,p;if(h==="off")g=`${d}/design-context.json`,p=`${d}/design-context.md`;else if(h==="beta")u==="full"&&n.stderr.push(zE("[HANDOFF] --full is ignored in beta mode; spec files are projected verbatim")),u="beta",g=`${d}/spec-context.json`,p=`${d}/spec-context.md`;else throw new me([xe(`ERROR: invalid context_compression: ${h}`),xe("Valid values: off, beta")].join(`
|
|
255
|
+
`));let m=N(a.projectRoot,g),w=N(a.projectRoot,p),y=await ah(a.projectRoot,l,f),C=`classic-handoff:${y}`,k=await W(l);if(!k.classic)throw new me(xe("ERROR: design handoff requires Classic state"));let E=k.run?await hr(l,k.run.pendingRef):null,R=E?.id===C&&E.type==="handoff"&&E.ref===y;if(k.classic.handoffHash&&k.classic.handoffHash!==y&&!R)throw new me(xe(`ERROR: stale handoff detected: source hash ${y} does not match completed hash ${k.classic.handoffHash}`));await En(a.projectRoot,`${l}/.comet`,"Classic change runtime directory"),await En(a.projectRoot,d,"Classic handoff directory");let I=await nn(l),b=await hr(l,I.run.pendingRef),L=b?.id===C&&b.type==="handoff"&&b.ref===y;if(I.run.pending&&I.run.pending!==C)throw new me(xe(`ERROR: another action is pending: ${I.run.pending}`));if(I.classic.handoffHash===y&&I.classic.handoffContext===m&&!I.run.pending&&!b&&await sR(a.projectRoot,l,I.run,y,g,p,m,w))return n.stderr.push(sn(`[HANDOFF] wrote ${m}`)),n.stderr.push(sn(`[HANDOFF] wrote ${w}`)),n.stderr.push(sn(`[HANDOFF] handoff_hash=${y}`)),n.toResult(0);let Ie={id:C,stepId:I.run.currentStep,type:"handoff",ref:y};await ko(l,I.run.pendingRef,Ie);let z={...I.run,pending:C,status:"waiting"};await Ne(l,{classic:I.classic,run:z,unknownKeys:(await W(l)).unknownKeys}),u==="beta"?(await nR(a.projectRoot,l,f,i,y,p),await iR(a.projectRoot,l,f,i,y,g)):(await ZE(a.projectRoot,l,f,i,u,y,p),await eR(a.projectRoot,l,f,i,u,y,g));let K=await B(a.projectRoot,p,{label:"Classic handoff markdown output"});await bo(l,z.contextRef,K);let Ce={...await ii(l,z.artifactsRef),handoff_context:m,handoff_markdown:w};await ri(l,z.artifactsRef,Ce);let Dr={...I.classic,handoffContext:m,handoffHash:y},ut={...z.currentStep==="full.design.handoff"?await rn(l,Dr,z,{actionId:C,kind:"classic-handoff"}):z,pending:null,status:"running"};(R||L)&&await rR(l,ut,C);let Fr=await Te(l,ut.trajectoryRef),fn={runId:ut.runId,stateVersion:ut.iteration,trajectoryOffset:Fr.length,contextHash:xt(K),artifactsHash:ph(Ce),createdAt:new Date().toISOString()};return await si(l,ut.checkpointRef,fn),await Ne(l,{classic:Dr,run:ut,unknownKeys:(await W(l)).unknownKeys}),await So(l,ut.pendingRef),n.stderr.push(sn(`[SET] handoff_context=${g}`)),n.stderr.push(sn(`[SET] handoff_hash=${y}`)),n.stderr.push(sn(`[HANDOFF] wrote ${m}`)),n.stderr.push(sn(`[HANDOFF] wrote ${w}`)),n.stderr.push(sn(`[HANDOFF] handoff_hash=${y}`)),n.toResult(0)}catch(a){if(a instanceof me){for(let c of a.message.split(`
|
|
256
|
+
`))n.stderr.push(c);return n.toResult(a.exitCode)}throw a}});import{promises as Wo,readFileSync as oR}from"fs";import je from"path";function cn(e,t){return{exitCode:e,stderr:t+`
|
|
257
|
+
`}}function Pt(e){return cn(0,`[COMET-HOOK] allowed: ${e}`)}function aR(){if(process.env.FILE_PATH)return process.env.FILE_PATH;if(process.stdin.isTTY)return"";let e=oR(0,"utf8");if(!e)return"";try{let t=JSON.parse(e);return typeof t.tool_input?.file_path=="string"?t.tool_input.file_path:""}catch{return""}}function Or(e){return e.replaceAll("\\","/").replace(/\/+/gu,"/")}function $n(e){let t=Or(e);return process.platform==="win32"?t.toLowerCase():t}function cR(e){let t=e.indexOf("--project-root"),n=t>=0?e[t+1]:void 0;return je.resolve(n&&!n.startsWith("--")?n:process.cwd())}function wh(e,t){let n=Or(je.relative(t,e));return n===""?"":n.startsWith("../")||n===".."||je.isAbsolute(n)?null:n}async function lR(e){let t=je.resolve(e),n=je.parse(t).root,i=[],r=t;for(;r&&r!==n;)try{let s=await Wo.realpath(r);return je.join(s,...i.reverse())}catch(s){let o=s.code;if(o!=="ENOENT"&&o!=="ENOTDIR")throw s;i.push(je.basename(r)),r=je.dirname(r)}try{let s=await Wo.realpath(n);return je.join(s,...i.reverse())}catch{return null}}async function uR(e,t){let n=je.isAbsolute(e)?e:je.resolve(process.cwd(),e),i=Or(n),r=wh(n,t);if(r!==null)return r;try{let s=await lR(n),o=await Wo.realpath(t);if(s){let a=wh(s,o);if(a!==null)return a;i=Or(s)}}catch{if(!je.isAbsolute(e))return Or(e).replace(/^\.\//u,"")}return i.replace(/^\.\//u,"")}async function Ch(e){try{let t=await W(e,{migrate:!1}),n=Array.from(new Set(t.unknownKeys)).sort();if(n.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${n.join(", ")}`);if(!t.classic)throw new Error("Classic state projection is unavailable");return{changeDir:e,phase:t.classic.phase,classic:t.classic,archived:t.classic.archived}}catch{let t=await zm(e);return t.phase?{changeDir:e,phase:t.phase,classic:null,archived:t.archived}:null}}async function fR(e){let t=(await Z(e)).changesDir,n=[];if(!(await V(e,t,{label:"Classic changes directory",expected:"directory"})).exists)return n;for(let r of(await Wo.readdir(t,{withFileTypes:!0})).sort((s,o)=>s.name.localeCompare(o.name))){if(r.name==="archive"||ge(r.name))continue;let s=await Je(r.name,e);if(!s.exists||!s.stateExists)continue;let o=await Ch(s.directory);!o||o.archived||n.push(o)}return n}var Hl=Io("classicActiveChanges",e=>fR(e));function kh(e,t){return`${N(e,t.superpowersRoot)}/`}function Sh(e,t){return $n(e).startsWith($n(t))}function dR(e,t){return[{prefix:`${N(e,t.superpowersSpecsDir)}/`,field:"designDoc",wireField:"design_doc",phase:"design"},{prefix:`${N(e,t.superpowersPlansDir)}/`,field:"plan",wireField:"plan",phase:"build"},{prefix:`${N(e,t.superpowersReportsDir)}/`,field:"verificationReport",wireField:"verification_report",phase:"verify"}]}function mR(e,t){let n=$n(e),i=t.find(s=>n.startsWith($n(s.prefix)));if(!i)return null;let r=n.slice($n(i.prefix).length);return!r||r.includes("/")||!r.endsWith(".md")?null:i}function Eh(e,t){return e.classic?.[t.field]??null}function yh(e,t){return e.classic!==null&&e.phase===t.phase&&!Eh(e,t)}function Rh(e){return e.phase==="design"||e.phase==="build"||e.phase==="verify"}function an(e){return e.changeDir?je.basename(e.changeDir):null}var pR=new Set(["design","plan","verify","verification","verification-report","report"]);function vh(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function hR(e,t){return[t.classic?.designDoc,t.classic?.plan,t.classic?.verificationReport].some(i=>i&&$n(i)===$n(e))}function gR(e,t){let i=(e.split("/").at(-1)??e).replace(/\.[^.]+$/u,"");if(i===t)return!0;let r=[...pR].map(vh).join("|");return new RegExp(`(^|[-_.])${vh(t)}[-_.](${r})$`,"u").test(i)}async function wR(e,t){let n=await Hl(t),i=n.find(o=>hR(e,o));if(i)return{governing:i,match:"recorded"};let s=n.filter(Rh).filter(o=>{let a=an(o);return a!==null&&gR(e,a)}).sort((o,a)=>(an(a)?.length??0)-(an(o)?.length??0))[0];return s?{governing:s,match:"named"}:null}async function bh(e,t,n){let i=await Hl(e);if(i.length===0)return null;if(n)return i.find(o=>an(o)===n)??{blockedResult:Pr(t,`selected change '${n}' is no longer active`)};let r=await jo(e);if(r.status==="stale")return{blockedResult:Pr(t,r.reason)};if(r.status==="selected"){let s=i.find(o=>an(o)===r.selection.change);return s||{blockedResult:Pr(t,`selected change '${r.selection.change}' is no longer active`)}}if(i.length===1){let s=i[0];if(s.changeDir!==null){let o=await St(s.changeDir,{heal:!1,cwd:e}),a=an(s)??"unknown";if(o.status==="drift")return{blockedResult:Pr(t,yr(a,o.boundBranch,o.currentBranch))};if(o.status==="unbound-detached")return{blockedResult:Pr(t,Et(a))}}return s}return{blockedResult:_R(t,i.map(s=>an(s)).filter(Boolean))}}async function yR(e,t,n,i){let r=`${N(t,n.changesDir)}/`;if(e.startsWith(r)){let s=e.slice(r.length),[o]=s.split("/");if(o&&o!=="archive"){let a=await Je(o,t);if(a.stateExists){let c=await Ch(a.directory);return c||{changeDir:a.directory,phase:"open",classic:null,archived:!1}}return{changeDir:a.directory,phase:"open",classic:null,archived:!1}}}if(Sh(e,kh(t,n))){let s=await wR(e,t);if(s?.match==="recorded")return{...s.governing,superpowersArtifact:"matched"};let o=mR(e,dR(t,n));if(s)return o?{...s.governing,superpowersArtifact:yh(s.governing,o)?"matched":"unmatched",superpowersSlot:o}:{...s.governing,superpowersArtifact:"matched"};if(o){let l=await bh(t,e,i);return!l||"blockedResult"in l?l:{...l,superpowersArtifact:yh(l,o)?"matched":"unmatched",superpowersSlot:o}}let a=await Hl(t),c=i?a.find(l=>an(l)===i)??null:a[0]??null;return c?{...c,superpowersArtifact:"unmatched"}:null}return bh(t,e,i)}function vR(e){return!e.includes("/")&&e.endsWith(".md")}function bR(e){return e.startsWith(".comet/")||e.includes("/.comet/")}function CR(e){return e===".superpowers"||e.startsWith(".superpowers/")}function kR(e,t,n){if(!e.startsWith(n))return null;let i=e.endsWith("/.comet.yaml")||e.endsWith("/.openspec.yaml"),r=e.endsWith("/proposal.md")||e.endsWith("/design.md")||e.endsWith("/tasks.md"),s=e.includes("/.comet/"),o=e.includes("/specs/");return t==="open"&&(r||i||s||o)?`${e} (phase: open, openspec artifacts)`:t==="design"&&(r||i||s||o)?`${e} (phase: design, handoff/spec)`:t==="build"&&(e.endsWith("/tasks.md")||i||o)?`${e} (phase: build, spec/tasks)`:t==="verify"&&(e.endsWith("/tasks.md")||i)?`${e} (phase: verify, tasks/state)`:t==="archive"&&i?`${e} (phase: archive, state)`:null}function SR(e,t){let n=t==="open"?[" BLOCKED: source writes are not allowed during open"," This phase does not allow source writes"," ALLOWED: create proposal/design/tasks artifacts and run guard"," NEXT: finish clarification and artifacts, then run guard --apply"]:t==="design"?[" BLOCKED: source writes are not allowed during design"," This phase does not allow source writes"," ALLOWED: run brainstorming, create the Design Doc, and run guard"," NEXT: finish the Design Doc, then run comet guard <change-name> design --apply to enter build"]:[" BLOCKED: source writes are not allowed during archive"," This phase does not allow source writes"," ALLOWED: confirm archive state and run the archive script"];return cn(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${t}`,` Target file: ${e}`,"",...n,""].join(`
|
|
258
|
+
`))}function ER(e){return cn(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," Current phase: build (workflow: full), but design_doc is empty",` Target file: ${e}`,""," BLOCKED: full workflow source writes require a recorded Design Doc"," This phase does not allow source writes until design_doc is recorded"," NEXT: return to design, create/link the Design Doc, then run guard again",""].join(`
|
|
259
|
+
`))}function RR(e,t){let n=t.superpowersSlot,i=n?Eh(t,n):null,r=n?t.phase!==n.phase?[` BLOCKED: ${n.wireField} cannot be first-written in phase ${t.phase}`,` Expected phase: ${n.phase}`," NEXT: resume the matching Comet phase or use an already recorded artifact path"]:i?[` BLOCKED: ${n.wireField} is already recorded for this change`,` Recorded path: ${i}`," NEXT: write the recorded artifact or explicitly correct the state path"]:[" BLOCKED: standard Superpowers artifact state is incomplete"," NEXT: validate the active change state, then retry the matching phase"]:[" BLOCKED: unmatched Superpowers artifact"," This docs/superpowers/ path does not match any active change artifact"," NEXT: use a recorded artifact path or a standard phase artifact directory"];return cn(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${t.phase}`,` Target file: ${e}`,"",...r,""].join(`
|
|
260
|
+
`))}function _R(e,t){return cn(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," BLOCKED: multiple active changes require a current change",` Target file: ${e}`,` Active changes: ${t.join(", ")}`,""," NEXT: run comet state select <change-name>, then retry the source write",""].join(`
|
|
261
261
|
`))}function Pr(e,t){return cn(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," BLOCKED: current change selection is stale or invalid",` Target file: ${e}`,` Reason: ${t}`,""," NEXT: run comet state select <change-name>, then retry the source write",""].join(`
|
|
262
|
-
`))}async function
|
|
262
|
+
`))}async function xR(e,t,n){let i=await uR(t,e),r;try{r=await Ee(e)}catch(c){return cn(2,`[COMET-HOOK] blocked: ${c instanceof Error?c.message:String(c)}`)}if(bR(i))return Pt(`${i} (whitelist: comet config)`);if(CR(i))return Pt(`${i} (whitelist: superpowers workspace)`);if(i==="CLAUDE.md"||i==="CHANGELOG.md"||i==="README.md"||vR(i))return Pt(`${i} (whitelist: root markdown)`);let s;try{s=await yR(i,e,r,n)}catch(c){return cn(2,`[COMET-HOOK] blocked: ${c instanceof Error?c.message:String(c)}`)}if(!s)return Pt("no active comet change");if("blockedResult"in s)return s.blockedResult;if(s.archived)return Pt(`${i} (own change archived)`);let o=s.phase,a=kR(i,o,`${N(e,r.openSpecRoot)}/`);if(a)return Pt(a);if(Sh(i,kh(e,r))){if(s.superpowersArtifact==="matched"&&Rh(s))return Pt(`${i} (phase: ${o}, superpowers)`);if(s.superpowersArtifact==="unmatched")return RR(i,s)}return o==="build"&&s.classic?.workflow==="full"&&!s.classic.designDoc?ER(i):o==="build"||o==="verify"?Pt(`${i} (phase: ${o})`):SR(i,o)}var _h=async e=>{let t=cR(e),n=aR();return n?xR(t,n):Pt("no file path in tool input")};var PR="comet.intent.v1";var OR=["start_change","resume_change","fix_bug","make_tweak","ask_question","unknown"],$R=["change_id","workflow","file_path","command","capability","bug_signal","risk_signal"],IR=["start","resume","continue","fix","modify","create","verify","archive","question","unknown"],xh=["full","hotfix","tweak"],AR=["small","medium","large","unknown"],NR=["full","hotfix","tweak","resume","ask_user","out_of_scope"],TR=["comet-open","comet-hotfix","comet-tweak","comet-design","comet-build","comet-verify","comet-archive"],jR=["user","repo","state"],mi=class extends Error{constructor(n){super(`Invalid CometIntentFrame:
|
|
263
263
|
${n.map(i=>`- ${i}`).join(`
|
|
264
|
-
`)}`);this.issues=n}issues};function Pe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ln(e,t,n,i){return typeof e!="string"||!t.includes(e)?(i.push(`${n} must be one of: ${t.join(", ")}`),null):e}function Kl(e,t,n,i){return e==null?null:ln(e,t,n,i)}function fi(e,t,n){return typeof e!="string"||e.trim()===""?(n.push(`${t} must be a non-empty string`),""):e}function Jl(e,t,n){return e==null?null:typeof e!="string"||e.trim()===""?(n.push(`${t} must be a non-empty string or null`),null):e}function di(e,t,n){return e==null?null:typeof e!="boolean"?(n.push(`${t} must be boolean or null`),null):e}function
|
|
265
|
-
Usage: comet-intent.mjs route --stdin`)}async function
|
|
266
|
-
`)}catch(s){if(s instanceof SyntaxError)return
|
|
267
|
-
`).toLowerCase()}function
|
|
268
|
-
Usage: comet-resume-probe.mjs probe --stdin`)}async function
|
|
269
|
-
`)}catch(o){return o instanceof SyntaxError?
|
|
270
|
-
`,a;try{await eu(e,s,o,"update-journal-temp",i);let c=await Ci(s,"file","Classic root move updated journal");a=await
|
|
271
|
-
`,"create-journal-temp",i),await Zo(e,r,t,"create-journal-commit",i)}catch(s){throw s.code==="EEXIST"?new Error("Classic root move is incomplete; use comet doctor --repair --strategy continue|rollback",{cause:s}):s}finally{await Tn(e,r,"cleanup-create-journal-temp").catch(()=>!1)}}function Xh(e){return jr("sha256").update(JSON.stringify({directories:e.directories,files:e.files,totalBytes:e.totalBytes})).digest("hex")}function Ar(e,t){return e<t?-1:e>t?1:0}function Ko(e,t){return e.every((n,i)=>i===0||t(e[i-1],n)<=0)}function Qh(e){return jr("sha256").update(JSON.stringify({source:e.source,target:e.target,staging:e.staging,artifactLayout:e.artifactLayout,sourceIdentity:e.sourceIdentity,targetInitialIdentity:e.targetInitialIdentity,targetInitialState:e.targetInitialState,fileCount:e.fileCount,directoryCount:e.directoryCount,totalBytes:e.totalBytes,manifestHash:e.manifestHash,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash})).digest("hex")}function t_(e){return jr("sha256").update(JSON.stringify({source:e.source,target:e.target,staging:Zl,targetInitialState:e.targetInitialState,fileCount:e.fileCount,directoryCount:e.directoryCount,totalBytes:e.totalBytes,manifestHash:e.manifestHash,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash})).digest("hex")}function zo(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Gl(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function n_(e){return"mtimeNs"in e&&typeof e.mtimeNs=="bigint"?e.mtimeNs:e.mtimeMs}function jn(e){return{dev:e.dev,ino:e.ino,birthtime:zo(e)}}function Ir(e){return String(e)}function Xo(e,t){let n=jn(e);if(!bn(n,n))throw new Error(`${t} filesystem does not expose a stable device and file identity; refusing an auditable root move`);return{dev:Ir(e.dev),ino:Ir(e.ino),birthtime:Ir(zo(e)),ctime:Ir(Gl(e)),mtime:Ir(n_(e))}}function i_(e,t,n){return t.entries.map(i=>{let r=Xo(i.stat,n);return{path:Xe(e,i.path)||".",dev:r.dev,ino:r.ino,birthtime:r.birthtime}})}function tu(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Zh(e,t){return e.length===t.length&&e.every((n,i)=>tu(n,t[i]))}async function zl(e,t,n){let i=await $e(e,t,n);return await U(i,n),i_(e,i,n)}function ta(e,t){let n=jn(e),i=jn(t);return bn(n,i)?Ae(n,i):Ae(n,i)&&zo(e)===zo(t)&&Gl(e)===Gl(t)&&e.size===t.size}function gi(e){return jr("sha256").update(e).digest("hex")}async function Nr(e,t,n,i,r){let s=await Y(e,Xe(e,t),n,{label:i,bigint:!0});if(r&&!ta(r,s.stat))throw new Error(`${i} changed while reading`);if(BigInt(s.stat.size)!==BigInt(s.bytes.byteLength))throw new Error(`${i} changed while reading`);return s.bytes}async function eg(e){let t=await kn(e,{allowPartialProject:!0});if(!t.document||!t.identity.exists||!t.identity.sha256)throw new Error(".comet/config.yaml does not exist");return t}async function nu(e){return(await eg(e)).identity.sha256}function r_(e){let t=e.value.classic;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("classic must be a mapping");let n=Gn({...e.value,classic:{...t,artifact_layout:"docs"}},e.classic?.language==="zh-CN"||e.native?.language==="zh-CN"?"zh-CN":"en");return jr("sha256").update(n).digest("hex")}async function na(e,t,n){let i=[],r=[],s=0;async function o(c,l){await bi(e,c,l||Xe(e,t),"directory");let f=await ZR(e,c,`tree:${l||Xe(e,t)}`,n);for(let u of f.sort((d,h)=>Ar(d.name,h.name))){let d=O.join(c,u.name),h=l?`${l}/${u.name}`:u.name,g=await te.lstat(d,{bigint:!0});if(g.isSymbolicLink())throw new Error(`Classic root move does not support symbolic links or junctions: ${h}`);if(g.isDirectory()){i.push(h),await o(d,h);continue}if(!g.isFile())throw new Error(`Classic root move supports only regular files and directories: ${h}`);if(await n?.afterSourceFileInspect?.(h),r.length+1>Yo)throw new Error(`Classic root move exceeds ${Yo} files`);let p=Vo-s,m=await Nr(e,d,Math.max(1,p),`Classic root move source file ${h}`,g);if(s+=m.byteLength,s>Vo)throw new Error(`Classic root move exceeds ${Vo} bytes`);r.push({path:h,size:m.byteLength,hash:gi(m)})}}await o(t,""),i.sort(Ar),r.sort((c,l)=>Ar(c.path,l.path));let a={directories:i,files:r,totalBytes:s};return{...a,hash:Xh(a)}}function iu(e,t){return e.hash===t.hash}async function s_(e,t,n){try{let i=await $e(e,t,"docs-target"),r=i.entries.at(-1);if(!r)throw new Error("Classic docs target identity is unavailable");let s=Xo(r.stat,"Classic docs target");await n?.afterDirectoryInspect?.("docs-target"),await U(i,"docs-target");let o=await te.readdir(t,{withFileTypes:!0});await U(i,"docs-target");let c=(await $e(e,t,"docs-target")).entries.at(-1),l=c?Xo(c.stat,"Classic docs target"):null;if(!l||!tu(s,l))throw new Error("Classic docs target changed after inspection");return o.length>0?{state:"non-empty",conflicts:["Classic docs target is not empty"],identity:l}:{state:"empty",conflicts:[],identity:l}}catch(i){if(i.code==="ENOENT")return{state:"missing",conflicts:[],identity:null};throw i}}async function o_(e){if(await _m(e),await Gt(e)!=="legacy")throw new Error("Classic root move requires classic.artifact_layout: legacy")}async function Xl(e,t={}){if(await ea(e),await o_(e),await Gt(e)!=="legacy")throw new Error("Classic root move requires the legacy layout");let n=yt(e,"legacy"),i=yt(e,"docs");if(!await Nn(e,n.openSpecRoot,"Classic legacy root"))throw new Error("Classic legacy root does not exist: openspec/");let r=await zl(e,n.openSpecRoot,"Classic legacy root identity"),s=await na(e,n.openSpecRoot,t.testHooks),o=await zl(e,n.openSpecRoot,"Classic legacy root identity");if(!Zh(r,o))throw new Error("Classic legacy root identity changed during migration preflight");let a=await s_(e,i.openSpecRoot,t.testHooks),c=await eg(e);await t.testHooks?.afterConfigSnapshot?.();let l=c.identity.sha256,f=r_(c.document),u={source:Xe(e,n.openSpecRoot),target:Xe(e,i.openSpecRoot),staging:Zl,artifactLayout:"legacy",sourceIdentity:o,targetInitialIdentity:a.identity,targetInitialState:a.state,fileCount:s.files.length,directoryCount:s.directories.length,totalBytes:s.totalBytes,manifestHash:s.hash,configPath:ce,originalConfigHash:l,expectedConfigHash:f};return{manifest:s,plan:{projectRoot:e,...u,configHash:l,planId:Qh(u),fileSummary:s.files.map(d=>({...d})),configChange:{from:"legacy",to:"docs"},conflicts:a.conflicts,blockers:[],pendingRecovery:null,historicalPointersPreserved:[...Jh],applyPreconditions:[...Uh],allowedRecoveryStrategies:[],readyToApply:a.conflicts.length===0}}}async function a_(e,t,n,i,r){await hi(e,n,"Classic root move staging root",r);for(let s of i.directories)await hi(e,O.join(n,...s.split("/")),`Classic root move staging directory ${s}`,r);for(let s of i.files){await r?.beforeSourceFileCopy?.(s.path);let o=O.join(t,...s.path.split("/")),a=await Nr(e,o,Math.max(1,s.size),`Classic root move source file ${s.path}`);if(a.byteLength!==s.size||gi(a)!==s.hash)throw new Error("Classic legacy root changed after migration preflight");let c=O.join(n,...s.path.split("/"));if(await hi(e,O.dirname(c),`Classic root move staging parent ${s.path}`,r),(await T(e,Xe(e,c),{label:`Classic root move staging file ${s.path}`,expected:"file"})).exists)throw new Error("Classic root move staging changed after migration preflight");await eu(e,c,a,`copy-file:${s.path}`,r);let f=await Nr(e,c,Math.max(1,s.size),`Classic root move staging file ${s.path}`);if(f.byteLength!==s.size||gi(f)!==s.hash)throw new Error("Classic root move staging verification failed")}}function Mn(e){return O.join(e,...Ql.split("/"))}function q(e){return new Error(`invalid Classic root move journal: ${e}`)}function wi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw q(`${t} must be an object`);return e}function Ln(e,t,n){let i=Object.keys(e).sort(),r=[...t].sort();if(JSON.stringify(i)!==JSON.stringify(r))throw q(`${n} fields are invalid`)}function Bh(e,t){if(typeof e!="string"||e.length===0||e.includes("\\"))throw q(`${t} is invalid`);let n=e.split("/");if(O.posix.isAbsolute(e)||n.some(i=>i===""||i==="."||i==="..")||O.posix.normalize(e)!==e)throw q(`${t} must stay inside the migration tree`);return e}function tg(e){let t=wi(e,"manifest");if(Ln(t,["directories","files","totalBytes","hash"],"manifest"),!Array.isArray(t.directories)||!Array.isArray(t.files)||!Number.isSafeInteger(t.totalBytes)||t.totalBytes<0||t.totalBytes>Vo||typeof t.hash!="string"||!ct.test(t.hash))throw q("manifest shape is invalid");let n=t.directories.map((f,u)=>Bh(f,`manifest path directories[${u}]`)),i=t.files.map((f,u)=>{let d=wi(f,`manifest.files[${u}]`);Ln(d,["path","size","hash"],`manifest.files[${u}]`);let h=Bh(d.path,`manifest path files[${u}]`);if(!Number.isSafeInteger(d.size)||d.size<0||typeof d.hash!="string"||!ct.test(d.hash))throw q(`manifest.files[${u}] is invalid`);return{path:h,size:d.size,hash:d.hash}});if(i.length>Yo)throw q(`manifest exceeds ${Yo} files`);let r=i.map(f=>f.path),s=new Set(n).size!==n.length||new Set(r).size!==r.length,o=Ko(n,Ar)&&Ko(r,Ar)||Ko(n,(f,u)=>f.localeCompare(u))&&Ko(r,(f,u)=>f.localeCompare(u));if(s||!o)throw q("manifest paths must be unique and sorted");let a=i.reduce((f,u)=>f+u.size,0);if(a!==t.totalBytes)throw q("manifest totalBytes does not match its files");let c={directories:n,files:i,totalBytes:a},l=Xh(c);if(l!==t.hash)throw q("manifest hash is invalid");return{...c,hash:l}}function ng(e,t){let n=wi(e,t);Ln(n,["dev","ino","birthtime"],t);let i=/^-?[0-9]+$/u;for(let r of["dev","ino","birthtime"])if(typeof n[r]!="string"||!i.test(n[r]))throw q(`${t}.${r} is invalid`);if(n.dev==="0"||n.ino==="0")throw q(`${t} does not contain a stable filesystem identity`);return{dev:n.dev,ino:n.ino,birthtime:n.birthtime}}function c_(e,t){let n=wi(e,t);Ln(n,["dev","ino","birthtime","ctime","mtime"],t);let i=ng({dev:n.dev,ino:n.ino,birthtime:n.birthtime},t),r=/^-?[0-9]+$/u;if(typeof n.ctime!="string"||!r.test(n.ctime)||typeof n.mtime!="string"||!r.test(n.mtime))throw q(`${t} timestamps are invalid`);return{...i,ctime:n.ctime,mtime:n.mtime}}function l_(e){if(!Array.isArray(e)||e.length!==2)throw q("sourceIdentity must bind the project root and openspec root");let t=[".","openspec"];return e.map((n,i)=>{let r=wi(n,`sourceIdentity[${i}]`);if(Ln(r,["path","dev","ino","birthtime"],`sourceIdentity[${i}]`),r.path!==t[i])throw q(`sourceIdentity[${i}].path is invalid`);let s={dev:r.dev,ino:r.ino,birthtime:r.birthtime};return{path:t[i],...ng(s,`sourceIdentity[${i}]`)}})}function u_(e){if(Ln(e,["schema","id","stage","source","target","staging","configPath","originalConfigHash","expectedConfigHash","planId","targetInitialState","manifest"],"root"),typeof e.id!="string"||!Vh.test(e.id))throw q("id is invalid");if(e.stage!=="copying"&&e.stage!=="ready"&&e.stage!=="switched"&&e.stage!=="configured")throw q("stage is invalid");let t=`.comet/transactions/classic-root-move/${e.id}/openspec`;if(e.source!=="openspec"||e.target!=="docs/openspec"||e.staging!==t)throw q("source, target, and staging must use the managed project paths");if(e.configPath!==ce||typeof e.originalConfigHash!="string"||!ct.test(e.originalConfigHash)||typeof e.expectedConfigHash!="string"||!ct.test(e.expectedConfigHash)||typeof e.planId!="string"||!ct.test(e.planId))throw q("config path, config hashes, or planId is invalid");if(e.targetInitialState!=="missing"&&e.targetInitialState!=="empty")throw q("targetInitialState is invalid");let n=e.targetInitialState,i=tg(e.manifest),r={source:e.source,target:e.target,targetInitialState:n,fileCount:i.files.length,directoryCount:i.directories.length,totalBytes:i.totalBytes,manifestHash:i.hash,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash};if(t_(r)!==e.planId)throw q("planId does not match the bound config and tree");return{schema:"comet.classic-root-move.v1",id:e.id,stage:e.stage,source:e.source,target:e.target,staging:e.staging,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash,planId:e.planId,targetInitialState:n,manifest:i}}function f_(e){if(Ln(e,["schema","id","stage","source","target","staging","artifactLayout","sourceIdentity","targetInitialIdentity","configPath","originalConfigHash","expectedConfigHash","planId","approvedPlanId","targetInitialState","manifest"],"root"),typeof e.id!="string"||!Vh.test(e.id))throw q("id is invalid");if(e.stage!=="locked"&&e.stage!=="copying"&&e.stage!=="ready"&&e.stage!=="switched"&&e.stage!=="configured")throw q("stage is invalid");let t=`.comet/transactions/classic-root-move/${e.id}/openspec`;if(e.source!=="openspec"||e.target!=="docs/openspec"||e.staging!==t)throw q("source, target, and staging must use the managed project paths");if(e.artifactLayout!=="legacy")throw q("artifactLayout must be legacy");let n=l_(e.sourceIdentity);if(e.configPath!==ce||typeof e.originalConfigHash!="string"||!ct.test(e.originalConfigHash)||typeof e.expectedConfigHash!="string"||!ct.test(e.expectedConfigHash)||typeof e.planId!="string"||!ct.test(e.planId)||typeof e.approvedPlanId!="string"||!ct.test(e.approvedPlanId))throw q("config path, config hashes, planId, or approvedPlanId is invalid");let i=e.targetInitialState;if(i!=="missing"&&i!=="empty"&&!(e.stage==="locked"&&i==="non-empty"))throw q("targetInitialState is invalid");let r=e.targetInitialIdentity===null?null:c_(e.targetInitialIdentity,"targetInitialIdentity");if(i==="missing"&&r!==null||i!=="missing"&&r===null)throw q("targetInitialIdentity does not match targetInitialState");let s=tg(e.manifest),o={source:e.source,target:e.target,staging:Zl,artifactLayout:"legacy",sourceIdentity:n,targetInitialIdentity:r,targetInitialState:i,fileCount:s.files.length,directoryCount:s.directories.length,totalBytes:s.totalBytes,manifestHash:s.hash,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash};if(Qh(o)!==e.planId)throw q("planId does not match the bound config and tree");if(e.stage!=="locked"&&e.approvedPlanId!==e.planId)throw q("approvedPlanId does not match the executable plan");return{schema:"comet.classic-root-move.v2",id:e.id,stage:e.stage,source:e.source,target:e.target,staging:e.staging,artifactLayout:"legacy",sourceIdentity:n,targetInitialIdentity:r,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash,planId:e.planId,approvedPlanId:e.approvedPlanId,targetInitialState:i,manifest:s}}function d_(e){let t=wi(e,"root");if(t.schema==="comet.classic-root-move.v1")return u_(t);if(t.schema==="comet.classic-root-move.v2")return f_(t);throw q("schema is unsupported")}async function yi(e,t){return ru(e,Mn(e),Ql,t?.afterJournalInspect)}async function ru(e,t,n,i){await bi(e,t,n,"file");try{let r=await te.lstat(t,{bigint:!0});if(!r.isFile()||r.isSymbolicLink()||r.size>BigInt(Dh))throw q("journal must be a bounded regular file");await i?.();let s=await Nr(e,t,Dh,"Classic root move journal",r),o=d_(JSON.parse(s.toString("utf8")));return Object.defineProperty(o,Yh,{value:{fileIdentity:r,contentHash:gi(s)},enumerable:!1}),o}catch(r){if(r.code==="ENOENT")return null;throw r}}function vi(e){let t=e[Yh];if(!t)throw new Error("Classic root move journal has no ownership claim");return t}function su(e,t){let n=vi(e),i=vi(t);return ta(n.fileIdentity,i.fileIdentity)&&n.contentHash===i.contentHash&&e.schema===t.schema&&e.id===t.id&&e.stage===t.stage&&e.planId===t.planId}async function Wh(e,t){let n=await ru(e,Mn(e),Ql);if(!n||!su(t,n))throw new Error("Classic root move journal ownership changed")}async function ig(e,t,n,i){let r=Mn(e);try{await Zo(e,t.file,r,`${n}-publish`,i)}catch(o){if(o.code==="EEXIST")return!1;throw o}let s=await yi(e);if(!s||!su(t.journal,s))throw new Error("Classic root move journal ownership changed while restoring quarantine");return await Tn(e,t.file,`${n}-cleanup-quarantine`,i,{expectedIdentity:vi(t.journal).fileIdentity}),!0}async function rg(e,t,n,i){let r=Mn(e),s=`${r}.${t.id}.${Qo()}.quarantine`;await Wh(e,t);let o=await $e(e,O.dirname(r),`Classic root move ${n} quarantine`);await i?.beforeMutation?.(`${n}-quarantine`),await U(o,`Classic root move ${n} quarantine`),await Wh(e,t),await te.rename(r,s),await U(o,`Classic root move ${n} quarantine`);let a=await ru(e,s,Xe(e,s)).catch(async c=>{throw await Hh(e,s,`${n}-restore-unverified`,i).catch(()=>!1),new Error("Classic root move journal ownership changed while quarantining",{cause:c})});if(!a||!su(t,a))throw await Hh(e,s,`${n}-restore-successor`,i).catch(()=>!1),new Error("Classic root move journal ownership changed while quarantining");return await i?.afterJournalQuarantine?.(n),{file:s,journal:a}}async function Hh(e,t,n,i){let r=Mn(e),s;try{s=await Ci(t,"file",`Classic root move ${n}`)}catch(o){if(o.code==="ENOENT")return!1;throw o}try{await Zo(e,t,r,`${n}-publish`,i)}catch(o){if(o.code==="EEXIST")return!1;throw o}return await Tn(e,t,`${n}-cleanup-quarantine`,i,{expectedIdentity:s}),!0}async function sg(e,t,n,i){let r=await rg(e,t,n,i);try{if(!await Tn(e,r.file,`${n}-quarantined`,i,{expectedIdentity:vi(r.journal).fileIdentity}))throw new Error("Classic root move quarantined journal disappeared before removal");return!0}catch(s){throw await ig(e,r,`${n}-restore`,i).catch(()=>!1),s}}async function Jo(e,t,n,i){if(t.schema==="comet.classic-root-move.v1"&&n==="locked")throw new Error("Legacy Classic root move journals do not support the locked stage");let r={...t,stage:n};return zh(e,t,r,i)}function og(e,t){let n={legacy:yt(e,"legacy"),docs:yt(e,"docs")},i=O.join(e,".comet","transactions","classic-root-move",t.id);return{source:n.legacy.openSpecRoot,target:n.docs.openSpecRoot,staging:O.join(i,"openspec"),quarantine:O.join(i,"legacy-source"),transactionRoot:i}}async function Tr(e,t,n){if(!await Nn(e,t,"Classic root move tree"))return"missing";try{return iu(await na(e,t),n)?"match":"mismatch"}catch{return"mismatch"}}async function ou(e,t,n){if(!await Nn(e,t,"Classic root move target"))return"missing";try{let i=await na(e,t);return iu(i,n)?"match":i.directories.length===0&&i.files.length===0?"empty":"mismatch"}catch{return"mismatch"}}async function ag(e,t,n){if(!await Nn(e,t,"Classic root move manifest tree"))return{status:"missing"};try{let i=await na(e,t);if(iu(i,n))return{status:"complete",actual:i};let r=new Set(n.directories),s=new Map(n.files.map(o=>[o.path,o]));if(i.directories.some(o=>!r.has(o)))return{status:"mismatch"};for(let o of i.files){let a=s.get(o.path);if(!a||a.size!==o.size||a.hash!==o.hash)return{status:"mismatch"}}return{status:"partial",actual:i}}catch{return{status:"mismatch"}}}async function m_(e,t,n,i,r="remove-quarantine"){let s=await ag(e,t,n);if(s.status==="missing")return;if(s.status==="mismatch"||!s.actual)throw new Error("Classic quarantine contains unknown or changed content; files were preserved");for(let a of s.actual.files){let c=O.join(t,...a.path.split("/")),l;try{l=await te.lstat(c,{bigint:!0})}catch(u){if(u.code==="ENOENT")continue;throw u}let f=l.isFile()&&!l.isSymbolicLink()?await Nr(e,c,Math.max(1,a.size),`Classic root move quarantine file ${a.path}`,l):null;if(!f||f.byteLength!==a.size||gi(f)!==a.hash)throw new Error("Classic quarantine contains unknown or changed content; files were preserved");await Tn(e,c,`${r}-file:${a.path}`,i)}let o=[...s.actual.directories].sort((a,c)=>{let l=c.split("/").length-a.split("/").length;return l===0?c.localeCompare(a):l});for(let a of o){let c=O.join(t,...a.split("/"));await Go(e,c,`${r}-directory:${a}`,i)}await Go(e,t,`${r}-root`,i)}async function p_(e,t,n,i){let r=await ou(e,t,n.manifest);if(n.targetInitialState==="missing"){if(r!=="missing")throw new Error("Classic docs target changed after migration preflight");return}if(r==="empty"){if(n.schema==="comet.classic-root-move.v2"&&!n.targetInitialIdentity)throw new Error("Classic docs target identity is missing from the approved plan");await Go(e,t,"remove-empty-target",i,n.schema==="comet.classic-root-move.v2"?n.targetInitialIdentity??void 0:void 0);return}if(r!=="missing")throw new Error("Classic docs target changed after migration preflight")}async function Uo(e,t,n){if(n.schema==="comet.classic-root-move.v1")return;let i=await zl(e,t,"Classic legacy root identity");if(!Zh(i,n.sourceIdentity))throw new Error("Classic legacy root identity changed after migration preflight")}async function Yl(e,t){if(await nu(e)!==t.originalConfigHash)throw new Error("Classic project config changed after migration preflight");if(await Gt(e)!=="legacy")throw new Error("Classic project config changed after migration preflight")}async function Kh(e,t){if(await nu(e)!==t.expectedConfigHash)throw new Error("Classic project config does not match the expected post-switch config hash");if(await Gt(e)!=="docs")throw new Error("Classic project config does not match the expected post-switch config hash")}async function An(e,t,n,i){if(await Tr(e,t,n)!=="match")throw new Error(i)}async function h_(e,t,n){if(t.stage==="locked")throw new Error("Classic root move locked preflight must be approved before execution");await ea(e,t.id);let{source:i,target:r,staging:s,quarantine:o,transactionRoot:a}=og(e,t),c=t;if(c.stage==="copying"){await Yl(e,c),await Uo(e,i,c),await An(e,i,c.manifest,"Classic legacy root changed after migration preflight"),await p_(e,r,c,n);let l=await Tr(e,s,c.manifest);if(l==="mismatch")throw new Error("Classic root move staging changed after migration preflight");l==="missing"&&await a_(e,i,s,c.manifest,n),await An(e,s,c.manifest,"Classic root move staging verification failed"),c=await Jo(e,c,"ready",n)}if(c.stage==="ready"){await Yl(e,c),await Uo(e,i,c),await An(e,i,c.manifest,"Classic legacy root changed after migration preflight");let l=await Tr(e,s,c.manifest),f=await ou(e,r,c.manifest);if(l==="missing"&&f==="match")c=await Jo(e,c,"switched",n);else{if(l!=="match")throw new Error("Classic root move staging changed after migration preflight");if(f==="mismatch"||f==="empty")throw new Error("Classic docs target changed after migration preflight");f==="missing"&&(await hi(e,O.dirname(r),"Classic docs target parent",n),await Fh(e,s,r,"rename-staging-target",n),c=await Jo(e,c,"switched",n))}}if(c.stage==="switched"){await Uo(e,i,c),await An(e,i,c.manifest,"Classic legacy root changed before config switch"),await An(e,r,c.manifest,"Classic docs target verification failed after switch");let l=await Gt(e);if(l==="legacy")await Yl(e,c),await xm(e,"docs",{expectedIdentity:{exists:!0,sha256:c.originalConfigHash}});else if(l!=="docs")throw new Error("Classic project config changed after migration preflight");await Kh(e,c),c=await Jo(e,c,"configured",n)}if(c.stage!=="configured")throw new Error(`Unsupported Classic root move stage: ${c.stage}`);if(await Kh(e,c),await An(e,r,c.manifest,"Classic docs target verification failed after config switch"),await Nn(e,i,"Classic legacy root")){if(await Uo(e,i,c),await An(e,i,c.manifest,"Classic legacy root changed before cleanup; both roots were preserved"),await Nn(e,o,"Classic root move quarantine"))throw new Error("Classic root move quarantine conflicts with the legacy root");await Fh(e,i,o,"rename-source-quarantine",n)}await Nn(e,o,"Classic root move quarantine")&&await m_(e,o,c.manifest,n),await Go(e,a,"remove-transaction-root",n),await sg(e,c,"remove-journal",n)}async function g_(e,t){if(await ea(e,t.id),t.stage==="locked")return{allowedStrategies:["rollback"],reason:"the locked apply preflight was not approved for execution"};let{source:n,target:i,staging:r,quarantine:s}=og(e,t),o=await Gt(e),a=await nu(e),c=o==="legacy"&&a===t.originalConfigHash,l=o==="docs"&&a===t.expectedConfigHash,[f,u,d,h]=await Promise.all([Tr(e,n,t.manifest),ou(e,i,t.manifest),Tr(e,r,t.manifest),ag(e,s,t.manifest)]),g=h.status;if(f==="mismatch")return{allowedStrategies:[],reason:"Classic legacy root changed after migration preflight"};if(u==="mismatch")return{allowedStrategies:[],reason:"Classic docs target changed after migration preflight"};if(d==="mismatch")return{allowedStrategies:[],reason:"Classic staging changed after migration preflight"};if(g==="mismatch")return{allowedStrategies:[],reason:"Classic quarantine contains unknown or changed content"};if(t.stage==="configured"||o==="docs")return l?u==="match"&&(f==="match"&&g==="missing"||f==="missing"&&(g==="missing"||g==="complete"||g==="partial"))?{allowedStrategies:["continue"]}:{allowedStrategies:[],reason:"the configured migration trees are incomplete"}:{allowedStrategies:[],reason:"project config does not match the expected post-switch config hash"};if(!c)return{allowedStrategies:[],reason:"project config changed after migration preflight"};let p=f==="match",m=d==="match"||d==="missing",w=u==="match"||u==="missing"||t.targetInitialState==="empty"&&u==="empty";return!p||!m||!w||g!=="missing"?{allowedStrategies:[],reason:"the migration trees are not recoverable"}:{allowedStrategies:["continue","rollback"]}}async function cg(e,t={}){let n=await ue(e),i=await yi(n,t.testHooks);if(i){let r=await w_(n);if(!r)throw new Error("Classic root move journal disappeared during inspection");return{projectRoot:n,source:i.source,target:i.target,staging:i.staging,artifactLayout:"legacy",sourceIdentity:i.schema==="comet.classic-root-move.v2"?i.sourceIdentity.map(s=>({...s})):[],targetInitialIdentity:i.schema==="comet.classic-root-move.v2"&&i.targetInitialIdentity?{...i.targetInitialIdentity}:null,fileCount:i.manifest.files.length,directoryCount:i.manifest.directories.length,totalBytes:i.manifest.totalBytes,manifestHash:i.manifest.hash,configPath:i.configPath,configHash:i.originalConfigHash,originalConfigHash:i.originalConfigHash,expectedConfigHash:i.expectedConfigHash,planId:i.planId,fileSummary:i.manifest.files.map(s=>({...s})),configChange:{from:"legacy",to:"docs"},conflicts:r.reason?[r.reason]:[],blockers:[`pending Classic root move: ${i.id} at ${i.stage}`],pendingRecovery:r,historicalPointersPreserved:[...Jh],applyPreconditions:[...Uh],allowedRecoveryStrategies:[...r.allowedStrategies],targetInitialState:i.targetInitialState,readyToApply:!1}}return(await Xl(n,t)).plan}async function lg(e,t={}){let n=await ue(e),i=await yi(n,t.testHooks);if(i)throw new Error(`Classic root move ${i.id} is incomplete; use comet doctor --repair --strategy continue|rollback`);let r=await Xl(n),s=t.planId??r.plan.planId;if(!ct.test(s))throw new Error("Classic root move apply received an invalid internal plan ID");let o=Qo();await ea(n,o);let a={schema:"comet.classic-root-move.v2",id:o,stage:"locked",source:r.plan.source,target:r.plan.target,staging:`.comet/transactions/classic-root-move/${o}/openspec`,artifactLayout:r.plan.artifactLayout,sourceIdentity:r.plan.sourceIdentity.map(f=>({...f})),targetInitialIdentity:r.plan.targetInitialIdentity?{...r.plan.targetInitialIdentity}:null,configPath:ce,originalConfigHash:r.plan.originalConfigHash,expectedConfigHash:r.plan.expectedConfigHash,planId:r.plan.planId,approvedPlanId:s,targetInitialState:r.plan.targetInitialState,manifest:r.manifest};await e_(n,Mn(n),a,t.testHooks);let c=await yi(n);if(!c||c.id!==o||c.stage!=="locked")throw new Error("Classic root move lock ownership changed before locked preflight");let l=!1;try{let f=await Xl(n,t),u=f.plan;if(u.planId!==s)throw new Error(`Classic root move plan changed since dry-run: approved ${s}, current ${u.planId}`);if(!u.readyToApply)throw new Error(`Classic root move apply is blocked: ${[...u.conflicts,...u.blockers].join("; ")}`);if(u.targetInitialState==="non-empty")throw new Error("Classic root move apply is blocked: Classic docs target is not empty");let d={schema:"comet.classic-root-move.v2",id:o,stage:"copying",source:u.source,target:u.target,staging:`.comet/transactions/classic-root-move/${o}/openspec`,artifactLayout:u.artifactLayout,sourceIdentity:u.sourceIdentity.map(g=>({...g})),targetInitialIdentity:u.targetInitialIdentity?{...u.targetInitialIdentity}:null,configPath:ce,originalConfigHash:u.originalConfigHash,expectedConfigHash:u.expectedConfigHash,planId:u.planId,approvedPlanId:s,targetInitialState:u.targetInitialState,manifest:f.manifest},h=await zh(n,c,d,t.testHooks);return l=!0,await h_(n,h,t.testHooks),{...u,staging:d.staging}}catch(f){throw l||await sg(n,c,"remove-rejected-lock",t.testHooks).catch(()=>!1),f}}async function w_(e,t={}){let n=await yi(e,t.testHooks);if(!n)return null;let i=await g_(e,n);return{id:n.id,stage:n.stage,source:n.source,target:n.target,staging:n.staging,planId:n.planId,...i}}wt();function ug(e="en"){return{exitCode:64,stderr:e==="zh-CN"?"用法:comet classic root show | comet classic root move docs --dry-run | comet classic root move docs --apply":"Usage: comet classic root show | comet classic root move docs --dry-run | comet classic root move docs --apply"}}function y_(e){return e?.classic?.language==="en"?"en":"zh-CN"}function v_(e,t){let n=e instanceof Error?e.message:String(e);return t==="en"?n:n==="invalid Classic root move journal: manifest paths must be unique and sorted"?"Classic 根目录迁移失败:迁移记录中的清单路径必须唯一且按顺序排列":n.startsWith("invalid Classic root move journal:")?"Classic 根目录迁移失败:迁移记录格式或内容无效,请运行 comet doctor 检查恢复状态":"Classic 根目录迁移失败:迁移过程中发生错误,请运行 comet doctor 检查迁移状态"}function fg(e,t,n="en"){let i=n==="zh-CN",r=d=>d.length>0?d.join("; "):i?"无":"none",s=d=>{if(!i)return d;let h=/^pending Classic root move: (.+) at (.+)$/u.exec(d);return h?`存在待恢复的 Classic 根目录迁移:${h[1]},阶段 ${h[2]}`:{"Classic docs target is not empty":"docs 目标目录非空","the locked apply preflight was not approved for execution":"已锁定的迁移预检尚未获准执行","Classic legacy root changed after migration preflight":"迁移预检后 legacy 根目录发生变化","Classic docs target changed after migration preflight":"迁移预检后 docs 目标目录发生变化","Classic staging changed after migration preflight":"迁移预检后暂存目录发生变化","Classic quarantine contains unknown or changed content":"隔离目录包含未知或已变化的内容","project config does not match the expected post-switch config hash":"项目配置与切换后的预期配置哈希不一致","the configured migration trees are incomplete":"已切换配置对应的迁移目录不完整","project config changed after migration preflight":"迁移预检后项目配置发生变化","the migration trees are not recoverable":"迁移目录当前无法安全恢复"}[d]??"迁移状态存在无法识别的冲突,请运行 comet doctor 检查恢复状态"},o=(d,h)=>h.length===0?[`${d}: ${i?"无":"none"}`]:[`${d}:`,...h.map(g=>`- ${s(g)}`)],a=i?{missing:"缺失",empty:"空目录","non-empty":"非空目录"}[e.targetInitialState]:e.targetInitialState,c=i?"handoff 哈希;运行状态;检查点;轨迹;已归档证据与产物指针":e.historicalPointersPreserved.join("; "),l=i?"内部迁移身份仍与布局、源目录、清单、目标目录和配置一致;不存在待恢复的根迁移事务;目标仍然缺失或为已绑定的空目录;所有迁移路径仍受保护":e.applyPreconditions.join("; "),f=i?e.allowedRecoveryStrategies.map(d=>d==="continue"?"继续":"回滚"):e.allowedRecoveryStrategies,u=[t==="dry-run"?i?"Classic 根目录迁移现状":"Classic root move status":i?"Classic 根目录迁移完成":"Classic root move complete",...t==="dry-run"?[i?"说明:仅查看现状,未修改任何文件。":"Note: Inspection only; no files were changed."]:[],`${i?"源目录":"source"}: ${e.source}`,`${i?"目标目录":"target"}: ${e.target}`,`${i?"暂存目录":"staging"}: ${e.staging}`,`${i?"当前布局":"artifact layout"}: ${e.artifactLayout}`,`${i?"源目录身份":"source identity"}: ${JSON.stringify(e.sourceIdentity)}`,`${i?"目标初始身份":"target initial identity"}: ${e.targetInitialIdentity?JSON.stringify(e.targetInitialIdentity):i?"缺失":"missing"}`,`${i?"文件数":"files"}: ${e.fileCount}`,`${i?"目录数":"directories"}: ${e.directoryCount}`,`${i?"总字节数":"bytes"}: ${e.totalBytes}`,`${i?"清单哈希":"manifest"}: ${e.manifestHash}`,...e.fileSummary.map(d=>`${i?"文件":"file"}: ${d.path} ${d.size} ${d.hash}`),`${i?"配置变更":"config change"}: ${e.configChange.from} -> ${e.configChange.to}`,`${i?"配置路径":"config path"}: ${e.configPath}`,`${i?"配置哈希":"config"}: ${e.configHash}`,`${i?"原配置哈希":"original config"}: ${e.originalConfigHash}`,`${i?"预期配置哈希":"expected config"}: ${e.expectedConfigHash}`,`${i?"目标初始状态":"target initial state"}: ${a}`,...o(i?"冲突":"conflicts",e.conflicts),...o(i?"阻塞项":"blockers",e.blockers),`${i?"待恢复事务":"pending recovery"}: ${e.pendingRecovery?`${e.pendingRecovery.id} ${i?"位于阶段":"at"} ${e.pendingRecovery.stage}`:i?"无":"none"}`,`${i?"保留历史指针":"historical pointers preserved"}: ${c}`,`${i?"执行前提":"apply preconditions"}: ${l}`,`${i?"允许的恢复策略":"allowed recovery strategies"}: ${r(f)}`,`${i?"可执行迁移":"ready to apply"}: ${e.readyToApply?i?"是":"yes":i?"否":"no"}`];return t==="dry-run"?u.push(e.readyToApply?i?"下一步:运行 comet classic root move docs --apply 执行迁移。":"Next: run comet classic root move docs --apply to apply the migration.":i?"下一步:请先解决上述冲突或阻塞项。":"Next: resolve the conflicts or blockers above before applying."):u.push(i?"结果:迁移已完成。":"Result: Migration completed."),`${u.join(`
|
|
264
|
+
`)}`);this.issues=n}issues};function Pe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ln(e,t,n,i){return typeof e!="string"||!t.includes(e)?(i.push(`${n} must be one of: ${t.join(", ")}`),null):e}function Kl(e,t,n,i){return e==null?null:ln(e,t,n,i)}function fi(e,t,n){return typeof e!="string"||e.trim()===""?(n.push(`${t} must be a non-empty string`),""):e}function Jl(e,t,n){return e==null?null:typeof e!="string"||e.trim()===""?(n.push(`${t} must be a non-empty string or null`),null):e}function di(e,t,n){return e==null?null:typeof e!="boolean"?(n.push(`${t} must be boolean or null`),null):e}function Ph(e,t,n){return typeof e!="number"||Number.isNaN(e)||e<0||e>1?(n.push(`${t} must be a number between 0 and 1`),0):e}function LR(e,t,n){return typeof e!="number"||!Number.isInteger(e)||e<0?(n.push(`${t} must be a non-negative integer`),0):e}function MR(e){let t=[];if(!Pe(e))throw new mi(["frame must be an object"]);let n=Pe(e.intent)?e.intent:{};Pe(e.intent)||t.push("intent must be an object");let i=Pe(e.slots)?e.slots:{};Pe(e.slots)||t.push("slots must be an object");let r=Pe(e.context)?e.context:{};Pe(e.context)||t.push("context must be an object");let s=Pe(e.proposed_route)?e.proposed_route:{};Pe(e.proposed_route)||t.push("proposed_route must be an object");let o=e.entities===void 0?[]:Array.isArray(e.entities)?e.entities:[];e.entities!==void 0&&!Array.isArray(e.entities)&&t.push("entities must be an array");let a=Array.isArray(e.evidence)?e.evidence:[];Array.isArray(e.evidence)||t.push("evidence must be an array");let c={schema_version:ln(e.schema_version,[PR],"schema_version",t),utterance:fi(e.utterance,"utterance",t),locale:e.locale===void 0?"unknown":fi(e.locale,"locale",t),intent:{name:ln(n.name,OR,"intent.name",t)??"unknown",confidence:Ph(n.confidence,"intent.confidence",t)},entities:o.map((l,f)=>{let u=Pe(l)?l:{};return Pe(l)||t.push(`entities[${f}] must be an object`),{type:ln(u.type,$R,`entities[${f}].type`,t)??"risk_signal",value:fi(u.value,`entities[${f}].value`,t),text:fi(u.text,`entities[${f}].text`,t)}}),slots:{requested_action:ln(i.requested_action,IR,"slots.requested_action",t)??"unknown",workflow_candidate:Kl(i.workflow_candidate,xh,"slots.workflow_candidate",t),user_explicit_workflow:Kl(i.user_explicit_workflow,xh,"slots.user_explicit_workflow",t),change_id:Jl(i.change_id,"slots.change_id",t),target_area:Jl(i.target_area,"slots.target_area",t),scope:i.scope===void 0?"unknown":ln(i.scope,AR,"slots.scope",t)??"unknown",existing_behavior:di(i.existing_behavior,"slots.existing_behavior",t),new_capability:di(i.new_capability,"slots.new_capability",t),public_api_change:di(i.public_api_change,"slots.public_api_change",t),schema_change:di(i.schema_change,"slots.schema_change",t),cross_module_change:di(i.cross_module_change,"slots.cross_module_change",t)},context:{active_changes_count:LR(r.active_changes_count,"context.active_changes_count",t),active_change_names:Pe(r)?Array.isArray(r.active_change_names)?r.active_change_names.every(l=>typeof l=="string")?r.active_change_names:(t.push("context.active_change_names must only contain strings"),[]):(t.push("context.active_change_names must be an array"),[]):[],dirty_worktree:di(r.dirty_worktree,"context.dirty_worktree",t)},evidence:a.map((l,f)=>{let u=Pe(l)?l:{};return Pe(l)||t.push(`evidence[${f}] must be an object`),{field:fi(u.field,`evidence[${f}].field`,t),quote:fi(u.quote,`evidence[${f}].quote`,t),source:ln(u.source,jR,`evidence[${f}].source`,t)??"user"}}),proposed_route:{name:ln(s.name,NR,"proposed_route.name",t)??"ask_user",next_skill:Kl(s.next_skill,TR,"proposed_route.next_skill",t),confidence:Ph(s.confidence,"proposed_route.confidence",t),requires_confirmation:typeof s.requires_confirmation=="boolean"?s.requires_confirmation:!0,fallback_reason:Jl(s.fallback_reason,"proposed_route.fallback_reason",t)}};if(t.length>0)throw new mi(t);return c}function Ul(e,t){return e.evidence.some(n=>n.field===t&&n.quote.trim()!=="")}function Oh(e){return e.slots.new_capability===!0||e.slots.public_api_change===!0||e.slots.schema_change===!0||e.slots.cross_module_change===!0}function In(e,t,n=null){return{name:e,next_skill:{full:"comet-open",hotfix:"comet-hotfix",tweak:"comet-tweak",resume:null,ask_user:null,out_of_scope:null}[e],confidence:t,requires_confirmation:e==="ask_user"||e==="out_of_scope",fallback_reason:n}}function $r(e){return In("ask_user",.5,e)}function $h(e,t){return In(e,t)}function Ih(e){let t=MR(e),n=[],i=t.intent.confidence,r;return t.intent.confidence<.7?r=$r(`intent confidence ${t.intent.confidence} is below ${.7}`):(t.intent.name==="resume_change"||t.slots.requested_action==="resume"||t.slots.requested_action==="continue")&&!t.slots.change_id&&t.context.active_changes_count>1?r=$r("multiple active changes require an explicit change_id"):(t.intent.name==="resume_change"||t.slots.requested_action==="resume"||t.slots.requested_action==="continue")&&t.slots.change_id?r=t.context.active_change_names.includes(t.slots.change_id)?In("resume",i):$r(`change_id '${t.slots.change_id}' is not in active_change_names`):t.intent.name==="ask_question"||t.slots.requested_action==="question"?r=In("out_of_scope",i,"user asked a question without requesting a Comet workflow"):t.slots.user_explicit_workflow&&t.slots.user_explicit_workflow!=="full"&&Oh(t)?r=$r(`explicit workflow '${t.slots.user_explicit_workflow}' conflicts with risk signals`):t.slots.user_explicit_workflow?r=$h(t.slots.user_explicit_workflow,i):Oh(t)?r=In("full",i):t.intent.name==="fix_bug"&&t.slots.existing_behavior===!0&&Ul(t,"slots.workflow_candidate")?r=In("hotfix",i):t.intent.name==="make_tweak"&&t.slots.workflow_candidate==="tweak"&&Ul(t,"slots.workflow_candidate")?r=In("tweak",i):t.slots.workflow_candidate&&Ul(t,"slots.workflow_candidate")?r=$h(t.slots.workflow_candidate,i):r=$r("workflow_candidate evidence is missing or route is ambiguous"),r.name!==t.proposed_route.name&&n.push(`agent proposed_route '${t.proposed_route.name}' normalized to '${r.name}'`),r.next_skill!==t.proposed_route.next_skill&&n.push(`agent proposed_route next_skill '${t.proposed_route.next_skill}' normalized to '${r.next_skill}'`),r.requires_confirmation!==t.proposed_route.requires_confirmation&&n.push(`agent proposed_route requires_confirmation '${t.proposed_route.requires_confirmation}' normalized to '${r.requires_confirmation}'`),r.fallback_reason!==t.proposed_route.fallback_reason&&n.push(`agent proposed_route fallback_reason '${t.proposed_route.fallback_reason}' normalized to '${r.fallback_reason}'`),{route:r,diagnostics:n,normalizedFrame:{...t,route:r}}}function Ho(e,t,n){return{exitCode:e,...t===void 0?{}:{stdout:t},...n===void 0?{}:{stderr:n}}}function Ah(){return Ho(64,void 0,`Usage: comet-intent.mjs route <frame-json>
|
|
265
|
+
Usage: comet-intent.mjs route --stdin`)}async function qR(){let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Buffer.concat(e).toString("utf8")}var Nh=async(e,t)=>{let[n,i]=e;if(n!=="route")return Ah();let r=i==="--stdin"?await qR():i;if(!r)return Ah();try{let s=Ih(JSON.parse(r));return Ho(0,`${JSON.stringify(s,null,2)}
|
|
266
|
+
`)}catch(s){if(s instanceof SyntaxError)return Ho(1,void 0,`Invalid JSON: ${s.message}`);if(s instanceof mi)return Ho(1,void 0,s.message);throw s}};import{spawn as DR}from"child_process";var pi="comet.resume_probe.v1";function Th(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function FR(e){if(!Th(e))throw new Error("Invalid CometResumeProbeInput: input must be an object");if(e.schema_version!==pi)throw new Error(`Invalid CometResumeProbeInput: schema_version must be ${pi}`);if(typeof e.utterance!="string")throw new Error("Invalid CometResumeProbeInput: utterance must be a string");let t=Th(e.agent_context)?e.agent_context:{};return{schema_version:pi,utterance:e.utterance,locale:typeof e.locale=="string"?e.locale:"unknown",agent_context:{non_trivial_work:t.non_trivial_work===!0,already_in_comet_flow:t.already_in_comet_flow===!0}}}function Oe(e,t,n,i,r=[]){return{schema_version:pi,action:e,changeName:t?.name??null,phase:t?.phase??null,nextCommand:e==="auto_resume"||e==="ask_user"?t?.nextCommand??null:null,confidence:n,reason:i,evidence:r}}async function BR(e,t,n){return await ee(e,t,{label:n,expected:"file"})?B(e,t,{label:n}):""}async function jh(e,t,n){let i=["proposal.md","design.md","tasks.md"],r=[n.name,n.workflow,n.phase];for(let s of i)r.push(await BR(e,`${t}/${s}`,`Classic change ${n.name} ${s}`));return r.join(`
|
|
267
|
+
`).toLowerCase()}function WR(e){switch(e){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}}function HR(e,t,n){let i=n.classic,r=n.unknownKeys.filter(s=>s!=="run_id");return i?r.length>0?{name:t,valid:!1,workflow:i.workflow,phase:i.phase,currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:`unknown field(s): ${r.join(", ")}`}:{name:t,valid:!0,workflow:i.workflow,phase:i.phase,currentStep:null,nextCommand:WR(i.phase),runtimeMode:"engine-projection",runtimeEval:null,evidence:[]}:{name:t,valid:!1,workflow:"unknown",phase:"invalid",currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:`${e} does not contain valid Comet state`}}async function KR(e,t){return await ee(e,`${t}/proposal.md`,{label:"Classic proposal",expected:"file"})||await ee(e,`${t}/design.md`,{label:"Classic design",expected:"file"})||await ee(e,`${t}/tasks.md`,{label:"Classic tasks",expected:"file"})}async function JR(e){let t=(await Z(e)).changesDir;if(!(await V(e,t,{label:"Classic changes directory",expected:"directory"})).exists)return[];let i=await wu(t),r=[];for(let s of i){if(s==="archive"||ge(s))continue;let o=await Je(s,e);if(!o.exists)continue;let a=o.directory;if(!o.stateExists){if(!await KR(e,a))continue;let m={name:s,workflow:"unknown",phase:"invalid",nextCommand:null,diagnostic:{name:s,valid:!1,workflow:"unknown",phase:"invalid",currentStep:null,nextCommand:null,runtimeMode:"invalid",runtimeEval:null,evidence:[],error:"missing Comet state"},buildPause:null,hasClassicProjection:!1,verifyResult:null,text:"",missingCometState:!0};m.text=await jh(e,a,m),r.push(m);continue}let l=await W(a,{migrate:!1}),f=l.classic,u=HR(a,s,l),d=!!f,h=f?.phase??u.phase,g=f?.workflow??u.workflow;if(h==="archive"||f?.archived)continue;let p={name:s,workflow:g,phase:h,nextCommand:u.nextCommand,diagnostic:u,buildPause:f?.buildPause??null,hasClassicProjection:d,verifyResult:f?.verifyResult??null,text:"",missingCometState:!1};p.text=await jh(e,a,p),r.push(p)}return r}var UR=["continue","resume","carry on","finish","run it","commit","verify","archive","继续","接着","恢复","跑完","提交","验证","归档","修刚才"],VR=["what","why","how","explain","summarize","reliable","靠谱吗","是什么","为什么","解释","总结","取名","命名"],YR=new Set(["add","build","cache","change","code","design","docs","file","fix","implement","plan","readme","task","test","update","修改","更新","修复","添加","文档","任务","计划","实现"]),GR=["do not resume","don't resume","without comet","skip comet","不要恢复","不走 comet","不要走 comet","直接解释","只回答"];function Vl(e,t){return t.some(n=>e.includes(n))}function Lh(e){return e.missingCometState||!e.hasClassicProjection||!e.diagnostic.valid||e.phase==="archive"||e.verifyResult==="fail"||e.diagnostic.runtimeEval&&!e.diagnostic.runtimeEval.passed?!0:e.phase!=="build"?!1:e.buildPause==="plan-ready"}function zR(e,t){let n=e.toLowerCase(),i=[];n.includes(t.name.toLowerCase())&&i.push({source:"user",quote:t.name});let r=t.text.split(/[^a-zA-Z0-9_\-\u4e00-\u9fff/]+/u).map(o=>o.trim().toLowerCase()).filter(o=>o.length>=4&&!YR.has(o)),s=[...new Set(r.filter(o=>n.includes(o)))].slice(0,3);for(let o of s)i.push({source:"repo",quote:o});return i}async function XR(e){return new Promise(t=>{let n=DR("git",["status","--short","--untracked-files=all"],{cwd:e,stdio:["ignore","pipe","ignore"],shell:!1}),i=[];n.stdout.on("data",r=>{i.push(Buffer.isBuffer(r)?r:Buffer.from(String(r)))}),n.on("error",()=>t([])),n.on("exit",r=>{if(r!==0){t([]);return}let s=Buffer.concat(i).toString("utf8").split(/\r?\n/u).map(o=>o.trim()).filter(Boolean);t(s)})})}async function Mh(e,t){let n=FR(t),i=n.utterance.trim(),r=i.toLowerCase();if(n.agent_context.already_in_comet_flow)return Oe("out_of_scope",null,"low","already in Comet flow");if(Vl(r,GR))return Oe("out_of_scope",null,"low","user opted out of Comet resume",[{source:"user",quote:i}]);let s=await JR(e);if(s.length===0)return Oe("none",null,"none","no active Comet changes");let o=await XR(e);if(s.length>1){let u=s.find(d=>r.includes(d.name.toLowerCase()));return u?o.length>0?Oe("ask_user",u,"low","uncommitted worktree changes require attribution",[{source:"repo",quote:`${o.length} dirty file(s)`}]):Lh(u)?Oe("ask_user",u,"low","active change is at a decision point"):Oe("auto_resume",u,"high","request names an active change",[{source:"user",quote:u.name}]):Oe("ask_user",null,"low","multiple active changes require a change name")}let[a]=s;if(o.length>0)return Oe("ask_user",a,"low","uncommitted worktree changes require attribution",[{source:"repo",quote:`${o.length} dirty file(s)`}]);if(Lh(a))return a.missingCometState?Oe("ask_user",a,"low","active OpenSpec change is missing Comet state"):Oe("ask_user",a,"low","active change is at a decision point",[{source:"state",quote:`phase: ${a.phase}`}]);let c=Vl(r,UR);if(!n.agent_context.non_trivial_work&&Vl(r,VR)&&!c)return Oe("out_of_scope",a,"low","user asked a question without workflow work");let f=zR(i,a);return c||f.length>0?Oe("auto_resume",a,"high","single active change and request is related",[{source:"state",quote:`phase: ${a.phase}`},...f]):n.agent_context.non_trivial_work?Oe("ask_user",a,"low","single active change exists but request looks unrelated"):Oe("out_of_scope",a,"low","request is not workflow work")}function Ko(e,t,n){return{exitCode:e,...t===void 0?{}:{stdout:t},...n===void 0?{}:{stderr:n}}}function qh(){return Ko(64,void 0,`Usage: comet-resume-probe.mjs probe <input-json>
|
|
268
|
+
Usage: comet-resume-probe.mjs probe --stdin`)}async function QR(){let e=[];for await(let t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Buffer.concat(e).toString("utf8")}function ZR(e){return{schema_version:pi,utterance:e,locale:"unknown",agent_context:{non_trivial_work:!0,already_in_comet_flow:!1}}}function e_(e){try{return JSON.parse(e)}catch{return ZR(e)}}var Dh=async(e,t)=>ot(t,async()=>{let[n,i]=e;if(n!=="probe")return qh();let r=i==="--stdin",s=r?await QR():i;if(!s)return qh();try{let o=r?e_(s):JSON.parse(s),a=await Mh(P(),o);return Ko(0,`${JSON.stringify(a,null,2)}
|
|
269
|
+
`)}catch(o){return o instanceof SyntaxError?Ko(1,void 0,`Invalid JSON: ${o.message}`):Ko(1,void 0,o instanceof Error?o.message:String(o))}});tr();ht();wt();Me();import{createHash as jr,randomUUID as Zo}from"crypto";import{promises as ne}from"fs";import O from"path";var Ql=".comet/classic-root-move.json",Zl=".comet/transactions/classic-root-move/<transaction-id>/openspec",Uh=["handoff hashes","Run state","checkpoints","trajectory","archived evidence and artifact pointers"],Vh=["approved plan ID still matches layout, source identity and manifest, target identity, and configuration","no pending root-move recovery transaction","target remains absent or the bound empty directory","source, target, staging, transaction, and config paths remain protected"],Go=5e4,Yo=512*1024*1024,Fh=16*1024*1024,ct=/^[a-f0-9]{64}$/u,Yh=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/u,Gh=Symbol("ClassicRootMoveJournalClaim");function Xe(e,t){return O.relative(e,t).replaceAll("\\","/")}async function bi(e,t,n,i="directory"){await T(e,Xe(e,t),{label:`Classic root move physical path ${n}`,expected:i})}function zh(e,t){return Ae(e,t)}async function $e(e,t,n){let i=O.resolve(e),r=O.resolve(t),s=O.relative(i,r);if(O.isAbsolute(s)||s===".."||s.startsWith(`..${O.sep}`))throw new Error(`${n} must stay inside the project root`);r!==i&&await bi(e,t,n,"directory");let o=[i],a=i;for(let l of s.split(O.sep).filter(Boolean))a=O.join(a,l),o.push(a);let c=[];for(let l of o){let f=await ne.lstat(l,{bigint:!0});if(!f.isDirectory()||f.isSymbolicLink())throw new Error(`${n} crosses a symbolic link or junction`);c.push({path:l,identity:jn(f),stat:f})}return{entries:c}}async function U(e,t){for(let n of e.entries){let i=await ne.lstat(n.path,{bigint:!0});if(!i.isDirectory()||i.isSymbolicLink()||!zh(n.identity,jn(i)))throw new Error(`${t} changed after inspection`)}}async function t_(e,t,n,i){let r=await $e(e,t,n);await i?.afterDirectoryInspect?.(n),await U(r,n);let s=await ne.readdir(t,{withFileTypes:!0});return await U(r,n),s}async function Nn(e,t,n){try{return await $e(e,t,n),!0}catch(i){if(i.code==="ENOENT")return!1;throw i}}async function hi(e,t,n,i){let r=O.resolve(e),s=O.resolve(t),o=O.relative(r,s);if(O.isAbsolute(o)||o===".."||o.startsWith(`..${O.sep}`))throw new Error(`${n} must stay inside the project root`);let a=r;for(let c of o.split(O.sep).filter(Boolean)){let l=O.join(a,c);try{let f=await ne.lstat(l,{bigint:!0});if(!f.isDirectory()||f.isSymbolicLink())throw new Error(`${n} crosses a symbolic link or junction`)}catch(f){if(f.code!=="ENOENT")throw f;let u=await $e(e,a,n),d=`create-directory:${Xe(e,l)}`;await i?.beforeMutation?.(d),await U(u,n);try{await ne.mkdir(l)}catch(g){if(g.code!=="EEXIST")throw g}await U(u,n);let h=await ne.lstat(l,{bigint:!0});if(!h.isDirectory()||h.isSymbolicLink())throw new Error(`${n} changed while creating a directory`,{cause:f})}a=l}await bi(e,t,n,"directory")}async function Ci(e,t,n){let i=await ne.lstat(e,{bigint:!0});if(i.isSymbolicLink()||(t==="file"?!i.isFile():!i.isDirectory()))throw new Error(`${n} must be a real ${t}`);return i}async function ze(e,t,n){let i=await ne.lstat(e,{bigint:!0}),r=t.isDirectory()?zh(jn(t),jn(i)):na(t,i);if(i.isSymbolicLink()||i.isFile()!==t.isFile()||i.isDirectory()!==t.isDirectory()||!r)throw new Error(`${n} changed after inspection`)}async function eu(e,t,n,i,r){let s=`Classic root move ${i}`,o=await $e(e,O.dirname(t),s);await r?.beforeMutation?.(i),await U(o,s);let a=await ne.open(t,"wx");try{await U(o,s),await a.writeFile(n),await a.sync()}finally{await a.close()}await U(o,s),await bi(e,t,s,"file")}async function ea(e,t,n,i,r){let s=`Classic root move ${i}`,o=await $e(e,O.dirname(t),s),a=await $e(e,O.dirname(n),s),c=await Ci(t,"file",s);await r?.beforeMutation?.(i),await U(o,s),await U(a,s),await ze(t,c,s),await ne.link(t,n),await U(o,s),await U(a,s),await ze(n,c,s)}async function Bh(e,t,n,i,r,s={}){let o=`Classic root move ${i}`,a=await $e(e,O.dirname(t),o),c=await $e(e,O.dirname(n),o),l=await Ci(t,(await ne.lstat(t)).isDirectory()?"directory":"file",o);if(s.replaceTarget)s.expectedTargetIdentity&&await ze(n,s.expectedTargetIdentity,o);else if((await T(e,Xe(e,n),{label:o,expected:"any"})).exists)throw new Error(`${o} target already exists`);await r?.beforeMutation?.(i),await U(a,o),await U(c,o),await ze(t,l,o),s.expectedTargetIdentity&&await ze(n,s.expectedTargetIdentity,o),await s.validateTarget?.(),await ne.rename(t,n),await U(a,o),await U(c,o),await ze(n,l,o)}async function Tn(e,t,n,i,r={}){let s=`Classic root move ${n}`,o;try{o=await Ci(t,"file",s)}catch(c){if(c.code==="ENOENT")return!1;throw c}r.expectedIdentity&&await ze(t,r.expectedIdentity,s);let a=await $e(e,O.dirname(t),s);return await i?.beforeMutation?.(n),await U(a,s),await ze(t,o,s),r.expectedIdentity&&await ze(t,r.expectedIdentity,s),await r.validateTarget?.(),await ne.unlink(t),await U(a,s),!0}async function zo(e,t,n,i,r){let s=`Classic root move ${n}`,o;try{o=await Ci(t,"directory",s)}catch(l){if(l.code==="ENOENT")return!1;throw l}if(r&&!tu(Qo(o,`Classic root move ${n}`),r))throw new Error(`Classic root move ${n} changed after migration preflight`);let a=await $e(e,O.dirname(t),s);await i?.beforeMutation?.(n),await U(a,s),await ze(t,o,s);let c=await ne.readdir(t);if(await U(a,s),await ze(t,o,s),c.length>0)throw new Error(`${s} directory is not empty`);return await ne.rmdir(t),await U(a,s),!0}async function ta(e,t){let n=yt(e,"legacy"),i=yt(e,"docs"),r=O.join(e,".comet","transactions","classic-root-move"),s=[[O.join(e,".comet"),".comet","directory"],[O.join(e,".comet","config.yaml"),".comet/config.yaml","file"],[n.openSpecRoot,"openspec","directory"],[O.dirname(i.openSpecRoot),"docs","directory"],[i.openSpecRoot,"docs/openspec","directory"],[O.join(e,".comet","transactions"),".comet/transactions","directory"],[r,".comet/transactions/classic-root-move","directory"]];if(t){let o=O.join(r,t);s.push([o,`transaction ${t}`,"directory"],[O.join(o,"openspec"),`transaction ${t} staging`,"directory"],[O.join(o,"legacy-source"),`transaction ${t} quarantine`,"directory"])}for(let[o,a,c]of s)await bi(e,o,a,c)}async function Xh(e,t,n,i){let r=Mn(e);await hi(e,O.dirname(r),"Classic root move journal parent",i);let s=`${r}.${Zo()}.tmp`,o=JSON.stringify(n,null,2)+`
|
|
270
|
+
`,a;try{await eu(e,s,o,"update-journal-temp",i);let c=await Ci(s,"file","Classic root move updated journal");a=await sg(e,t,"update-journal-commit",i);try{await ea(e,s,r,"update-journal-publish",i)}catch(u){throw new Error("Classic root move journal publish failed; a successor journal was preserved",{cause:u})}let l=await yi(e),f=l?vi(l):null;if(!l||l.id!==n.id||l.stage!==n.stage||l.planId!==n.planId||l.schema!==n.schema||!f||f.contentHash!==gi(Buffer.from(o))||!na(c,f.fileIdentity))throw new Error("Classic root move journal ownership changed while updating");return await Tn(e,a.file,"cleanup-update-journal-quarantine",i,{expectedIdentity:vi(a.journal).fileIdentity}),a=void 0,l}catch(c){throw a&&await rg(e,a,"restore-update-journal",i).catch(()=>!1),c}finally{await Tn(e,s,"cleanup-update-journal-temp").catch(()=>!1)}}async function n_(e,t,n,i){await hi(e,O.dirname(t),"Classic root move journal parent",i);let r=`${t}.${Zo()}.tmp`;try{await eu(e,r,JSON.stringify(n,null,2)+`
|
|
271
|
+
`,"create-journal-temp",i),await ea(e,r,t,"create-journal-commit",i)}catch(s){throw s.code==="EEXIST"?new Error("Classic root move is incomplete; use comet doctor --repair --strategy continue|rollback",{cause:s}):s}finally{await Tn(e,r,"cleanup-create-journal-temp").catch(()=>!1)}}function Qh(e){return jr("sha256").update(JSON.stringify({directories:e.directories,files:e.files,totalBytes:e.totalBytes})).digest("hex")}function Ar(e,t){return e<t?-1:e>t?1:0}function Jo(e,t){return e.every((n,i)=>i===0||t(e[i-1],n)<=0)}function Zh(e){return jr("sha256").update(JSON.stringify({source:e.source,target:e.target,staging:e.staging,artifactLayout:e.artifactLayout,sourceIdentity:e.sourceIdentity,targetInitialIdentity:e.targetInitialIdentity,targetInitialState:e.targetInitialState,fileCount:e.fileCount,directoryCount:e.directoryCount,totalBytes:e.totalBytes,manifestHash:e.manifestHash,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash})).digest("hex")}function i_(e){return jr("sha256").update(JSON.stringify({source:e.source,target:e.target,staging:Zl,targetInitialState:e.targetInitialState,fileCount:e.fileCount,directoryCount:e.directoryCount,totalBytes:e.totalBytes,manifestHash:e.manifestHash,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash})).digest("hex")}function Xo(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Gl(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function r_(e){return"mtimeNs"in e&&typeof e.mtimeNs=="bigint"?e.mtimeNs:e.mtimeMs}function jn(e){return{dev:e.dev,ino:e.ino,birthtime:Xo(e)}}function Ir(e){return String(e)}function Qo(e,t){let n=jn(e);if(!bn(n,n))throw new Error(`${t} filesystem does not expose a stable device and file identity; refusing an auditable root move`);return{dev:Ir(e.dev),ino:Ir(e.ino),birthtime:Ir(Xo(e)),ctime:Ir(Gl(e)),mtime:Ir(r_(e))}}function s_(e,t,n){return t.entries.map(i=>{let r=Qo(i.stat,n);return{path:Xe(e,i.path)||".",dev:r.dev,ino:r.ino,birthtime:r.birthtime}})}function tu(e,t){return JSON.stringify(e)===JSON.stringify(t)}function eg(e,t){return e.length===t.length&&e.every((n,i)=>tu(n,t[i]))}async function zl(e,t,n){let i=await $e(e,t,n);return await U(i,n),s_(e,i,n)}function na(e,t){let n=jn(e),i=jn(t);return bn(n,i)?Ae(n,i):Ae(n,i)&&Xo(e)===Xo(t)&&Gl(e)===Gl(t)&&e.size===t.size}function gi(e){return jr("sha256").update(e).digest("hex")}async function Nr(e,t,n,i,r){let s=await Y(e,Xe(e,t),n,{label:i,bigint:!0});if(r&&!na(r,s.stat))throw new Error(`${i} changed while reading`);if(BigInt(s.stat.size)!==BigInt(s.bytes.byteLength))throw new Error(`${i} changed while reading`);return s.bytes}async function tg(e){let t=await kn(e,{allowPartialProject:!0});if(!t.document||!t.identity.exists||!t.identity.sha256)throw new Error(".comet/config.yaml does not exist");return t}async function nu(e){return(await tg(e)).identity.sha256}function o_(e){let t=e.value.classic;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("classic must be a mapping");let n=Gn({...e.value,classic:{...t,artifact_layout:"docs"}},e.classic?.language==="zh-CN"||e.native?.language==="zh-CN"?"zh-CN":"en");return jr("sha256").update(n).digest("hex")}async function ia(e,t,n){let i=[],r=[],s=0;async function o(c,l){await bi(e,c,l||Xe(e,t),"directory");let f=await t_(e,c,`tree:${l||Xe(e,t)}`,n);for(let u of f.sort((d,h)=>Ar(d.name,h.name))){let d=O.join(c,u.name),h=l?`${l}/${u.name}`:u.name,g=await ne.lstat(d,{bigint:!0});if(g.isSymbolicLink())throw new Error(`Classic root move does not support symbolic links or junctions: ${h}`);if(g.isDirectory()){i.push(h),await o(d,h);continue}if(!g.isFile())throw new Error(`Classic root move supports only regular files and directories: ${h}`);if(await n?.afterSourceFileInspect?.(h),r.length+1>Go)throw new Error(`Classic root move exceeds ${Go} files`);let p=Yo-s,m=await Nr(e,d,Math.max(1,p),`Classic root move source file ${h}`,g);if(s+=m.byteLength,s>Yo)throw new Error(`Classic root move exceeds ${Yo} bytes`);r.push({path:h,size:m.byteLength,hash:gi(m)})}}await o(t,""),i.sort(Ar),r.sort((c,l)=>Ar(c.path,l.path));let a={directories:i,files:r,totalBytes:s};return{...a,hash:Qh(a)}}function iu(e,t){return e.hash===t.hash}async function a_(e,t,n){try{let i=await $e(e,t,"docs-target"),r=i.entries.at(-1);if(!r)throw new Error("Classic docs target identity is unavailable");let s=Qo(r.stat,"Classic docs target");await n?.afterDirectoryInspect?.("docs-target"),await U(i,"docs-target");let o=await ne.readdir(t,{withFileTypes:!0});await U(i,"docs-target");let c=(await $e(e,t,"docs-target")).entries.at(-1),l=c?Qo(c.stat,"Classic docs target"):null;if(!l||!tu(s,l))throw new Error("Classic docs target changed after inspection");return o.length>0?{state:"non-empty",conflicts:["Classic docs target is not empty"],identity:l}:{state:"empty",conflicts:[],identity:l}}catch(i){if(i.code==="ENOENT")return{state:"missing",conflicts:[],identity:null};throw i}}async function c_(e){if(await xm(e),await Gt(e)!=="legacy")throw new Error("Classic root move requires classic.artifact_layout: legacy")}async function Xl(e,t={}){if(await ta(e),await c_(e),await Gt(e)!=="legacy")throw new Error("Classic root move requires the legacy layout");let n=yt(e,"legacy"),i=yt(e,"docs");if(!await Nn(e,n.openSpecRoot,"Classic legacy root"))throw new Error("Classic legacy root does not exist: openspec/");let r=await zl(e,n.openSpecRoot,"Classic legacy root identity"),s=await ia(e,n.openSpecRoot,t.testHooks),o=await zl(e,n.openSpecRoot,"Classic legacy root identity");if(!eg(r,o))throw new Error("Classic legacy root identity changed during migration preflight");let a=await a_(e,i.openSpecRoot,t.testHooks),c=await tg(e);await t.testHooks?.afterConfigSnapshot?.();let l=c.identity.sha256,f=o_(c.document),u={source:Xe(e,n.openSpecRoot),target:Xe(e,i.openSpecRoot),staging:Zl,artifactLayout:"legacy",sourceIdentity:o,targetInitialIdentity:a.identity,targetInitialState:a.state,fileCount:s.files.length,directoryCount:s.directories.length,totalBytes:s.totalBytes,manifestHash:s.hash,configPath:ce,originalConfigHash:l,expectedConfigHash:f};return{manifest:s,plan:{projectRoot:e,...u,configHash:l,planId:Zh(u),fileSummary:s.files.map(d=>({...d})),configChange:{from:"legacy",to:"docs"},conflicts:a.conflicts,blockers:[],pendingRecovery:null,historicalPointersPreserved:[...Uh],applyPreconditions:[...Vh],allowedRecoveryStrategies:[],readyToApply:a.conflicts.length===0}}}async function l_(e,t,n,i,r){await hi(e,n,"Classic root move staging root",r);for(let s of i.directories)await hi(e,O.join(n,...s.split("/")),`Classic root move staging directory ${s}`,r);for(let s of i.files){await r?.beforeSourceFileCopy?.(s.path);let o=O.join(t,...s.path.split("/")),a=await Nr(e,o,Math.max(1,s.size),`Classic root move source file ${s.path}`);if(a.byteLength!==s.size||gi(a)!==s.hash)throw new Error("Classic legacy root changed after migration preflight");let c=O.join(n,...s.path.split("/"));if(await hi(e,O.dirname(c),`Classic root move staging parent ${s.path}`,r),(await T(e,Xe(e,c),{label:`Classic root move staging file ${s.path}`,expected:"file"})).exists)throw new Error("Classic root move staging changed after migration preflight");await eu(e,c,a,`copy-file:${s.path}`,r);let f=await Nr(e,c,Math.max(1,s.size),`Classic root move staging file ${s.path}`);if(f.byteLength!==s.size||gi(f)!==s.hash)throw new Error("Classic root move staging verification failed")}}function Mn(e){return O.join(e,...Ql.split("/"))}function q(e){return new Error(`invalid Classic root move journal: ${e}`)}function wi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw q(`${t} must be an object`);return e}function Ln(e,t,n){let i=Object.keys(e).sort(),r=[...t].sort();if(JSON.stringify(i)!==JSON.stringify(r))throw q(`${n} fields are invalid`)}function Wh(e,t){if(typeof e!="string"||e.length===0||e.includes("\\"))throw q(`${t} is invalid`);let n=e.split("/");if(O.posix.isAbsolute(e)||n.some(i=>i===""||i==="."||i==="..")||O.posix.normalize(e)!==e)throw q(`${t} must stay inside the migration tree`);return e}function ng(e){let t=wi(e,"manifest");if(Ln(t,["directories","files","totalBytes","hash"],"manifest"),!Array.isArray(t.directories)||!Array.isArray(t.files)||!Number.isSafeInteger(t.totalBytes)||t.totalBytes<0||t.totalBytes>Yo||typeof t.hash!="string"||!ct.test(t.hash))throw q("manifest shape is invalid");let n=t.directories.map((f,u)=>Wh(f,`manifest path directories[${u}]`)),i=t.files.map((f,u)=>{let d=wi(f,`manifest.files[${u}]`);Ln(d,["path","size","hash"],`manifest.files[${u}]`);let h=Wh(d.path,`manifest path files[${u}]`);if(!Number.isSafeInteger(d.size)||d.size<0||typeof d.hash!="string"||!ct.test(d.hash))throw q(`manifest.files[${u}] is invalid`);return{path:h,size:d.size,hash:d.hash}});if(i.length>Go)throw q(`manifest exceeds ${Go} files`);let r=i.map(f=>f.path),s=new Set(n).size!==n.length||new Set(r).size!==r.length,o=Jo(n,Ar)&&Jo(r,Ar)||Jo(n,(f,u)=>f.localeCompare(u))&&Jo(r,(f,u)=>f.localeCompare(u));if(s||!o)throw q("manifest paths must be unique and sorted");let a=i.reduce((f,u)=>f+u.size,0);if(a!==t.totalBytes)throw q("manifest totalBytes does not match its files");let c={directories:n,files:i,totalBytes:a},l=Qh(c);if(l!==t.hash)throw q("manifest hash is invalid");return{...c,hash:l}}function ig(e,t){let n=wi(e,t);Ln(n,["dev","ino","birthtime"],t);let i=/^-?[0-9]+$/u;for(let r of["dev","ino","birthtime"])if(typeof n[r]!="string"||!i.test(n[r]))throw q(`${t}.${r} is invalid`);if(n.dev==="0"||n.ino==="0")throw q(`${t} does not contain a stable filesystem identity`);return{dev:n.dev,ino:n.ino,birthtime:n.birthtime}}function u_(e,t){let n=wi(e,t);Ln(n,["dev","ino","birthtime","ctime","mtime"],t);let i=ig({dev:n.dev,ino:n.ino,birthtime:n.birthtime},t),r=/^-?[0-9]+$/u;if(typeof n.ctime!="string"||!r.test(n.ctime)||typeof n.mtime!="string"||!r.test(n.mtime))throw q(`${t} timestamps are invalid`);return{...i,ctime:n.ctime,mtime:n.mtime}}function f_(e){if(!Array.isArray(e)||e.length!==2)throw q("sourceIdentity must bind the project root and openspec root");let t=[".","openspec"];return e.map((n,i)=>{let r=wi(n,`sourceIdentity[${i}]`);if(Ln(r,["path","dev","ino","birthtime"],`sourceIdentity[${i}]`),r.path!==t[i])throw q(`sourceIdentity[${i}].path is invalid`);let s={dev:r.dev,ino:r.ino,birthtime:r.birthtime};return{path:t[i],...ig(s,`sourceIdentity[${i}]`)}})}function d_(e){if(Ln(e,["schema","id","stage","source","target","staging","configPath","originalConfigHash","expectedConfigHash","planId","targetInitialState","manifest"],"root"),typeof e.id!="string"||!Yh.test(e.id))throw q("id is invalid");if(e.stage!=="copying"&&e.stage!=="ready"&&e.stage!=="switched"&&e.stage!=="configured")throw q("stage is invalid");let t=`.comet/transactions/classic-root-move/${e.id}/openspec`;if(e.source!=="openspec"||e.target!=="docs/openspec"||e.staging!==t)throw q("source, target, and staging must use the managed project paths");if(e.configPath!==ce||typeof e.originalConfigHash!="string"||!ct.test(e.originalConfigHash)||typeof e.expectedConfigHash!="string"||!ct.test(e.expectedConfigHash)||typeof e.planId!="string"||!ct.test(e.planId))throw q("config path, config hashes, or planId is invalid");if(e.targetInitialState!=="missing"&&e.targetInitialState!=="empty")throw q("targetInitialState is invalid");let n=e.targetInitialState,i=ng(e.manifest),r={source:e.source,target:e.target,targetInitialState:n,fileCount:i.files.length,directoryCount:i.directories.length,totalBytes:i.totalBytes,manifestHash:i.hash,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash};if(i_(r)!==e.planId)throw q("planId does not match the bound config and tree");return{schema:"comet.classic-root-move.v1",id:e.id,stage:e.stage,source:e.source,target:e.target,staging:e.staging,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash,planId:e.planId,targetInitialState:n,manifest:i}}function m_(e){if(Ln(e,["schema","id","stage","source","target","staging","artifactLayout","sourceIdentity","targetInitialIdentity","configPath","originalConfigHash","expectedConfigHash","planId","approvedPlanId","targetInitialState","manifest"],"root"),typeof e.id!="string"||!Yh.test(e.id))throw q("id is invalid");if(e.stage!=="locked"&&e.stage!=="copying"&&e.stage!=="ready"&&e.stage!=="switched"&&e.stage!=="configured")throw q("stage is invalid");let t=`.comet/transactions/classic-root-move/${e.id}/openspec`;if(e.source!=="openspec"||e.target!=="docs/openspec"||e.staging!==t)throw q("source, target, and staging must use the managed project paths");if(e.artifactLayout!=="legacy")throw q("artifactLayout must be legacy");let n=f_(e.sourceIdentity);if(e.configPath!==ce||typeof e.originalConfigHash!="string"||!ct.test(e.originalConfigHash)||typeof e.expectedConfigHash!="string"||!ct.test(e.expectedConfigHash)||typeof e.planId!="string"||!ct.test(e.planId)||typeof e.approvedPlanId!="string"||!ct.test(e.approvedPlanId))throw q("config path, config hashes, planId, or approvedPlanId is invalid");let i=e.targetInitialState;if(i!=="missing"&&i!=="empty"&&!(e.stage==="locked"&&i==="non-empty"))throw q("targetInitialState is invalid");let r=e.targetInitialIdentity===null?null:u_(e.targetInitialIdentity,"targetInitialIdentity");if(i==="missing"&&r!==null||i!=="missing"&&r===null)throw q("targetInitialIdentity does not match targetInitialState");let s=ng(e.manifest),o={source:e.source,target:e.target,staging:Zl,artifactLayout:"legacy",sourceIdentity:n,targetInitialIdentity:r,targetInitialState:i,fileCount:s.files.length,directoryCount:s.directories.length,totalBytes:s.totalBytes,manifestHash:s.hash,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash};if(Zh(o)!==e.planId)throw q("planId does not match the bound config and tree");if(e.stage!=="locked"&&e.approvedPlanId!==e.planId)throw q("approvedPlanId does not match the executable plan");return{schema:"comet.classic-root-move.v2",id:e.id,stage:e.stage,source:e.source,target:e.target,staging:e.staging,artifactLayout:"legacy",sourceIdentity:n,targetInitialIdentity:r,configPath:e.configPath,originalConfigHash:e.originalConfigHash,expectedConfigHash:e.expectedConfigHash,planId:e.planId,approvedPlanId:e.approvedPlanId,targetInitialState:i,manifest:s}}function p_(e){let t=wi(e,"root");if(t.schema==="comet.classic-root-move.v1")return d_(t);if(t.schema==="comet.classic-root-move.v2")return m_(t);throw q("schema is unsupported")}async function yi(e,t){return ru(e,Mn(e),Ql,t?.afterJournalInspect)}async function ru(e,t,n,i){await bi(e,t,n,"file");try{let r=await ne.lstat(t,{bigint:!0});if(!r.isFile()||r.isSymbolicLink()||r.size>BigInt(Fh))throw q("journal must be a bounded regular file");await i?.();let s=await Nr(e,t,Fh,"Classic root move journal",r),o=p_(JSON.parse(s.toString("utf8")));return Object.defineProperty(o,Gh,{value:{fileIdentity:r,contentHash:gi(s)},enumerable:!1}),o}catch(r){if(r.code==="ENOENT")return null;throw r}}function vi(e){let t=e[Gh];if(!t)throw new Error("Classic root move journal has no ownership claim");return t}function su(e,t){let n=vi(e),i=vi(t);return na(n.fileIdentity,i.fileIdentity)&&n.contentHash===i.contentHash&&e.schema===t.schema&&e.id===t.id&&e.stage===t.stage&&e.planId===t.planId}async function Hh(e,t){let n=await ru(e,Mn(e),Ql);if(!n||!su(t,n))throw new Error("Classic root move journal ownership changed")}async function rg(e,t,n,i){let r=Mn(e);try{await ea(e,t.file,r,`${n}-publish`,i)}catch(o){if(o.code==="EEXIST")return!1;throw o}let s=await yi(e);if(!s||!su(t.journal,s))throw new Error("Classic root move journal ownership changed while restoring quarantine");return await Tn(e,t.file,`${n}-cleanup-quarantine`,i,{expectedIdentity:vi(t.journal).fileIdentity}),!0}async function sg(e,t,n,i){let r=Mn(e),s=`${r}.${t.id}.${Zo()}.quarantine`;await Hh(e,t);let o=await $e(e,O.dirname(r),`Classic root move ${n} quarantine`);await i?.beforeMutation?.(`${n}-quarantine`),await U(o,`Classic root move ${n} quarantine`),await Hh(e,t),await ne.rename(r,s),await U(o,`Classic root move ${n} quarantine`);let a=await ru(e,s,Xe(e,s)).catch(async c=>{throw await Kh(e,s,`${n}-restore-unverified`,i).catch(()=>!1),new Error("Classic root move journal ownership changed while quarantining",{cause:c})});if(!a||!su(t,a))throw await Kh(e,s,`${n}-restore-successor`,i).catch(()=>!1),new Error("Classic root move journal ownership changed while quarantining");return await i?.afterJournalQuarantine?.(n),{file:s,journal:a}}async function Kh(e,t,n,i){let r=Mn(e),s;try{s=await Ci(t,"file",`Classic root move ${n}`)}catch(o){if(o.code==="ENOENT")return!1;throw o}try{await ea(e,t,r,`${n}-publish`,i)}catch(o){if(o.code==="EEXIST")return!1;throw o}return await Tn(e,t,`${n}-cleanup-quarantine`,i,{expectedIdentity:s}),!0}async function og(e,t,n,i){let r=await sg(e,t,n,i);try{if(!await Tn(e,r.file,`${n}-quarantined`,i,{expectedIdentity:vi(r.journal).fileIdentity}))throw new Error("Classic root move quarantined journal disappeared before removal");return!0}catch(s){throw await rg(e,r,`${n}-restore`,i).catch(()=>!1),s}}async function Uo(e,t,n,i){if(t.schema==="comet.classic-root-move.v1"&&n==="locked")throw new Error("Legacy Classic root move journals do not support the locked stage");let r={...t,stage:n};return Xh(e,t,r,i)}function ag(e,t){let n={legacy:yt(e,"legacy"),docs:yt(e,"docs")},i=O.join(e,".comet","transactions","classic-root-move",t.id);return{source:n.legacy.openSpecRoot,target:n.docs.openSpecRoot,staging:O.join(i,"openspec"),quarantine:O.join(i,"legacy-source"),transactionRoot:i}}async function Tr(e,t,n){if(!await Nn(e,t,"Classic root move tree"))return"missing";try{return iu(await ia(e,t),n)?"match":"mismatch"}catch{return"mismatch"}}async function ou(e,t,n){if(!await Nn(e,t,"Classic root move target"))return"missing";try{let i=await ia(e,t);return iu(i,n)?"match":i.directories.length===0&&i.files.length===0?"empty":"mismatch"}catch{return"mismatch"}}async function cg(e,t,n){if(!await Nn(e,t,"Classic root move manifest tree"))return{status:"missing"};try{let i=await ia(e,t);if(iu(i,n))return{status:"complete",actual:i};let r=new Set(n.directories),s=new Map(n.files.map(o=>[o.path,o]));if(i.directories.some(o=>!r.has(o)))return{status:"mismatch"};for(let o of i.files){let a=s.get(o.path);if(!a||a.size!==o.size||a.hash!==o.hash)return{status:"mismatch"}}return{status:"partial",actual:i}}catch{return{status:"mismatch"}}}async function h_(e,t,n,i,r="remove-quarantine"){let s=await cg(e,t,n);if(s.status==="missing")return;if(s.status==="mismatch"||!s.actual)throw new Error("Classic quarantine contains unknown or changed content; files were preserved");for(let a of s.actual.files){let c=O.join(t,...a.path.split("/")),l;try{l=await ne.lstat(c,{bigint:!0})}catch(u){if(u.code==="ENOENT")continue;throw u}let f=l.isFile()&&!l.isSymbolicLink()?await Nr(e,c,Math.max(1,a.size),`Classic root move quarantine file ${a.path}`,l):null;if(!f||f.byteLength!==a.size||gi(f)!==a.hash)throw new Error("Classic quarantine contains unknown or changed content; files were preserved");await Tn(e,c,`${r}-file:${a.path}`,i)}let o=[...s.actual.directories].sort((a,c)=>{let l=c.split("/").length-a.split("/").length;return l===0?c.localeCompare(a):l});for(let a of o){let c=O.join(t,...a.split("/"));await zo(e,c,`${r}-directory:${a}`,i)}await zo(e,t,`${r}-root`,i)}async function g_(e,t,n,i){let r=await ou(e,t,n.manifest);if(n.targetInitialState==="missing"){if(r!=="missing")throw new Error("Classic docs target changed after migration preflight");return}if(r==="empty"){if(n.schema==="comet.classic-root-move.v2"&&!n.targetInitialIdentity)throw new Error("Classic docs target identity is missing from the approved plan");await zo(e,t,"remove-empty-target",i,n.schema==="comet.classic-root-move.v2"?n.targetInitialIdentity??void 0:void 0);return}if(r!=="missing")throw new Error("Classic docs target changed after migration preflight")}async function Vo(e,t,n){if(n.schema==="comet.classic-root-move.v1")return;let i=await zl(e,t,"Classic legacy root identity");if(!eg(i,n.sourceIdentity))throw new Error("Classic legacy root identity changed after migration preflight")}async function Yl(e,t){if(await nu(e)!==t.originalConfigHash)throw new Error("Classic project config changed after migration preflight");if(await Gt(e)!=="legacy")throw new Error("Classic project config changed after migration preflight")}async function Jh(e,t){if(await nu(e)!==t.expectedConfigHash)throw new Error("Classic project config does not match the expected post-switch config hash");if(await Gt(e)!=="docs")throw new Error("Classic project config does not match the expected post-switch config hash")}async function An(e,t,n,i){if(await Tr(e,t,n)!=="match")throw new Error(i)}async function w_(e,t,n){if(t.stage==="locked")throw new Error("Classic root move locked preflight must be approved before execution");await ta(e,t.id);let{source:i,target:r,staging:s,quarantine:o,transactionRoot:a}=ag(e,t),c=t;if(c.stage==="copying"){await Yl(e,c),await Vo(e,i,c),await An(e,i,c.manifest,"Classic legacy root changed after migration preflight"),await g_(e,r,c,n);let l=await Tr(e,s,c.manifest);if(l==="mismatch")throw new Error("Classic root move staging changed after migration preflight");l==="missing"&&await l_(e,i,s,c.manifest,n),await An(e,s,c.manifest,"Classic root move staging verification failed"),c=await Uo(e,c,"ready",n)}if(c.stage==="ready"){await Yl(e,c),await Vo(e,i,c),await An(e,i,c.manifest,"Classic legacy root changed after migration preflight");let l=await Tr(e,s,c.manifest),f=await ou(e,r,c.manifest);if(l==="missing"&&f==="match")c=await Uo(e,c,"switched",n);else{if(l!=="match")throw new Error("Classic root move staging changed after migration preflight");if(f==="mismatch"||f==="empty")throw new Error("Classic docs target changed after migration preflight");f==="missing"&&(await hi(e,O.dirname(r),"Classic docs target parent",n),await Bh(e,s,r,"rename-staging-target",n),c=await Uo(e,c,"switched",n))}}if(c.stage==="switched"){await Vo(e,i,c),await An(e,i,c.manifest,"Classic legacy root changed before config switch"),await An(e,r,c.manifest,"Classic docs target verification failed after switch");let l=await Gt(e);if(l==="legacy")await Yl(e,c),await Pm(e,"docs",{expectedIdentity:{exists:!0,sha256:c.originalConfigHash}});else if(l!=="docs")throw new Error("Classic project config changed after migration preflight");await Jh(e,c),c=await Uo(e,c,"configured",n)}if(c.stage!=="configured")throw new Error(`Unsupported Classic root move stage: ${c.stage}`);if(await Jh(e,c),await An(e,r,c.manifest,"Classic docs target verification failed after config switch"),await Nn(e,i,"Classic legacy root")){if(await Vo(e,i,c),await An(e,i,c.manifest,"Classic legacy root changed before cleanup; both roots were preserved"),await Nn(e,o,"Classic root move quarantine"))throw new Error("Classic root move quarantine conflicts with the legacy root");await Bh(e,i,o,"rename-source-quarantine",n)}await Nn(e,o,"Classic root move quarantine")&&await h_(e,o,c.manifest,n),await zo(e,a,"remove-transaction-root",n),await og(e,c,"remove-journal",n)}async function y_(e,t){if(await ta(e,t.id),t.stage==="locked")return{allowedStrategies:["rollback"],reason:"the locked apply preflight was not approved for execution"};let{source:n,target:i,staging:r,quarantine:s}=ag(e,t),o=await Gt(e),a=await nu(e),c=o==="legacy"&&a===t.originalConfigHash,l=o==="docs"&&a===t.expectedConfigHash,[f,u,d,h]=await Promise.all([Tr(e,n,t.manifest),ou(e,i,t.manifest),Tr(e,r,t.manifest),cg(e,s,t.manifest)]),g=h.status;if(f==="mismatch")return{allowedStrategies:[],reason:"Classic legacy root changed after migration preflight"};if(u==="mismatch")return{allowedStrategies:[],reason:"Classic docs target changed after migration preflight"};if(d==="mismatch")return{allowedStrategies:[],reason:"Classic staging changed after migration preflight"};if(g==="mismatch")return{allowedStrategies:[],reason:"Classic quarantine contains unknown or changed content"};if(t.stage==="configured"||o==="docs")return l?u==="match"&&(f==="match"&&g==="missing"||f==="missing"&&(g==="missing"||g==="complete"||g==="partial"))?{allowedStrategies:["continue"]}:{allowedStrategies:[],reason:"the configured migration trees are incomplete"}:{allowedStrategies:[],reason:"project config does not match the expected post-switch config hash"};if(!c)return{allowedStrategies:[],reason:"project config changed after migration preflight"};let p=f==="match",m=d==="match"||d==="missing",w=u==="match"||u==="missing"||t.targetInitialState==="empty"&&u==="empty";return!p||!m||!w||g!=="missing"?{allowedStrategies:[],reason:"the migration trees are not recoverable"}:{allowedStrategies:["continue","rollback"]}}async function lg(e,t={}){let n=await ue(e),i=await yi(n,t.testHooks);if(i){let r=await v_(n);if(!r)throw new Error("Classic root move journal disappeared during inspection");return{projectRoot:n,source:i.source,target:i.target,staging:i.staging,artifactLayout:"legacy",sourceIdentity:i.schema==="comet.classic-root-move.v2"?i.sourceIdentity.map(s=>({...s})):[],targetInitialIdentity:i.schema==="comet.classic-root-move.v2"&&i.targetInitialIdentity?{...i.targetInitialIdentity}:null,fileCount:i.manifest.files.length,directoryCount:i.manifest.directories.length,totalBytes:i.manifest.totalBytes,manifestHash:i.manifest.hash,configPath:i.configPath,configHash:i.originalConfigHash,originalConfigHash:i.originalConfigHash,expectedConfigHash:i.expectedConfigHash,planId:i.planId,fileSummary:i.manifest.files.map(s=>({...s})),configChange:{from:"legacy",to:"docs"},conflicts:r.reason?[r.reason]:[],blockers:[`pending Classic root move: ${i.id} at ${i.stage}`],pendingRecovery:r,historicalPointersPreserved:[...Uh],applyPreconditions:[...Vh],allowedRecoveryStrategies:[...r.allowedStrategies],targetInitialState:i.targetInitialState,readyToApply:!1}}return(await Xl(n,t)).plan}async function ug(e,t={}){let n=await ue(e),i=await yi(n,t.testHooks);if(i)throw new Error(`Classic root move ${i.id} is incomplete; use comet doctor --repair --strategy continue|rollback`);let r=await Xl(n),s=t.planId??r.plan.planId;if(!ct.test(s))throw new Error("Classic root move apply received an invalid internal plan ID");let o=Zo();await ta(n,o);let a={schema:"comet.classic-root-move.v2",id:o,stage:"locked",source:r.plan.source,target:r.plan.target,staging:`.comet/transactions/classic-root-move/${o}/openspec`,artifactLayout:r.plan.artifactLayout,sourceIdentity:r.plan.sourceIdentity.map(f=>({...f})),targetInitialIdentity:r.plan.targetInitialIdentity?{...r.plan.targetInitialIdentity}:null,configPath:ce,originalConfigHash:r.plan.originalConfigHash,expectedConfigHash:r.plan.expectedConfigHash,planId:r.plan.planId,approvedPlanId:s,targetInitialState:r.plan.targetInitialState,manifest:r.manifest};await n_(n,Mn(n),a,t.testHooks);let c=await yi(n);if(!c||c.id!==o||c.stage!=="locked")throw new Error("Classic root move lock ownership changed before locked preflight");let l=!1;try{let f=await Xl(n,t),u=f.plan;if(u.planId!==s)throw new Error(`Classic root move plan changed since dry-run: approved ${s}, current ${u.planId}`);if(!u.readyToApply)throw new Error(`Classic root move apply is blocked: ${[...u.conflicts,...u.blockers].join("; ")}`);if(u.targetInitialState==="non-empty")throw new Error("Classic root move apply is blocked: Classic docs target is not empty");let d={schema:"comet.classic-root-move.v2",id:o,stage:"copying",source:u.source,target:u.target,staging:`.comet/transactions/classic-root-move/${o}/openspec`,artifactLayout:u.artifactLayout,sourceIdentity:u.sourceIdentity.map(g=>({...g})),targetInitialIdentity:u.targetInitialIdentity?{...u.targetInitialIdentity}:null,configPath:ce,originalConfigHash:u.originalConfigHash,expectedConfigHash:u.expectedConfigHash,planId:u.planId,approvedPlanId:s,targetInitialState:u.targetInitialState,manifest:f.manifest},h=await Xh(n,c,d,t.testHooks);return l=!0,await w_(n,h,t.testHooks),{...u,staging:d.staging}}catch(f){throw l||await og(n,c,"remove-rejected-lock",t.testHooks).catch(()=>!1),f}}async function v_(e,t={}){let n=await yi(e,t.testHooks);if(!n)return null;let i=await y_(e,n);return{id:n.id,stage:n.stage,source:n.source,target:n.target,staging:n.staging,planId:n.planId,...i}}wt();function fg(e="en"){return{exitCode:64,stderr:e==="zh-CN"?"用法:comet classic root show | comet classic root move docs --dry-run | comet classic root move docs --apply":"Usage: comet classic root show | comet classic root move docs --dry-run | comet classic root move docs --apply"}}function b_(e){return e?.classic?.language==="en"?"en":"zh-CN"}function C_(e,t){let n=e instanceof Error?e.message:String(e);return t==="en"?n:n==="invalid Classic root move journal: manifest paths must be unique and sorted"?"Classic 根目录迁移失败:迁移记录中的清单路径必须唯一且按顺序排列":n.startsWith("invalid Classic root move journal:")?"Classic 根目录迁移失败:迁移记录格式或内容无效,请运行 comet doctor 检查恢复状态":"Classic 根目录迁移失败:迁移过程中发生错误,请运行 comet doctor 检查迁移状态"}function dg(e,t,n="en"){let i=n==="zh-CN",r=d=>d.length>0?d.join("; "):i?"无":"none",s=d=>{if(!i)return d;let h=/^pending Classic root move: (.+) at (.+)$/u.exec(d);return h?`存在待恢复的 Classic 根目录迁移:${h[1]},阶段 ${h[2]}`:{"Classic docs target is not empty":"docs 目标目录非空","the locked apply preflight was not approved for execution":"已锁定的迁移预检尚未获准执行","Classic legacy root changed after migration preflight":"迁移预检后 legacy 根目录发生变化","Classic docs target changed after migration preflight":"迁移预检后 docs 目标目录发生变化","Classic staging changed after migration preflight":"迁移预检后暂存目录发生变化","Classic quarantine contains unknown or changed content":"隔离目录包含未知或已变化的内容","project config does not match the expected post-switch config hash":"项目配置与切换后的预期配置哈希不一致","the configured migration trees are incomplete":"已切换配置对应的迁移目录不完整","project config changed after migration preflight":"迁移预检后项目配置发生变化","the migration trees are not recoverable":"迁移目录当前无法安全恢复"}[d]??"迁移状态存在无法识别的冲突,请运行 comet doctor 检查恢复状态"},o=(d,h)=>h.length===0?[`${d}: ${i?"无":"none"}`]:[`${d}:`,...h.map(g=>`- ${s(g)}`)],a=i?{missing:"缺失",empty:"空目录","non-empty":"非空目录"}[e.targetInitialState]:e.targetInitialState,c=i?"handoff 哈希;运行状态;检查点;轨迹;已归档证据与产物指针":e.historicalPointersPreserved.join("; "),l=i?"内部迁移身份仍与布局、源目录、清单、目标目录和配置一致;不存在待恢复的根迁移事务;目标仍然缺失或为已绑定的空目录;所有迁移路径仍受保护":e.applyPreconditions.join("; "),f=i?e.allowedRecoveryStrategies.map(d=>d==="continue"?"继续":"回滚"):e.allowedRecoveryStrategies,u=[t==="dry-run"?i?"Classic 根目录迁移现状":"Classic root move status":i?"Classic 根目录迁移完成":"Classic root move complete",...t==="dry-run"?[i?"说明:仅查看现状,未修改任何文件。":"Note: Inspection only; no files were changed."]:[],`${i?"源目录":"source"}: ${e.source}`,`${i?"目标目录":"target"}: ${e.target}`,`${i?"暂存目录":"staging"}: ${e.staging}`,`${i?"当前布局":"artifact layout"}: ${e.artifactLayout}`,`${i?"源目录身份":"source identity"}: ${JSON.stringify(e.sourceIdentity)}`,`${i?"目标初始身份":"target initial identity"}: ${e.targetInitialIdentity?JSON.stringify(e.targetInitialIdentity):i?"缺失":"missing"}`,`${i?"文件数":"files"}: ${e.fileCount}`,`${i?"目录数":"directories"}: ${e.directoryCount}`,`${i?"总字节数":"bytes"}: ${e.totalBytes}`,`${i?"清单哈希":"manifest"}: ${e.manifestHash}`,...e.fileSummary.map(d=>`${i?"文件":"file"}: ${d.path} ${d.size} ${d.hash}`),`${i?"配置变更":"config change"}: ${e.configChange.from} -> ${e.configChange.to}`,`${i?"配置路径":"config path"}: ${e.configPath}`,`${i?"配置哈希":"config"}: ${e.configHash}`,`${i?"原配置哈希":"original config"}: ${e.originalConfigHash}`,`${i?"预期配置哈希":"expected config"}: ${e.expectedConfigHash}`,`${i?"目标初始状态":"target initial state"}: ${a}`,...o(i?"冲突":"conflicts",e.conflicts),...o(i?"阻塞项":"blockers",e.blockers),`${i?"待恢复事务":"pending recovery"}: ${e.pendingRecovery?`${e.pendingRecovery.id} ${i?"位于阶段":"at"} ${e.pendingRecovery.stage}`:i?"无":"none"}`,`${i?"保留历史指针":"historical pointers preserved"}: ${c}`,`${i?"执行前提":"apply preconditions"}: ${l}`,`${i?"允许的恢复策略":"allowed recovery strategies"}: ${r(f)}`,`${i?"可执行迁移":"ready to apply"}: ${e.readyToApply?i?"是":"yes":i?"否":"no"}`];return t==="dry-run"?u.push(e.readyToApply?i?"下一步:运行 comet classic root move docs --apply 执行迁移。":"Next: run comet classic root move docs --apply to apply the migration.":i?"下一步:请先解决上述冲突或阻塞项。":"Next: resolve the conflicts or blockers above before applying."):u.push(i?"结果:迁移已完成。":"Result: Migration completed."),`${u.join(`
|
|
272
272
|
`)}
|
|
273
|
-
`}function
|
|
273
|
+
`}function k_(e,t,n){let i=N(e.projectRoot,e.openSpecRoot);return n==="zh-CN"?[t==="dry-run"?"Classic 根目录迁移现状":"Classic 根目录迁移完成",`当前布局: ${e.artifactLayout}`,`Classic 根目录: ${i}`,t==="dry-run"?"说明:项目已经使用 docs/openspec,仅查看现状,未修改任何文件。":"结果:项目已经使用 docs/openspec,无需重复迁移,未修改任何文件。"].join(`
|
|
274
274
|
`)+`
|
|
275
275
|
`:[t==="dry-run"?"Classic root move status":"Classic root move complete",`current layout: ${e.artifactLayout}`,`Classic root: ${i}`,t==="dry-run"?"Note: The project already uses docs/openspec. Inspection only; no files were changed.":"Result: The project already uses docs/openspec. No migration was needed and no files were changed."].join(`
|
|
276
276
|
`)+`
|
|
277
|
-
`}var
|
|
278
|
-
`}}if(t!=="move"||n!=="docs")return
|
|
277
|
+
`}var mg=async e=>{let[t,n,i,...r]=e;if(t==="show"&&n===void 0){let f=await ue(process.cwd()),u=await Z(f);return{exitCode:0,stdout:JSON.stringify({schema:"comet.classic-layout.v1",artifactLayout:u.artifactLayout,openSpecRoot:N(f,u.openSpecRoot),changesRoot:N(f,u.changesDir),archiveRoot:N(f,u.archiveDir),specsRoot:N(f,u.specsDir),superpowersRoot:N(f,u.superpowersRoot)})+`
|
|
278
|
+
`}}if(t!=="move"||n!=="docs")return fg();let s=await ue(process.cwd()),o=await el(s),a=b_(o);if(i!=="--dry-run"&&i!=="--apply"||r.length>0)return fg(a);let c=await Z(s),l=i==="--dry-run"?"dry-run":"complete";if(c.artifactLayout==="docs")return{exitCode:0,stdout:k_(c,l,a)};try{if(i==="--dry-run"){let u=await lg(s);return{exitCode:0,stdout:dg(u,"dry-run",a)}}let f=await ug(s);return{exitCode:0,stdout:dg(f,"complete",a)}}catch(f){return{exitCode:70,stderr:C_(f,a)}}};var qr=ft(nt(),1);import{spawnSync as S_}from"child_process";import{promises as E_}from"fs";import D from"path";fr();var R_="\x1B[32m",__="\x1B[31m",x_="\x1B[33m",fu="\x1B[0m",Lr=["full","hotfix","tweak"],du=["open","design","build","verify","archive"],hg=["en","zh-CN"],P_=_p,cu=new Set([...dr,"archive_confirmation","verify_failures","classic_profile","classic_migration","bound_branch"]),O_=new Set(Zt.filter(e=>!cu.has(e))),$_={workflow:Lr,phase:du,context_compression:["off","beta"],build_mode:["subagent-driven-development","executing-plans","direct"],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:Lr,classic_migration:["1"]},I_=new Set(["design_doc","plan","verification_report","handoff_context"]),A_={archived:"archived",branchStatus:"branch_status",classicProfile:"classic_profile",designDoc:"design_doc",language:"language",phase:"phase",verificationReport:"verification_report",verifiedAt:"verified_at",archiveConfirmation:"archive_confirmation",verifyResult:"verify_result",verifyFailures:"verify_failures",workflow:"workflow"},Mr=class extends Error{constructor(n,i=1){super(n);this.exitCode=i}exitCode},sa=class{stdout=[];stderr=[];result(t=0){return{exitCode:t,...this.stdout.length>0?{stdout:this.stdout.join(`
|
|
279
279
|
`)+`
|
|
280
280
|
`}:{},...this.stderr.length>0?{stderr:this.stderr.join(`
|
|
281
|
-
`)}:{}}}};function Qe(e){return`${
|
|
282
|
-
Valid values: ${t.join(" ")}`)}function
|
|
283
|
-
Valid values: en, zh-CN`)}function
|
|
284
|
-
Valid values: off, beta`),e}async function
|
|
285
|
-
Valid values: true, false`),e}async function
|
|
286
|
-
Valid values: off, standard, thorough`),e==="null"?null:e}function
|
|
287
|
-
`);return n.errors.length>0&&S(`ERROR: Invalid value: '${t}'`),n.get(e)}async function
|
|
281
|
+
`)}:{}}}};function Qe(e){return`${R_}${e}${fu}`}function lu(e){return`${__}${e}${fu}`}function pg(e){return`${x_}${e}${fu}`}function S(e){throw new Mr(e)}function Ze(e){let t=ge(e);t&&S(`ERROR: ${t}`)}function aa(e,t){t.includes(e)||S(`ERROR: Invalid value: '${e}'
|
|
282
|
+
Valid values: ${t.join(" ")}`)}function oa(e,t){if(hg.includes(e))return e;S(`ERROR: Invalid language from ${t}: '${e}'
|
|
283
|
+
Valid values: en, zh-CN`)}function gg(e,t){!e||e==="null"||(/^(?:[A-Za-z]:|[\\/]|~)/u.test(e)&&S(`ERROR: ${t} must be a relative path within the repo: '${e}'`),e.split(/[\\/]/u).includes("..")&&S(`ERROR: ${t} cannot contain '..' (path traversal not allowed): '${e}'`))}async function oe(e){let t=P();return ee(t,e,{label:`Classic project path ${D.relative(t,D.resolve(t,e)).replaceAll("\\","/")}`})}async function At(e){let t=P();return Sn(t,e,`Classic project file ${D.relative(t,D.resolve(t,e)).replaceAll("\\","/")}`)}async function N_(e){return ei(e,P())}async function ca(e){let t,n=P();try{t=await B(n,e,{label:`Classic state ${D.relative(n,e).replaceAll("\\","/")}`})}catch(r){throw r.code==="ENOENT"&&S(`ERROR: .comet.yaml not found at ${D.relative(n,e).replaceAll("\\","/")}`),r}let i=(0,qr.parseDocument)(t,{uniqueKeys:!1});return i.errors.length>0&&S(`ERROR: Invalid .comet.yaml: ${i.errors[0].message}`),i}async function mu(e,t){await Qn(P(),e,t,{label:"Classic state write target"})}function uu(e){return e===null?"null":e===void 0?"":typeof e=="object"?JSON.stringify(e):String(e)}function wg(e){return A_[e]??String(e)}function yg(e){return e===null?"null":uu(e)}function be(e,t,n,i){let r=e[t];return typeof r=="string"&&n.includes(r)?r:i}function Ot(e,t){let n=e[t];return n==null||n===""?null:typeof n=="string"?n:String(n)}function au(e,t){let n=e[t];return n==null||n===""?null:typeof n=="boolean"?n:n==="true"?!0:n==="false"?!1:null}function T_(e,t,n=0){let i=e[t];return typeof i=="number"&&Number.isInteger(i)&&i>=0?i:n}function j_(e){let t=be(e,"workflow",Lr,"full");return{workflow:t,language:be(e,"language",hg,null),phase:be(e,"phase",du,"open"),contextCompression:be(e,"context_compression",["off","beta"],null),buildMode:be(e,"build_mode",["subagent-driven-development","executing-plans","direct"],null),buildPause:be(e,"build_pause",["plan-ready"],null),subagentDispatch:be(e,"subagent_dispatch",["confirmed"],null),tddMode:be(e,"tdd_mode",["tdd","direct"],null),reviewMode:be(e,"review_mode",["off","standard","thorough"],null),isolation:be(e,"isolation",["current","branch","worktree"],null),boundBranch:Ot(e,"bound_branch"),verifyMode:be(e,"verify_mode",["light","full"],null),autoTransition:au(e,"auto_transition"),baseRef:Ot(e,"base_ref"),designDoc:Ot(e,"design_doc"),plan:Ot(e,"plan"),verifyResult:be(e,"verify_result",["pending","pass","fail"],"pending"),verifyFailures:T_(e,"verify_failures"),verificationReport:Ot(e,"verification_report"),branchStatus:be(e,"branch_status",["pending","handled"],null),createdAt:Ot(e,"created_at"),verifiedAt:Ot(e,"verified_at"),archiveConfirmation:be(e,"archive_confirmation",["pending","confirmed"],null),archived:au(e,"archived")??!1,directOverride:au(e,"direct_override"),handoffContext:Ot(e,"handoff_context"),handoffHash:Ot(e,"handoff_hash"),classicProfile:be(e,"classic_profile",Lr,t),classicMigration:typeof e.classic_migration=="number"?e.classic_migration:null}}async function pu(e){return(await Rr(e,{cwd:P()}))?.value??null}async function vg(){if(process.env.COMET_LANGUAGE)return oa(process.env.COMET_LANGUAGE,"COMET_LANGUAGE");let e=await Rr("language",{cwd:P()});return e?oa(e.value,e.source):"en"}async function L_(){let e=process.env.COMET_CONTEXT_COMPRESSION??await pu("context_compression")??"off";return["off","beta"].includes(e)||S(`ERROR: Invalid context_compression: '${e}'
|
|
284
|
+
Valid values: off, beta`),e}async function bg(){let e=process.env.COMET_AUTO_TRANSITION??await pu("auto_transition")??"true";return["true","false"].includes(e)||S(`ERROR: Invalid auto_transition: '${e}'
|
|
285
|
+
Valid values: true, false`),e}async function M_(){let e=process.env.COMET_REVIEW_MODE??await pu("review_mode")??"standard";return["null","off","standard","thorough"].includes(e)||S(`ERROR: Invalid review_mode: '${e}'
|
|
286
|
+
Valid values: off, standard, thorough`),e==="null"?null:e}function Cg(e){let t=S_("git",e,{encoding:"utf8"});return t.status===0?t.stdout.trim():null}async function lt(e){let t=await N_(e);return await V(P(),D.join(t.directory,".comet"),{label:`Classic runtime directory for ${e}`,expected:"directory"}),{...t,file:D.join(t.directory,".comet.yaml")}}async function _(e,t){let{file:n}=await lt(e),s=(await ca(n)).toJS()[t];return t==="language"?s==null||s===""?vg():oa(uu(s),".comet.yaml"):t==="auto_transition"&&(s==null||s==="")?bg():uu(s)}function kg(e,t){let n=(0,qr.parseDocument)(`${e}: ${t}
|
|
287
|
+
`);return n.errors.length>0&&S(`ERROR: Invalid value: '${t}'`),n.get(e)}async function q_(e,t){if(e==="language"){oa(t,"language");return}let n=$_[e];n&&aa(t,n),I_.has(e)&&(gg(t,e),t&&t!=="null"&&await V(P(),t,{label:`${e} artifact pointer`,expected:"file"})),(e==="skill_hash"||e==="handoff_hash")&&!/^[a-f0-9]{64}$/u.test(t)&&S(`ERROR: ${e} must be a sha256 hex digest`),e==="iteration"&&!/^[0-9]+$/u.test(t)&&S("ERROR: iteration must be a non-negative integer")}async function Sg(e,t,n,i,r={}){cu.has(n)&&!r.machineOwned&&S(`ERROR: '${n}' is a machine-owned field and cannot be set directly`),!O_.has(n)&&!cu.has(n)&&S(`ERROR: Unknown field: '${n}'`),n==="phase"&&!r.internal&&process.env.COMET_FORCE_PHASE!=="1"&&S(`ERROR: Setting 'phase' directly is not allowed; it bypasses state machine evidence checks.
|
|
288
288
|
Use: comet-state.mjs transition <change-name> <event>
|
|
289
|
-
Repair-only escape hatch: COMET_FORCE_PHASE=1 comet-state.mjs set <change-name> phase <value>`),await L_(n,i);let{file:s,directory:o}=await lt(t),a=await aa(s),c=a.toJS()??{};if(a.set(n,Cg(n,i)),n==="isolation")if(Ao(i)){let u=typeof c.isolation=="string"?c.isolation:null,d=c.bound_branch;if(!(typeof d=="string"&&d!=="")||u!==i){let g=Rt(),p=Io(g),m=$l({isolation:i,boundBranch:null,currentBranch:p,gitWorkTree:p===null?Ol(g):!0});m.status==="needs-heal"?a.set("bound_branch",m.branch):m.status==="unbound-detached"?S(`ERROR: cannot bind isolation=${i} while HEAD is detached; checkout a branch first`):a.set("bound_branch",null)}}else a.set("bound_branch",null);let l=await ur(o),f=mr(a.toJS(),l);if(f.run){f.classic||S("ERROR: migrated Run is missing its Classic projection");let u=await Ue(o,f),d=bt(f.classic,u),h=d!==f.run.currentStep,g={...f.run,currentStep:d,iteration:f.run.iteration+(h?1:0),status:d==="completed"?"completed":"running"};if(await Ne(o,{classic:f.classic,run:g,unknownKeys:f.unknownKeys}),h){let p=await Te(o,g.trajectoryRef);await De(o,g.trajectoryRef,{sequence:p.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:g.runId,data:{kind:"classic-config",field:n,fromStep:f.run.currentStep,toStep:d}})}}else await mu(s,a.toString());n==="phase"&&!r.internal&&e.stderr.push(mg("WARNING: Setting 'phase' directly bypasses state machine constraints."),mg(" Consider using: comet-state.mjs transition <change-name> <event>")),e.stderr.push(Qe(`[SET] ${n}=${i}`))}async function M_(e,t,n){Ze(t),oa(n,Lr);let i=await Nm(t,P()),{label:r,directory:s}=i,o=D.join(s,".comet.yaml");await oe(o)&&S(`ERROR: .comet.yaml already exists at ${r}/.comet.yaml`);let a=n!=="full",c=a?"off":await j_(),l=new qr.Document({workflow:n,language:await yg(),phase:"open",context_compression:await T_(),build_mode:a?"direct":null,build_pause:null,subagent_dispatch:null,tdd_mode:a?"direct":null,review_mode:c,isolation:null,verify_mode:a?"light":null,auto_transition:await vg()==="true",base_ref:bg(["rev-parse","--verify","HEAD"]),design_doc:null,plan:null,verify_result:"pending",verify_failures:0,verification_report:null,branch_status:"pending",created_at:new Date().toISOString().slice(0,10),verified_at:null,archive_confirmation:null,archived:!1});await mu(o,l.toString()),e.stdout.push(Qe(`Initialized: ${r}/.comet.yaml (workflow=${n})`))}async function $t(e,t){let n=await _(e,"phase");n!==t&&S(`ERROR: Cannot transition '${e}': expected phase ${t}, got ${n}`)}async function q_(e){let t=await _(e,"workflow"),n=await _(e,"build_mode"),i=await _(e,"isolation"),r=await _(e,"direct_override"),s=await _(e,"subagent_dispatch"),o=await _(e,"tdd_mode"),a=await _(e,"review_mode");["current","branch","worktree"].includes(i)||S(`ERROR: Cannot transition '${e}': isolation must be current, branch, or worktree, got '${i||"null"}'`),["subagent-driven-development","executing-plans","direct"].includes(n)||S(`ERROR: Cannot transition '${e}': build_mode must be selected before leaving build, got '${n||"null"}'`),n==="direct"&&!["hotfix","tweak"].includes(t)&&r!=="true"&&S(`ERROR: Cannot transition '${e}': build_mode=direct is only allowed for hotfix/tweak unless direct_override=true`),n==="subagent-driven-development"&&s!=="confirmed"&&S(`ERROR: Cannot transition '${e}': subagent_dispatch must be confirmed before using build_mode=subagent-driven-development`),t==="full"&&(!o||o==="null")&&S(`ERROR: Cannot transition '${e}': tdd_mode must be selected before leaving build (full workflow)`),t==="full"&&!["off","standard","thorough"].includes(a)&&S(`ERROR: Cannot transition '${e}': review_mode must be selected before leaving build (full workflow); review_mode must be off, standard, or thorough, got '${a||"null"}'`)}async function D_(e){let{directory:t}=await lt(e),n=await _(e,"workflow");for(let i of["proposal.md","tasks.md"])await At(D.join(t,i))||S(`ERROR: Cannot transition '${e}': ${i} must exist and be non-empty before leaving open`);n==="full"&&!await At(D.join(t,"design.md"))&&S(`ERROR: Cannot transition '${e}': design.md must exist and be non-empty before leaving open`)}async function F_(e){let t=await _(e,"design_doc");(!t||t==="null"||!await At(D.resolve(t)))&&S(`ERROR: Cannot transition '${e}': design_doc must point to an existing Design Doc before leaving design`)}async function B_(e,t){let n=D.join(e,".comet.yaml"),i=await aa(n);for(let r of t){let s=gg(r.field);i.set(s,Cg(s,wg(r.to)))}await mu(n,i.toString())}async function W_(e,t,n){let{directory:i}=await lt(t),r=await W(i),s=r.classic,o=!1;if(!s){r.run&&S("ERROR: Classic state projection is missing");let c=await aa(D.join(i,".comet.yaml"));s=N_(c.toJS()),o=!0}let a=ai(s,n);r.run?await rn(i,a.classic,r.run,{event:n,source:"comet-state"}):o?await B_(i,a.effects):await Ne(i,{classic:a.classic,run:null,unknownKeys:r.unknownKeys}),await Pn(i,{change:t,event:n,source:"comet-state",from:s,to:a.classic,effects:a.effects});for(let c of a.effects)e.stderr.push(Qe(`[SET] ${gg(c.field)}=${wg(c.to)}`));e.stderr.push(Qe(`[TRANSITION] ${n}`))}async function H_(e,t,n){if(Ze(t),oa(n,__),n==="open-complete")await $t(t,"open"),await D_(t);else if(n==="design-complete")await $t(t,"design"),await F_(t);else if(n==="build-complete")await $t(t,"build"),await q_(t);else if(n==="verify-pass"){await $t(t,"verify");let i=await _(t,"verification_report");(!i||!await oe(D.resolve(i)))&&S(`ERROR: Cannot transition '${t}': verification_report must point to an existing report file`)}else if(n==="verify-fail")await $t(t,"verify");else if(n==="archive-confirm")await $t(t,"archive"),await _(t,"verify_result")!=="pass"&&S(`ERROR: Cannot transition '${t}': verify_result must be pass before archiving`),await _(t,"archived")==="true"&&S(`ERROR: Cannot transition '${t}': already archived`);else if(n==="preset-escalate"){await $t(t,"build");let i=await _(t,"workflow");["hotfix","tweak"].includes(i)||S(`ERROR: Cannot transition '${t}': preset-escalate only applies to hotfix/tweak, got workflow='${i}'`)}else n==="archive-reopen"?(await $t(t,"archive"),await _(t,"archived")==="true"&&S(`ERROR: Cannot transition '${t}': already archived`)):(await $t(t,"archive"),await _(t,"verify_result")!=="pass"&&S(`ERROR: Cannot transition '${t}': verify_result must be pass before archiving`),await _(t,"archive_confirmation")!=="confirmed"&&S(`ERROR: Cannot transition '${t}': archive_confirmation must be confirmed before archiving`));await W_(e,t,n)}async function K_(e,t){Ze(t);let{file:n,label:i}=await lt(t);await oe(n)||S(`ERROR: .comet.yaml not found at ${i}/.comet.yaml`);let r=await _(t,"phase"),s=await _(t,"workflow"),o=await _(t,"auto_transition");if(await _(t,"archived")==="true"){e.stdout.push("NEXT: done");return}let a=r==="open"?"comet-open":r==="design"?"comet-design":r==="verify"?"comet-verify":r==="archive"?"comet-archive":r==="build"?s==="hotfix"?"comet-hotfix":s==="tweak"?"comet-tweak":"comet-build":null;a||S(`ERROR: Cannot resolve next step for '${t}': unknown phase '${r||"null"}'`),e.stdout.push(`NEXT: ${o==="false"?"manual":"auto"}`,`SKILL: ${a}`),o==="false"&&e.stdout.push(`HINT: phase is '${r}'; run /${a} manually to continue`)}async function J_(e,t,n){hg(t,"task file"),n||S("ERROR: Task text cannot be empty");let i=D.resolve(P(),t);await oe(i)||S(`ERROR: Task file not found: ${t}`);let s=(await B(P(),i,{label:"Classic task-checkoff file"})).split(/\r?\n/u).filter(a=>[`- [ ] ${n}`,`- [x] ${n}`,`- [X] ${n}`].includes(a)),o=s.filter(a=>/^- \[[xX]\] /u.test(a));s.length!==1&&S(`ERROR: task text must appear exactly once in ${t} (found ${s.length}): ${n}`),o.length!==1&&S(`ERROR: task is not checked in ${t}: ${n}`),e.stdout.push("TASK_CHECKOFF: PASS",`FILE: ${t}`,`TASK: ${n}`)}async function U_(e,t,n){Ze(t),oa(n,du);let{file:i,directory:r,label:s}=await lt(t);e.stdout.push(`=== Entry Check: comet-${n} ===`),await oe(i)||S(`ERROR: .comet.yaml not found at ${s}/.comet.yaml`);let o=!1,a=u=>e.stdout.push(` ${Qe("[PASS]")} ${u}`),c=u=>{e.stdout.push(` ${lu("[FAIL]")} ${u}`),o=!0},l=async(u,d)=>{let h=await _(t,u);(h===d?a:c)(`${u}=${h} (expected: ${d})`)};if(a(".comet.yaml exists"),await l("phase",n),n==="design"){await l("workflow","full");let u=await _(t,"design_doc");(!u||u==="null"?a:c)(u?`design_doc=${u} (expected: empty/null)`:"design_doc is empty/null");for(let d of["proposal.md","design.md","tasks.md"])(await At(D.join(r,d))?a:c)(`${d} ${await At(D.join(r,d))?"non-empty":"missing or empty"}`)}else if(n==="build"){let u=await _(t,"workflow"),d=await _(t,"design_doc");u==="full"?(d&&d!=="null"&&await oe(D.resolve(d))?a:c)(`design_doc=${d} (expected: non-null and file exists)`):a(`workflow=${u} (design_doc not required)`);for(let h of["proposal.md","tasks.md"])(await At(D.join(r,h))?a:c)(`${h} ${await At(D.join(r,h))?"non-empty":"missing or empty"}`)}else if(n==="verify"){let u=await _(t,"verify_result");(["","null","pending"].includes(u)?a:c)(`verify_result=${u} (expected: pending or null)`)}else if(n==="archive"){await l("verify_result","pass");let u=await _(t,"archived");(u!=="true"?a:c)(`archived=${u} (expected: not true)`)}let f=await St(r,{heal:!0,cwd:Rt()});if(f.bindingRequired)switch(f.status){case"drift":c(No(t,f.boundBranch,f.currentBranch));break;case"unbound-detached":c(Et(t));break;case"healed":a(`bound_branch lazily set to ${f.branch}`);break;case"needs-heal":case"ok":case"not-applicable":a("bound_branch matches current branch");break;default:{let u=f;throw new Error(`unhandled branch binding status: ${JSON.stringify(u)}`)}}if(e.stdout.push(""),o)throw e.stderr.push(lu("BLOCKED — fix failing checks before proceeding")),new Mr("",1);e.stderr.push(Qe("ALL CHECKS PASSED — ready to proceed"))}async function pe(e,t,n){return!t||t==="null"?` - ${e}: PENDING`:n&&!await oe(D.resolve(n))?` - ${e}: BROKEN (path ${t} does not exist)`:` - ${e}: DONE (${t})`}async function V_(e,t){e.stdout.push(" Artifacts:");let n=0;for(let i of["proposal.md","design.md","tasks.md"]){let r=await At(D.join(t,i));r&&(n+=1),e.stdout.push(` - ${i}: ${r?"DONE":"PENDING"}`)}e.stdout.push("",n===3?"Recovery action: All artifacts complete. Run /comet-open user confirmation, then guard to transition.":n===0?"Recovery action: No artifacts created yet. Start from /comet-open Step 1 (explore and clarify).":"Recovery action: Some artifacts incomplete. Resume /comet-open from the first missing artifact.")}async function Y_(e,t,n){e.stdout.push(" Artifacts:");for(let o of["proposal.md","design.md","tasks.md"])e.stdout.push(` - ${o}: ${await At(D.join(n,o))?"DONE":"MISSING (unexpected in design phase)"}`);let i=await _(t,"handoff_context"),r=await _(t,"handoff_hash"),s=await _(t,"design_doc");e.stdout.push(""," Design progress:",await pe("handoff_context",i,i),await pe("handoff_hash",r),await pe("design_doc",s,s),""),s&&s!=="null"&&await oe(D.resolve(s))?e.stdout.push("Recovery action: Design Doc already created and linked. Run guard to transition to build."):i&&i!=="null"&&await oe(D.resolve(i))?e.stdout.push("Recovery action: Handoff generated but Design Doc not yet created. Resume from brainstorming confirmation (Step 1c)."):e.stdout.push("Recovery action: No handoff generated yet. Start from Step 1a (generate handoff package).")}async function G_(e,t,n,i){let r=await _(t,"isolation"),s=await _(t,"build_mode"),o=await _(t,"build_pause"),a=await _(t,"subagent_dispatch"),c=await _(t,"tdd_mode"),l=await _(t,"review_mode"),f=await _(t,"plan"),u=[" Build decisions:",await pe("isolation",r),await pe("build_mode",s),await pe("build_pause",o),await pe("tdd_mode",c),await pe("review_mode",l)];(s==="subagent-driven-development"||a&&a!=="null")&&u.push(await pe("subagent_dispatch",a)),e.stdout.push(...u,""," Plan:",await pe("plan",f,f),"");let d=D.join(n,"tasks.md");if(!await oe(d)){e.stdout.push(" Tasks: tasks.md MISSING","","Recovery action: tasks.md missing. Verify change directory integrity.");return}let h=(await B(P(),d,{label:"Classic change tasks"})).split(/\r?\n/u),g=h.filter(E=>/^\s*- \[[ xX]\] /u.test(E)).length,p=h.filter(E=>/^\s*- \[[xX]\] /u.test(E)).length,m=g-p,w=0,y=0;if(f&&f!=="null"&&await oe(f)){let E=(await B(P(),f,{label:"Classic build plan"})).split(/\r?\n/u);w=E.filter(R=>/^\s*- \[[ xX]\] /u.test(R)).length,y=E.filter(R=>/^\s*- \[[xX]\] /u.test(R)).length}let C=w-y;e.stdout.push(` Tasks: ${p}/${g} done, ${m} pending`),w>0&&e.stdout.push(` Plan tasks: ${y}/${w} done, ${C} pending`),e.stdout.push("");let k=z_(i,r,s,o,a,c,l,f,m,C);e.stdout.push(k)}function un(e){return!e||e==="null"}function z_(e,t,n,i,r,s,o,a,c,l){let f=a&&a!=="null",u=e==="full"&&(un(s)||un(o));return i==="plan-ready"&&f&&(un(t)||un(n)||u)?e==="full"?"Recovery action: Plan-ready pause detected. Ask the user whether to continue, then choose isolation, build mode, TDD mode, and review mode without regenerating the plan.":"Recovery action: Plan-ready pause detected. Ask the user whether to continue, then choose isolation and build mode without regenerating the plan.":i==="plan-ready"&&!f?"Recovery action: Plan-ready pause is recorded, but the plan file is missing. Restore the plan file or rerun writing-plans before choosing execution.":i==="plan-ready"?n==="subagent-driven-development"&&(c>0||l>0)?r==="confirmed"?"Recovery action: Plan-ready pause is stale because build decisions are already selected. Clear build_pause to null, then inspect the first unchecked task (OpenSpec or plan additions) against recent git history/diff. If implemented, check it off; otherwise dispatch a subagent. Do not execute the pending task directly in the main window.":"Recovery action: Plan-ready pause is stale and selected subagent execution is not recorded. Run comet state set <change-name> subagent_dispatch confirmed, then continue from the first unchecked task through subagent execution.":c>0||l>0?"Recovery action: Plan-ready pause is stale because build decisions are already selected. Clear build_pause to null, then continue from the first unchecked task.":"Recovery action: Plan-ready pause is stale and all tasks are done. Clear build_pause to null, then run guard to transition to verify.":un(t)?"Recovery action: Isolation not selected. Use the current platform's user confirmation mechanism to ask user for branch/worktree choice.":un(n)?"Recovery action: Build mode not selected. Use the current platform's user confirmation mechanism to ask user for execution method.":e==="full"&&un(s)?"Recovery action: TDD mode not selected. Use the current platform's user confirmation mechanism to ask user for tdd or direct.":e==="full"&&un(o)?"Recovery action: Review mode not selected. Use the current platform's user confirmation mechanism to ask user for off, standard, or thorough.":c>0?n==="subagent-driven-development"?r==="confirmed"?"Recovery action: Read tasks.md and the Superpowers plan (which may include additions beyond OpenSpec), then inspect the first unchecked task against recent git history/diff. If implemented, check it off; otherwise dispatch a subagent. Do not execute the pending task directly in the main window.":"Recovery action: Selected subagent execution is not recorded. Run comet state set <change-name> subagent_dispatch confirmed, then continue from the first unchecked task through subagent execution.":"Recovery action: Read tasks.md and continue from first unchecked task.":l>0?n==="subagent-driven-development"?r==="confirmed"?"Recovery action: Read the Superpowers plan, then inspect the first unchecked Superpowers plan task against recent git history/diff. If implemented, check it off; otherwise dispatch a subagent. Do not execute the pending task directly in the main window.":"Recovery action: Selected subagent execution is not recorded. Run comet state set <change-name> subagent_dispatch confirmed, then continue from the first unchecked task through subagent execution.":"Recovery action: Read the Superpowers plan and continue from the first unchecked plan task.":"Recovery action: All tasks done. Run guard to transition to verify."}async function X_(e,t){let n=await _(t,"verify_result"),i=await _(t,"verify_failures"),r=await _(t,"verify_mode"),s=await _(t,"verification_report"),o=await _(t,"branch_status");e.stdout.push(" Verification:",await pe("verify_result",n),` - verify_failures: ${i||"0"}`,await pe("verify_mode",r),await pe("verification_report",s,s),o==="handled"?" - branch_status: LEGACY (handled before archive; archive still owns final closure)":" - branch_status: DEFERRED (handled after the archive commit)","",n==="pass"?"Recovery action: Verification complete. Continue to archive; branch handling happens after archive changes are committed.":n==="fail"?"Recovery action: Verification failed and rolled back to build. Resume from /comet-build.":"Recovery action: Verification not yet started or in progress. Run scale assessment then verify.")}async function Q_(e,t){let n=await _(t,"archive_confirmation");e.stdout.push(" Archive:",await pe("verify_result",await _(t,"verify_result")),await pe("archive_confirmation",n),await pe("archived",await _(t,"archived")),"",n==="confirmed"?"Recovery action: Archive is confirmed. Run /comet-archive to complete archiving.":"Recovery action: Ask for final archive confirmation in /comet-archive before running the archive command.")}async function Z_(e,t){Ze(t);let{file:n,directory:i,label:r}=await lt(t);await oe(n)||S(`ERROR: .comet.yaml not found at ${r}/.comet.yaml`);let s=await _(t,"phase"),o=await _(t,"workflow");e.stdout.push(`=== Recovery Context: ${t} ===`,`Phase: ${s}`,`Workflow: ${o}`,"","State fields:"),s==="open"?await V_(e,i):s==="design"?await Y_(e,t,i):s==="build"?await G_(e,t,i,o):s==="verify"?await X_(e,t):s==="archive"?await Q_(e,t):S(`ERROR: Unknown phase: ${s}`),e.stdout.push("","=== End Recovery Context ===")}async function ex(e,t){Ze(t);let{file:n,directory:i,label:r}=await lt(t);await oe(n)||S(`ERROR: .comet.yaml not found at ${r}/.comet.yaml`);let s=D.join(i,"tasks.md"),o=await oe(s)?(await B(P(),s,{label:"Classic scale task file"})).split(/\r?\n/u).filter(g=>/^- \[/u.test(g)).length:0,a=D.join(i,"specs"),c=0;if(await oe(a))for(let g of await k_.readdir(a))await oe(D.join(a,g,"spec.md"))&&(c+=1);let l=await _(t,"plan"),f="";l&&l!=="null"&&await oe(l)&&(f=(await B(P(),l,{label:"Classic scale plan"})).match(/^base-ref:\s*(.+)$/mu)?.[1].trim()??""),f||(f=await _(t,"base_ref"));let u=bg(["diff","--name-only",...f&&f!=="null"?[`${f}...HEAD`]:["HEAD"]]),d=u?u.split(/\r?\n/u).filter(Boolean).length:0,h=o>3||c>1||d>8?"full":"light";await kg(new ra,t,"verify_mode",h),e.stderr.push(`=== Scale Assessment: ${t} ===`,` Tasks: ${o} (threshold: 3)`,` Delta specs: ${c} capabilities (threshold: 1)`,` Changed files: ${d} (threshold: 8)`,` → Result: ${h}`,Qe(`[SCALE] verify_mode=${h}`))}function tx(e){let t,n,i;for(let r=0;r<e.length;r+=2){let s=e[r];["--command","--exit-code","--cwd"].includes(s)||S(`ERROR: Unknown option: ${s}`);let o=e[r+1];o===void 0&&S(`ERROR: Missing value for option: ${s}`),s==="--command"?t=o:s==="--exit-code"?n=o:i=o}return t===void 0&&S("ERROR: Missing option: --command"),n===void 0&&S("ERROR: Missing option: --exit-code"),/^-?\d+$/u.test(n)||S("ERROR: --exit-code must be an integer"),{command:t,exitCode:Number(n),...i===void 0?{}:{cwd:i}}}async function nx(e,t,n,i){Ze(t),n!=="build"&&n!=="verify"&&S(`ERROR: Invalid command check scope: '${n}'`);let r=tx(i),{directory:s,file:o}=await lt(t),a=P(),c=(await Q(a)).changesDir;(D.dirname(s)!==c||!await oe(o))&&S(`ERROR: command checks require an active change: ${t}`);try{let l=await W(s,{migrate:!1});if(!l.classic||!l.run)throw new Error("command checks require an existing synchronized Classic Run");let{run:f}=await El(s,l),u=await Up(a,s,f,{scope:n,...r,cwd:r.cwd??(D.relative(a,Rt()).replaceAll("\\","/")||".")});e.stderr.push(Qe(`[RECORDED] ${u.scope} exit=${u.exitCode} cwd=${u.cwd} command=${u.command}`))}catch(l){S(`ERROR: ${l.message}`)}}function It(e,t,n){e.length<t&&S(n)}function ia(e,t,n){e.length!==t&&S(n)}var ix=new Set(["init","set","transition","check","scale","record-check","rebind","select","clear-selection"]);async function rx(e){if(!(!e||!ix.has(e)))try{await Ee(P())}catch(t){S(`ERROR: ${t instanceof Error?t.message:String(t)}`)}}async function sx(e,t){Ze(t);try{let n=await qp(P(),t),i=await _(t,"bound_branch"),r=i&&i!=="null"?i:null;e.stderr.push(Qe(`[SELECTED] current change: ${n.change}${r?` (branch: ${r})`:""}`))}catch(n){S(`ERROR: ${n instanceof Error?n.message:String(n)}`)}}async function ox(e,t){Ze(t);let{directory:n}=await lt(t),i=await _(t,"bound_branch");(!i||i==="null")&&S(`ERROR: '${t}' is not yet bound; use 'comet state set ${t} isolation <current|branch|worktree>' to establish the first binding`);let r=Io(Rt());r===null&&S("ERROR: cannot rebind while HEAD is detached; checkout a branch first");let s=await W(n);s.classic||S("ERROR: Classic state projection is missing"),await Il(n,r);let o={...s.classic,boundBranch:r};await Pn(n,{change:t,event:"rebind",source:"comet-state",from:s.classic,to:o,effects:[{field:"boundBranch",from:i,to:r}]}),e.stderr.push(Qe(`[REBIND] bound_branch: ${i} → ${r}`))}async function ax(e){let t=await To(P());if(t.status==="selected"){e.stdout.push(t.selection.change);return}t.status==="missing"&&S(`ERROR: no current change selected
|
|
289
|
+
Repair-only escape hatch: COMET_FORCE_PHASE=1 comet-state.mjs set <change-name> phase <value>`),await q_(n,i);let{file:s,directory:o}=await lt(t),a=await ca(s),c=a.toJS()??{};if(a.set(n,kg(n,i)),n==="isolation")if(No(i)){let u=typeof c.isolation=="string"?c.isolation:null,d=c.bound_branch;if(!(typeof d=="string"&&d!=="")||u!==i){let g=Rt(),p=Ao(g),m=$l({isolation:i,boundBranch:null,currentBranch:p,gitWorkTree:p===null?Ol(g):!0});m.status==="needs-heal"?a.set("bound_branch",m.branch):m.status==="unbound-detached"?S(`ERROR: cannot bind isolation=${i} while HEAD is detached; checkout a branch first`):a.set("bound_branch",null)}}else a.set("bound_branch",null);let l=await ur(o),f=mr(a.toJS(),l);if(f.run){f.classic||S("ERROR: migrated Run is missing its Classic projection");let u=await Ue(o,f),d=bt(f.classic,u),h=d!==f.run.currentStep,g={...f.run,currentStep:d,iteration:f.run.iteration+(h?1:0),status:d==="completed"?"completed":"running"};if(await Ne(o,{classic:f.classic,run:g,unknownKeys:f.unknownKeys}),h){let p=await Te(o,g.trajectoryRef);await De(o,g.trajectoryRef,{sequence:p.length+1,timestamp:new Date().toISOString(),type:"state_transitioned",runId:g.runId,data:{kind:"classic-config",field:n,fromStep:f.run.currentStep,toStep:d}})}}else await mu(s,a.toString());n==="phase"&&!r.internal&&e.stderr.push(pg("WARNING: Setting 'phase' directly bypasses state machine constraints."),pg(" Consider using: comet-state.mjs transition <change-name> <event>")),e.stderr.push(Qe(`[SET] ${n}=${i}`))}async function D_(e,t,n){Ze(t),aa(n,Lr);let i=await Tm(t,P()),{label:r,directory:s}=i,o=D.join(s,".comet.yaml");await oe(o)&&S(`ERROR: .comet.yaml already exists at ${r}/.comet.yaml`);let a=n!=="full",c=a?"off":await M_(),l=new qr.Document({workflow:n,language:await vg(),phase:"open",context_compression:await L_(),build_mode:a?"direct":null,build_pause:null,subagent_dispatch:null,tdd_mode:a?"direct":null,review_mode:c,isolation:null,verify_mode:a?"light":null,auto_transition:await bg()==="true",base_ref:Cg(["rev-parse","--verify","HEAD"]),design_doc:null,plan:null,verify_result:"pending",verify_failures:0,verification_report:null,branch_status:"pending",created_at:new Date().toISOString().slice(0,10),verified_at:null,archive_confirmation:null,archived:!1});await mu(o,l.toString()),e.stdout.push(Qe(`Initialized: ${r}/.comet.yaml (workflow=${n})`))}async function $t(e,t){let n=await _(e,"phase");n!==t&&S(`ERROR: Cannot transition '${e}': expected phase ${t}, got ${n}`)}async function F_(e){let t=await _(e,"workflow"),n=await _(e,"build_mode"),i=await _(e,"isolation"),r=await _(e,"direct_override"),s=await _(e,"subagent_dispatch"),o=await _(e,"tdd_mode"),a=await _(e,"review_mode");["current","branch","worktree"].includes(i)||S(`ERROR: Cannot transition '${e}': isolation must be current, branch, or worktree, got '${i||"null"}'`),["subagent-driven-development","executing-plans","direct"].includes(n)||S(`ERROR: Cannot transition '${e}': build_mode must be selected before leaving build, got '${n||"null"}'`),n==="direct"&&!["hotfix","tweak"].includes(t)&&r!=="true"&&S(`ERROR: Cannot transition '${e}': build_mode=direct is only allowed for hotfix/tweak unless direct_override=true`),n==="subagent-driven-development"&&s!=="confirmed"&&S(`ERROR: Cannot transition '${e}': subagent_dispatch must be confirmed before using build_mode=subagent-driven-development`),t==="full"&&(!o||o==="null")&&S(`ERROR: Cannot transition '${e}': tdd_mode must be selected before leaving build (full workflow)`),t==="full"&&!["off","standard","thorough"].includes(a)&&S(`ERROR: Cannot transition '${e}': review_mode must be selected before leaving build (full workflow); review_mode must be off, standard, or thorough, got '${a||"null"}'`)}async function B_(e){let{directory:t}=await lt(e),n=await _(e,"workflow");for(let i of["proposal.md","tasks.md"])await At(D.join(t,i))||S(`ERROR: Cannot transition '${e}': ${i} must exist and be non-empty before leaving open`);n==="full"&&!await At(D.join(t,"design.md"))&&S(`ERROR: Cannot transition '${e}': design.md must exist and be non-empty before leaving open`)}async function W_(e){let t=await _(e,"design_doc");(!t||t==="null"||!await At(D.resolve(t)))&&S(`ERROR: Cannot transition '${e}': design_doc must point to an existing Design Doc before leaving design`)}async function H_(e,t){let n=D.join(e,".comet.yaml"),i=await ca(n);for(let r of t){let s=wg(r.field);i.set(s,kg(s,yg(r.to)))}await mu(n,i.toString())}async function K_(e,t,n){let{directory:i}=await lt(t),r=await W(i),s=r.classic,o=!1;if(!s){r.run&&S("ERROR: Classic state projection is missing");let c=await ca(D.join(i,".comet.yaml"));s=j_(c.toJS()),o=!0}let a=ai(s,n);r.run?await rn(i,a.classic,r.run,{event:n,source:"comet-state"}):o?await H_(i,a.effects):await Ne(i,{classic:a.classic,run:null,unknownKeys:r.unknownKeys}),await Pn(i,{change:t,event:n,source:"comet-state",from:s,to:a.classic,effects:a.effects});for(let c of a.effects)e.stderr.push(Qe(`[SET] ${wg(c.field)}=${yg(c.to)}`));e.stderr.push(Qe(`[TRANSITION] ${n}`))}async function J_(e,t,n){if(Ze(t),aa(n,P_),n==="open-complete")await $t(t,"open"),await B_(t);else if(n==="design-complete")await $t(t,"design"),await W_(t);else if(n==="build-complete")await $t(t,"build"),await F_(t);else if(n==="verify-pass"){await $t(t,"verify");let i=await _(t,"verification_report");(!i||!await oe(D.resolve(i)))&&S(`ERROR: Cannot transition '${t}': verification_report must point to an existing report file`)}else if(n==="verify-fail")await $t(t,"verify");else if(n==="archive-confirm")await $t(t,"archive"),await _(t,"verify_result")!=="pass"&&S(`ERROR: Cannot transition '${t}': verify_result must be pass before archiving`),await _(t,"archived")==="true"&&S(`ERROR: Cannot transition '${t}': already archived`);else if(n==="preset-escalate"){await $t(t,"build");let i=await _(t,"workflow");["hotfix","tweak"].includes(i)||S(`ERROR: Cannot transition '${t}': preset-escalate only applies to hotfix/tweak, got workflow='${i}'`)}else n==="archive-reopen"?(await $t(t,"archive"),await _(t,"archived")==="true"&&S(`ERROR: Cannot transition '${t}': already archived`)):(await $t(t,"archive"),await _(t,"verify_result")!=="pass"&&S(`ERROR: Cannot transition '${t}': verify_result must be pass before archiving`),await _(t,"archive_confirmation")!=="confirmed"&&S(`ERROR: Cannot transition '${t}': archive_confirmation must be confirmed before archiving`));await K_(e,t,n)}async function U_(e,t){Ze(t);let{file:n,label:i}=await lt(t);await oe(n)||S(`ERROR: .comet.yaml not found at ${i}/.comet.yaml`);let r=await _(t,"phase"),s=await _(t,"workflow"),o=await _(t,"auto_transition");if(await _(t,"archived")==="true"){e.stdout.push("NEXT: done");return}let a=r==="open"?"comet-open":r==="design"?"comet-design":r==="verify"?"comet-verify":r==="archive"?"comet-archive":r==="build"?s==="hotfix"?"comet-hotfix":s==="tweak"?"comet-tweak":"comet-build":null;a||S(`ERROR: Cannot resolve next step for '${t}': unknown phase '${r||"null"}'`),e.stdout.push(`NEXT: ${o==="false"?"manual":"auto"}`,`SKILL: ${a}`),o==="false"&&e.stdout.push(`HINT: phase is '${r}'; run /${a} manually to continue`)}async function V_(e,t,n){gg(t,"task file"),n||S("ERROR: Task text cannot be empty");let i=D.resolve(P(),t);await oe(i)||S(`ERROR: Task file not found: ${t}`);let s=(await B(P(),i,{label:"Classic task-checkoff file"})).split(/\r?\n/u).filter(a=>[`- [ ] ${n}`,`- [x] ${n}`,`- [X] ${n}`].includes(a)),o=s.filter(a=>/^- \[[xX]\] /u.test(a));s.length!==1&&S(`ERROR: task text must appear exactly once in ${t} (found ${s.length}): ${n}`),o.length!==1&&S(`ERROR: task is not checked in ${t}: ${n}`),e.stdout.push("TASK_CHECKOFF: PASS",`FILE: ${t}`,`TASK: ${n}`)}async function Y_(e,t,n){Ze(t),aa(n,du);let{file:i,directory:r,label:s}=await lt(t);e.stdout.push(`=== Entry Check: comet-${n} ===`),await oe(i)||S(`ERROR: .comet.yaml not found at ${s}/.comet.yaml`);let o=!1,a=u=>e.stdout.push(` ${Qe("[PASS]")} ${u}`),c=u=>{e.stdout.push(` ${lu("[FAIL]")} ${u}`),o=!0},l=async(u,d)=>{let h=await _(t,u);(h===d?a:c)(`${u}=${h} (expected: ${d})`)};if(a(".comet.yaml exists"),await l("phase",n),n==="design"){await l("workflow","full");let u=await _(t,"design_doc");(!u||u==="null"?a:c)(u?`design_doc=${u} (expected: empty/null)`:"design_doc is empty/null");for(let d of["proposal.md","design.md","tasks.md"])(await At(D.join(r,d))?a:c)(`${d} ${await At(D.join(r,d))?"non-empty":"missing or empty"}`)}else if(n==="build"){let u=await _(t,"workflow"),d=await _(t,"design_doc");u==="full"?(d&&d!=="null"&&await oe(D.resolve(d))?a:c)(`design_doc=${d} (expected: non-null and file exists)`):a(`workflow=${u} (design_doc not required)`);for(let h of["proposal.md","tasks.md"])(await At(D.join(r,h))?a:c)(`${h} ${await At(D.join(r,h))?"non-empty":"missing or empty"}`)}else if(n==="verify"){let u=await _(t,"verify_result");(["","null","pending"].includes(u)?a:c)(`verify_result=${u} (expected: pending or null)`)}else if(n==="archive"){await l("verify_result","pass");let u=await _(t,"archived");(u!=="true"?a:c)(`archived=${u} (expected: not true)`)}let f=await St(r,{heal:!0,cwd:Rt()});if(f.bindingRequired)switch(f.status){case"drift":c(To(t,f.boundBranch,f.currentBranch));break;case"unbound-detached":c(Et(t));break;case"healed":a(`bound_branch lazily set to ${f.branch}`);break;case"needs-heal":case"ok":case"not-applicable":a("bound_branch matches current branch");break;default:{let u=f;throw new Error(`unhandled branch binding status: ${JSON.stringify(u)}`)}}if(e.stdout.push(""),o)throw e.stderr.push(lu("BLOCKED — fix failing checks before proceeding")),new Mr("",1);e.stderr.push(Qe("ALL CHECKS PASSED — ready to proceed"))}async function pe(e,t,n){return!t||t==="null"?` - ${e}: PENDING`:n&&!await oe(D.resolve(n))?` - ${e}: BROKEN (path ${t} does not exist)`:` - ${e}: DONE (${t})`}async function G_(e,t){e.stdout.push(" Artifacts:");let n=0;for(let i of["proposal.md","design.md","tasks.md"]){let r=await At(D.join(t,i));r&&(n+=1),e.stdout.push(` - ${i}: ${r?"DONE":"PENDING"}`)}e.stdout.push("",n===3?"Recovery action: All artifacts complete. Run /comet-open user confirmation, then guard to transition.":n===0?"Recovery action: No artifacts created yet. Start from /comet-open Step 1 (explore and clarify).":"Recovery action: Some artifacts incomplete. Resume /comet-open from the first missing artifact.")}async function z_(e,t,n){e.stdout.push(" Artifacts:");for(let o of["proposal.md","design.md","tasks.md"])e.stdout.push(` - ${o}: ${await At(D.join(n,o))?"DONE":"MISSING (unexpected in design phase)"}`);let i=await _(t,"handoff_context"),r=await _(t,"handoff_hash"),s=await _(t,"design_doc");e.stdout.push(""," Design progress:",await pe("handoff_context",i,i),await pe("handoff_hash",r),await pe("design_doc",s,s),""),s&&s!=="null"&&await oe(D.resolve(s))?e.stdout.push("Recovery action: Design Doc already created and linked. Run guard to transition to build."):i&&i!=="null"&&await oe(D.resolve(i))?e.stdout.push("Recovery action: Handoff generated but Design Doc not yet created. Resume from brainstorming confirmation (Step 1c)."):e.stdout.push("Recovery action: No handoff generated yet. Start from Step 1a (generate handoff package).")}async function X_(e,t,n,i){let r=await _(t,"isolation"),s=await _(t,"build_mode"),o=await _(t,"build_pause"),a=await _(t,"subagent_dispatch"),c=await _(t,"tdd_mode"),l=await _(t,"review_mode"),f=await _(t,"plan"),u=[" Build decisions:",await pe("isolation",r),await pe("build_mode",s),await pe("build_pause",o),await pe("tdd_mode",c),await pe("review_mode",l)];(s==="subagent-driven-development"||a&&a!=="null")&&u.push(await pe("subagent_dispatch",a)),e.stdout.push(...u,""," Plan:",await pe("plan",f,f),"");let d=D.join(n,"tasks.md");if(!await oe(d)){e.stdout.push(" Tasks: tasks.md MISSING","","Recovery action: tasks.md missing. Verify change directory integrity.");return}let h=(await B(P(),d,{label:"Classic change tasks"})).split(/\r?\n/u),g=h.filter(E=>/^\s*- \[[ xX]\] /u.test(E)).length,p=h.filter(E=>/^\s*- \[[xX]\] /u.test(E)).length,m=g-p,w=0,y=0;if(f&&f!=="null"&&await oe(f)){let E=(await B(P(),f,{label:"Classic build plan"})).split(/\r?\n/u);w=E.filter(R=>/^\s*- \[[ xX]\] /u.test(R)).length,y=E.filter(R=>/^\s*- \[[xX]\] /u.test(R)).length}let C=w-y;e.stdout.push(` Tasks: ${p}/${g} done, ${m} pending`),w>0&&e.stdout.push(` Plan tasks: ${y}/${w} done, ${C} pending`),e.stdout.push("");let k=Q_(i,r,s,o,a,c,l,f,m,C);e.stdout.push(k)}function un(e){return!e||e==="null"}function Q_(e,t,n,i,r,s,o,a,c,l){let f=a&&a!=="null",u=e==="full"&&(un(s)||un(o));return i==="plan-ready"&&f&&(un(t)||un(n)||u)?e==="full"?"Recovery action: Plan-ready pause detected. Ask the user whether to continue, then choose isolation, build mode, TDD mode, and review mode without regenerating the plan.":"Recovery action: Plan-ready pause detected. Ask the user whether to continue, then choose isolation and build mode without regenerating the plan.":i==="plan-ready"&&!f?"Recovery action: Plan-ready pause is recorded, but the plan file is missing. Restore the plan file or rerun writing-plans before choosing execution.":i==="plan-ready"?n==="subagent-driven-development"&&(c>0||l>0)?r==="confirmed"?"Recovery action: Plan-ready pause is stale because build decisions are already selected. Clear build_pause to null, then inspect the first unchecked task (OpenSpec or plan additions) against recent git history/diff. If implemented, check it off; otherwise dispatch a subagent. Do not execute the pending task directly in the main window.":"Recovery action: Plan-ready pause is stale and selected subagent execution is not recorded. Run comet state set <change-name> subagent_dispatch confirmed, then continue from the first unchecked task through subagent execution.":c>0||l>0?"Recovery action: Plan-ready pause is stale because build decisions are already selected. Clear build_pause to null, then continue from the first unchecked task.":"Recovery action: Plan-ready pause is stale and all tasks are done. Clear build_pause to null, then run guard to transition to verify.":un(t)?"Recovery action: Isolation not selected. Use the current platform's user confirmation mechanism to ask user for branch/worktree choice.":un(n)?"Recovery action: Build mode not selected. Use the current platform's user confirmation mechanism to ask user for execution method.":e==="full"&&un(s)?"Recovery action: TDD mode not selected. Use the current platform's user confirmation mechanism to ask user for tdd or direct.":e==="full"&&un(o)?"Recovery action: Review mode not selected. Use the current platform's user confirmation mechanism to ask user for off, standard, or thorough.":c>0?n==="subagent-driven-development"?r==="confirmed"?"Recovery action: Read tasks.md and the Superpowers plan (which may include additions beyond OpenSpec), then inspect the first unchecked task against recent git history/diff. If implemented, check it off; otherwise dispatch a subagent. Do not execute the pending task directly in the main window.":"Recovery action: Selected subagent execution is not recorded. Run comet state set <change-name> subagent_dispatch confirmed, then continue from the first unchecked task through subagent execution.":"Recovery action: Read tasks.md and continue from first unchecked task.":l>0?n==="subagent-driven-development"?r==="confirmed"?"Recovery action: Read the Superpowers plan, then inspect the first unchecked Superpowers plan task against recent git history/diff. If implemented, check it off; otherwise dispatch a subagent. Do not execute the pending task directly in the main window.":"Recovery action: Selected subagent execution is not recorded. Run comet state set <change-name> subagent_dispatch confirmed, then continue from the first unchecked task through subagent execution.":"Recovery action: Read the Superpowers plan and continue from the first unchecked plan task.":"Recovery action: All tasks done. Run guard to transition to verify."}async function Z_(e,t){let n=await _(t,"verify_result"),i=await _(t,"verify_failures"),r=await _(t,"verify_mode"),s=await _(t,"verification_report"),o=await _(t,"branch_status");e.stdout.push(" Verification:",await pe("verify_result",n),` - verify_failures: ${i||"0"}`,await pe("verify_mode",r),await pe("verification_report",s,s),o==="handled"?" - branch_status: LEGACY (handled before archive; archive still owns final closure)":" - branch_status: DEFERRED (handled after the archive commit)","",n==="pass"?"Recovery action: Verification complete. Continue to archive; branch handling happens after archive changes are committed.":n==="fail"?"Recovery action: Verification failed and rolled back to build. Resume from /comet-build.":"Recovery action: Verification not yet started or in progress. Run scale assessment then verify.")}async function ex(e,t){let n=await _(t,"archive_confirmation");e.stdout.push(" Archive:",await pe("verify_result",await _(t,"verify_result")),await pe("archive_confirmation",n),await pe("archived",await _(t,"archived")),"",n==="confirmed"?"Recovery action: Archive is confirmed. Run /comet-archive to complete archiving.":"Recovery action: Ask for final archive confirmation in /comet-archive before running the archive command.")}async function tx(e,t){Ze(t);let{file:n,directory:i,label:r}=await lt(t);await oe(n)||S(`ERROR: .comet.yaml not found at ${r}/.comet.yaml`);let s=await _(t,"phase"),o=await _(t,"workflow");e.stdout.push(`=== Recovery Context: ${t} ===`,`Phase: ${s}`,`Workflow: ${o}`,"","State fields:"),s==="open"?await G_(e,i):s==="design"?await z_(e,t,i):s==="build"?await X_(e,t,i,o):s==="verify"?await Z_(e,t):s==="archive"?await ex(e,t):S(`ERROR: Unknown phase: ${s}`),e.stdout.push("","=== End Recovery Context ===")}async function nx(e,t){Ze(t);let{file:n,directory:i,label:r}=await lt(t);await oe(n)||S(`ERROR: .comet.yaml not found at ${r}/.comet.yaml`);let s=D.join(i,"tasks.md"),o=await oe(s)?(await B(P(),s,{label:"Classic scale task file"})).split(/\r?\n/u).filter(g=>/^- \[/u.test(g)).length:0,a=D.join(i,"specs"),c=0;if(await oe(a))for(let g of await E_.readdir(a))await oe(D.join(a,g,"spec.md"))&&(c+=1);let l=await _(t,"plan"),f="";l&&l!=="null"&&await oe(l)&&(f=(await B(P(),l,{label:"Classic scale plan"})).match(/^base-ref:\s*(.+)$/mu)?.[1].trim()??""),f||(f=await _(t,"base_ref"));let u=Cg(["diff","--name-only",...f&&f!=="null"?[`${f}...HEAD`]:["HEAD"]]),d=u?u.split(/\r?\n/u).filter(Boolean).length:0,h=o>3||c>1||d>8?"full":"light";await Sg(new sa,t,"verify_mode",h),e.stderr.push(`=== Scale Assessment: ${t} ===`,` Tasks: ${o} (threshold: 3)`,` Delta specs: ${c} capabilities (threshold: 1)`,` Changed files: ${d} (threshold: 8)`,` → Result: ${h}`,Qe(`[SCALE] verify_mode=${h}`))}function ix(e){let t,n,i;for(let r=0;r<e.length;r+=2){let s=e[r];["--command","--exit-code","--cwd"].includes(s)||S(`ERROR: Unknown option: ${s}`);let o=e[r+1];o===void 0&&S(`ERROR: Missing value for option: ${s}`),s==="--command"?t=o:s==="--exit-code"?n=o:i=o}return t===void 0&&S("ERROR: Missing option: --command"),n===void 0&&S("ERROR: Missing option: --exit-code"),/^-?\d+$/u.test(n)||S("ERROR: --exit-code must be an integer"),{command:t,exitCode:Number(n),...i===void 0?{}:{cwd:i}}}async function rx(e,t,n,i){Ze(t),n!=="build"&&n!=="verify"&&S(`ERROR: Invalid command check scope: '${n}'`);let r=ix(i),{directory:s,file:o}=await lt(t),a=P(),c=(await Z(a)).changesDir;(D.dirname(s)!==c||!await oe(o))&&S(`ERROR: command checks require an active change: ${t}`);try{let l=await W(s,{migrate:!1});if(!l.classic||!l.run)throw new Error("command checks require an existing synchronized Classic Run");let{run:f}=await El(s,l),u=await Vp(a,s,f,{scope:n,...r,cwd:r.cwd??(D.relative(a,Rt()).replaceAll("\\","/")||".")});e.stderr.push(Qe(`[RECORDED] ${u.scope} exit=${u.exitCode} cwd=${u.cwd} command=${u.command}`))}catch(l){S(`ERROR: ${l.message}`)}}function It(e,t,n){e.length<t&&S(n)}function ra(e,t,n){e.length!==t&&S(n)}var sx=new Set(["init","set","transition","check","scale","record-check","rebind","select","clear-selection"]);async function ox(e){if(!(!e||!sx.has(e)))try{await Ee(P())}catch(t){S(`ERROR: ${t instanceof Error?t.message:String(t)}`)}}async function ax(e,t){Ze(t);try{let n=await Dp(P(),t),i=await _(t,"bound_branch"),r=i&&i!=="null"?i:null;e.stderr.push(Qe(`[SELECTED] current change: ${n.change}${r?` (branch: ${r})`:""}`))}catch(n){S(`ERROR: ${n instanceof Error?n.message:String(n)}`)}}async function cx(e,t){Ze(t);let{directory:n}=await lt(t),i=await _(t,"bound_branch");(!i||i==="null")&&S(`ERROR: '${t}' is not yet bound; use 'comet state set ${t} isolation <current|branch|worktree>' to establish the first binding`);let r=Ao(Rt());r===null&&S("ERROR: cannot rebind while HEAD is detached; checkout a branch first");let s=await W(n);s.classic||S("ERROR: Classic state projection is missing"),await Il(n,r);let o={...s.classic,boundBranch:r};await Pn(n,{change:t,event:"rebind",source:"comet-state",from:s.classic,to:o,effects:[{field:"boundBranch",from:i,to:r}]}),e.stderr.push(Qe(`[REBIND] bound_branch: ${i} → ${r}`))}async function lx(e){let t=await jo(P());if(t.status==="selected"){e.stdout.push(t.selection.change);return}t.status==="missing"&&S(`ERROR: no current change selected
|
|
290
290
|
Use: comet-state.mjs select <change-name>`),S(`ERROR: current change selection is stale: ${t.reason}
|
|
291
|
-
Use: comet-state.mjs select <change-name>`)}async function
|
|
292
|
-
`))n.stderr.push(lu(r));return n.result(i.exitCode)}});var
|
|
293
|
-
`}}async function
|
|
291
|
+
Use: comet-state.mjs select <change-name>`)}async function ux(e){await Fp(P()),e.stderr.push(Qe("[CLEARED] current change selection"))}var Eg=async(e,t)=>ot(t,async()=>{let n=new sa;try{let[i,...r]=e;return await ox(i),i==="init"?(It(r,2,"Usage: comet-state.mjs init <change-name> <workflow>"),await D_(n,r[0],r[1])):i==="get"?(It(r,2,"Usage: comet-state.mjs get <change-name> <field>"),Ze(r[0]),n.stdout.push(await _(r[0],r[1]))):i==="set"?(It(r,3,"Usage: comet-state.mjs set <change-name> <field> <value>"),Ze(r[0]),await Sg(n,r[0],r[1],r[2])):i==="transition"?(It(r,2,"Usage: comet-state.mjs transition <change-name> <event>"),await J_(n,r[0],r[1])):i==="check"?(It(r,2,"Usage: comet-state.mjs check <change-name> <phase> [--recover]"),r[2]==="--recover"?await tx(n,r[0]):await Y_(n,r[0],r[1])):i==="scale"?(It(r,1,"Usage: comet-state.mjs scale <change-name>"),await nx(n,r[0])):i==="record-check"?(It(r,2,"Usage: comet state record-check <change> <build|verify> --command <text> --exit-code <int> [--cwd <path>]"),await rx(n,r[0],r[1],r.slice(2))):i==="task-checkoff"?(It(r,2,"Usage: comet-state.mjs task-checkoff <file> <task-text>"),await V_(n,r[0],r[1])):i==="rebind"?(ra(r,1,"Usage: comet-state.mjs rebind <change-name>"),await cx(n,r[0])):i==="select"?(ra(r,1,"Usage: comet-state.mjs select <change-name>"),await ax(n,r[0])):i==="current"?(ra(r,0,"Usage: comet-state.mjs current"),await lx(n)):i==="clear-selection"?(ra(r,0,"Usage: comet-state.mjs clear-selection"),await ux(n)):i==="next"?(It(r,1,"Usage: comet-state.mjs next <change-name>"),await U_(n,r[0])):S(`Unknown subcommand: ${i??""}`),n.result()}catch(i){if(!(i instanceof Mr))throw i;if(i.message)for(let r of i.message.split(`
|
|
292
|
+
`))n.stderr.push(lu(r));return n.result(i.exitCode)}});var _g=["state","validate","guard","handoff","archive","hook-guard","intent","resume-probe","openspec","root"],dx={state:Eg,validate:Do,guard:oh,handoff:gh,archive:Kp,"hook-guard":_h,intent:Nh,"resume-probe":Dh,openspec:Im,root:mg};function mx(e){return _g.includes(e)}function px(e){return e?{exitCode:64,stderr:`Unknown Classic command: ${e}`}:{exitCode:64,stderr:`Usage: comet-classic <${_g.join("|")}> [args]`}}async function hx(e,t,n,i){if(!e||!mx(e))return px(e);let r=i[e];if(!r)return{exitCode:70,stderr:`Classic command is not implemented: ${e}`};try{return await r(t,n)}catch(s){return{exitCode:70,stderr:s instanceof Error?s.message:String(s)}}}function gx(e,t){return{exitCode:t.exitCode,stdout:JSON.stringify({command:e??null,exitCode:t.exitCode,...t.stdout===void 0?{}:{stdout:t.stdout},...t.stderr===void 0?{}:{stderr:t.stderr}})+`
|
|
293
|
+
`}}async function wx(e,t=dx){let n=e[0]!=="openspec"&&e.includes("--json"),i=n?e.filter(o=>o!=="--json"):[...e],r=i.shift(),s=await hx(r,i,{json:n,invocationCwd:process.cwd()},t);return n?gx(r,s):s}async function yx(e=process.argv.slice(2)){let t=await wx(e);return t.stdout&&process.stdout.write(t.stdout),t.stderr&&process.stderr.write(t.stderr+(t.stderr.endsWith(`
|
|
294
294
|
`)?"":`
|
|
295
|
-
`)),t.exitCode}var
|
|
295
|
+
`)),t.exitCode}var Rg=process.argv[1];Rg&&import.meta.url===fx(Rg).href&&yx().then(e=>{process.exitCode=e});export{_g as CLASSIC_COMMANDS,yx as main,wx as runClassicCli};
|