@rpamis/comet 0.4.0-rc.1 → 0.4.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +3 -650
- package/assets/manifest.json +1 -1
- package/assets/skills/comet/scripts/comet-archive.mjs +74 -74
- package/assets/skills/comet/scripts/comet-guard.mjs +100 -100
- package/assets/skills/comet/scripts/comet-handoff.mjs +77 -77
- package/assets/skills/comet/scripts/comet-hook-guard.mjs +58 -59
- package/assets/skills/comet/scripts/comet-hook-router.mjs +103 -104
- package/assets/skills/comet/scripts/comet-intent.mjs +6 -6
- package/assets/skills/comet/scripts/comet-resume-probe.mjs +2 -2
- package/assets/skills/comet/scripts/comet-runtime.mjs +174 -175
- package/assets/skills/comet/scripts/comet-state.mjs +105 -105
- package/assets/skills/comet/scripts/comet-yaml-validate.mjs +2 -2
- package/assets/skills/comet-native/SKILL.md +5 -4
- package/assets/skills/comet-native/reference/commands.md +4 -4
- package/assets/skills/comet-native/scripts/comet-native-archive.mjs +108 -102
- package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +130 -124
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +96 -89
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +120 -114
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +112 -106
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +121 -115
- package/assets/skills/comet-native/scripts/comet-native-root.mjs +100 -94
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +164 -157
- package/assets/skills/comet-native/scripts/comet-native-select.mjs +113 -107
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +106 -100
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +94 -88
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +110 -104
- package/assets/skills-zh/comet-native/SKILL.md +5 -4
- package/assets/skills-zh/comet-native/reference/commands.md +4 -4
- package/dist/app/commands/status.d.ts.map +1 -1
- package/dist/app/commands/status.js +49 -9
- package/dist/app/commands/status.js.map +1 -1
- package/dist/app/commands/update.d.ts.map +1 -1
- package/dist/app/commands/update.js +1 -44
- package/dist/app/commands/update.js.map +1 -1
- package/dist/domains/comet-classic/classic-archive.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-archive.js +15 -0
- package/dist/domains/comet-classic/classic-archive.js.map +1 -1
- package/dist/domains/comet-classic/classic-cli.d.ts +8 -0
- package/dist/domains/comet-classic/classic-cli.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-cli.js +10 -0
- package/dist/domains/comet-classic/classic-cli.js.map +1 -1
- package/dist/domains/comet-classic/classic-guard.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-guard.js +20 -0
- package/dist/domains/comet-classic/classic-guard.js.map +1 -1
- package/dist/domains/comet-classic/classic-handoff.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-handoff.js +13 -0
- package/dist/domains/comet-classic/classic-handoff.js.map +1 -1
- package/dist/domains/comet-classic/classic-hook-guard.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-hook-guard.js +14 -15
- package/dist/domains/comet-classic/classic-hook-guard.js.map +1 -1
- package/dist/domains/comet-classic/classic-output-language.d.ts +73 -0
- package/dist/domains/comet-classic/classic-output-language.d.ts.map +1 -0
- package/dist/domains/comet-classic/classic-output-language.js +175 -0
- package/dist/domains/comet-classic/classic-output-language.js.map +1 -0
- package/dist/domains/comet-classic/classic-script-entry.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-script-entry.js +10 -0
- package/dist/domains/comet-classic/classic-script-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-state-command.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-state-command.js +43 -4
- package/dist/domains/comet-classic/classic-state-command.js.map +1 -1
- package/dist/domains/comet-entry/project-status.d.ts.map +1 -1
- package/dist/domains/comet-entry/project-status.js +15 -3
- package/dist/domains/comet-entry/project-status.js.map +1 -1
- package/dist/domains/comet-entry/types.d.ts +5 -1
- package/dist/domains/comet-entry/types.d.ts.map +1 -1
- package/dist/domains/comet-native/native-children.d.ts +16 -0
- package/dist/domains/comet-native/native-children.d.ts.map +1 -1
- package/dist/domains/comet-native/native-children.js +73 -7
- package/dist/domains/comet-native/native-children.js.map +1 -1
- package/dist/domains/comet-native/native-cli-help.d.ts.map +1 -1
- package/dist/domains/comet-native/native-cli-help.js +2 -1
- package/dist/domains/comet-native/native-cli-help.js.map +1 -1
- package/dist/domains/comet-native/native-cli-shared.d.ts +7 -1
- package/dist/domains/comet-native/native-cli-shared.d.ts.map +1 -1
- package/dist/domains/comet-native/native-cli-shared.js +51 -4
- package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
- package/dist/domains/comet-native/native-cli.d.ts.map +1 -1
- package/dist/domains/comet-native/native-cli.js +4 -2
- package/dist/domains/comet-native/native-cli.js.map +1 -1
- package/dist/domains/comet-native/native-loop-runtime.d.ts +4 -1
- package/dist/domains/comet-native/native-loop-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-loop-runtime.js +18 -3
- package/dist/domains/comet-native/native-loop-runtime.js.map +1 -1
- package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-next-command.js +1 -0
- package/dist/domains/comet-native/native-next-command.js.map +1 -1
- package/dist/domains/comet-native/native-output-language.d.ts +69 -0
- package/dist/domains/comet-native/native-output-language.d.ts.map +1 -0
- package/dist/domains/comet-native/native-output-language.js +369 -0
- package/dist/domains/comet-native/native-output-language.js.map +1 -0
- package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.js +44 -0
- package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
- package/dist/domains/comet-native/native-portable-runtime.d.ts +1 -0
- package/dist/domains/comet-native/native-portable-runtime.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-runtime.js +1 -1
- package/dist/domains/comet-native/native-portable-runtime.js.map +1 -1
- package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-state.js +5 -0
- package/dist/domains/comet-native/native-portable-state.js.map +1 -1
- package/dist/domains/comet-native/native-portable-types.d.ts +3 -0
- package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-types.js.map +1 -1
- package/dist/domains/comet-native/native-runner-input.d.ts +30 -28
- package/dist/domains/comet-native/native-runner-input.d.ts.map +1 -1
- package/dist/domains/comet-native/native-runner-input.js +5 -0
- package/dist/domains/comet-native/native-runner-input.js.map +1 -1
- package/dist/domains/comet-native/native-script-entry.d.ts +5 -4
- package/dist/domains/comet-native/native-script-entry.d.ts.map +1 -1
- package/dist/domains/comet-native/native-script-entry.js +8 -16
- package/dist/domains/comet-native/native-script-entry.js.map +1 -1
- package/dist/domains/comet-native/native-status-discovery.d.ts +31 -1
- package/dist/domains/comet-native/native-status-discovery.d.ts.map +1 -1
- package/dist/domains/comet-native/native-status-discovery.js +46 -8
- package/dist/domains/comet-native/native-status-discovery.js.map +1 -1
- package/dist/domains/dashboard/native-collector.d.ts.map +1 -1
- package/dist/domains/dashboard/native-collector.js +2 -0
- package/dist/domains/dashboard/native-collector.js.map +1 -1
- package/dist/domains/dashboard/web/index.html +14 -14
- package/dist/domains/workflow-contract/output-envelope.d.ts +59 -0
- package/dist/domains/workflow-contract/output-envelope.d.ts.map +1 -0
- package/dist/domains/workflow-contract/output-envelope.js +108 -0
- package/dist/domains/workflow-contract/output-envelope.js.map +1 -0
- package/dist/platform/version/version.d.ts +8 -0
- package/dist/platform/version/version.d.ts.map +1 -1
- package/dist/platform/version/version.js +58 -8
- package/dist/platform/version/version.js.map +1 -1
- package/eval/local/tasks/comet-native-wave-d-stagnation-stop/instruction.md +2 -0
- package/eval/local/tasks/comet-native-wave-d-stagnation-stop/task.toml +1 -0
- package/eval/local/tasks/comet-native-wave-d-stagnation-stop/validation/test_native_wave_d_stagnation_stop.py +37 -0
- package/package.json +1 -1
|
@@ -1,77 +1,77 @@
|
|
|
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
|
-
`)}};
|
|
6
|
-
`)?
|
|
4
|
+
var hP=Object.create;var Wm=Object.defineProperty;var pP=Object.getOwnPropertyDescriptor;var mP=Object.getOwnPropertyNames;var vP=Object.getPrototypeOf,gP=Object.prototype.hasOwnProperty;var Js=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,i)=>(typeof require<"u"?require:t)[i]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var C=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(i){throw t=0,i}};var wP=(e,t,i,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of mP(t))!gP.call(e,n)&&n!==i&&Wm(e,n,{get:()=>t[n],enumerable:!(r=pP(t,n))||r.enumerable});return e};var Rn=(e,t,i)=>(i=e!=null?hP(vP(e)):{},wP(t||!e||!e.__esModule?Wm(i,"default",{value:e,enumerable:!0}):i,e));var G=C(je=>{"use strict";var hd=Symbol.for("yaml.alias"),ev=Symbol.for("yaml.document"),Ks=Symbol.for("yaml.map"),tv=Symbol.for("yaml.pair"),pd=Symbol.for("yaml.scalar"),Ys=Symbol.for("yaml.seq"),Ri=Symbol.for("yaml.node.type"),SP=e=>!!e&&typeof e=="object"&&e[Ri]===hd,EP=e=>!!e&&typeof e=="object"&&e[Ri]===ev,PP=e=>!!e&&typeof e=="object"&&e[Ri]===Ks,RP=e=>!!e&&typeof e=="object"&&e[Ri]===tv,iv=e=>!!e&&typeof e=="object"&&e[Ri]===pd,CP=e=>!!e&&typeof e=="object"&&e[Ri]===Ys;function rv(e){if(e&&typeof e=="object")switch(e[Ri]){case Ks:case Ys:return!0}return!1}function xP(e){if(e&&typeof e=="object")switch(e[Ri]){case hd:case Ks:case pd:case Ys:return!0}return!1}var AP=e=>(iv(e)||rv(e))&&!!e.anchor;je.ALIAS=hd;je.DOC=ev;je.MAP=Ks;je.NODE_TYPE=Ri;je.PAIR=tv;je.SCALAR=pd;je.SEQ=Ys;je.hasAnchor=AP;je.isAlias=SP;je.isCollection=rv;je.isDocument=EP;je.isMap=PP;je.isNode=xP;je.isPair=RP;je.isScalar=iv;je.isSeq=CP});var Wa=C(md=>{"use strict";var Ce=G(),ot=Symbol("break visit"),nv=Symbol("skip children"),oi=Symbol("remove node");function Xs(e,t){let i=av(t);Ce.isDocument(e)?Cn(null,e.contents,i,Object.freeze([e]))===oi&&(e.contents=null):Cn(null,e,i,Object.freeze([]))}Xs.BREAK=ot;Xs.SKIP=nv;Xs.REMOVE=oi;function Cn(e,t,i,r){let n=ov(e,t,i,r);if(Ce.isNode(n)||Ce.isPair(n))return sv(e,r,n),Cn(e,n,i,r);if(typeof n!="symbol"){if(Ce.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=Cn(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ot)return ot;o===oi&&(t.items.splice(a,1),a-=1)}}}else if(Ce.isPair(t)){r=Object.freeze(r.concat(t));let a=Cn("key",t.key,i,r);if(a===ot)return ot;a===oi&&(t.key=null);let o=Cn("value",t.value,i,r);if(o===ot)return ot;o===oi&&(t.value=null)}}return n}async function Qs(e,t){let i=av(t);Ce.isDocument(e)?await xn(null,e.contents,i,Object.freeze([e]))===oi&&(e.contents=null):await xn(null,e,i,Object.freeze([]))}Qs.BREAK=ot;Qs.SKIP=nv;Qs.REMOVE=oi;async function xn(e,t,i,r){let n=await ov(e,t,i,r);if(Ce.isNode(n)||Ce.isPair(n))return sv(e,r,n),xn(e,n,i,r);if(typeof n!="symbol"){if(Ce.isCollection(t)){r=Object.freeze(r.concat(t));for(let a=0;a<t.items.length;++a){let o=await xn(a,t.items[a],i,r);if(typeof o=="number")a=o-1;else{if(o===ot)return ot;o===oi&&(t.items.splice(a,1),a-=1)}}}else if(Ce.isPair(t)){r=Object.freeze(r.concat(t));let a=await xn("key",t.key,i,r);if(a===ot)return ot;a===oi&&(t.key=null);let o=await xn("value",t.value,i,r);if(o===ot)return ot;o===oi&&(t.value=null)}}return n}function av(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 ov(e,t,i,r){if(typeof i=="function")return i(e,t,r);if(Ce.isMap(t))return i.Map?.(e,t,r);if(Ce.isSeq(t))return i.Seq?.(e,t,r);if(Ce.isPair(t))return i.Pair?.(e,t,r);if(Ce.isScalar(t))return i.Scalar?.(e,t,r);if(Ce.isAlias(t))return i.Alias?.(e,t,r)}function sv(e,t,i){let r=t[t.length-1];if(Ce.isCollection(r))r.items[e]=i;else if(Ce.isPair(r))e==="key"?r.key=i:r.value=i;else if(Ce.isDocument(r))r.contents=i;else{let n=Ce.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}md.visit=Xs;md.visitAsync=Qs});var vd=C(lv=>{"use strict";var cv=G(),_P=Wa(),TP={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},IP=e=>e.replace(/[!,[\]{}]/g,t=>TP[t]),za=class e{constructor(t,i){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,i)}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,i){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),n=r.shift();switch(n){case"%TAG":{if(r.length!==2&&(i(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[a,o]=r;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return i(0,"%YAML directive should contain exactly one part"),!1;let[a]=r;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return i(6,`Unsupported YAML version ${a}`,o),!1}}default:return i(0,`Unknown directive ${n}`,!0),!1}}tagName(t,i){if(t==="!")return"!";if(t[0]!=="!")return i(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(i(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&i("Verbatim tags must end with a >"),o)}let[,r,n]=t.match(/^(.*!)([^!]*)$/s);n||i(`The ${t} tag has no suffix`);let a=this.tags[r];if(a)try{return a+decodeURIComponent(n)}catch(o){return i(String(o)),null}return r==="!"?t:(i(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[i,r]of Object.entries(this.tags))if(t.startsWith(r))return i+IP(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let i=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),n;if(t&&r.length>0&&cv.isNode(t.contents)){let a={};_P.visit(t.contents,(o,s)=>{cv.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of r)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&i.push(`%TAG ${a} ${o}`);return i.join(`
|
|
5
|
+
`)}};za.defaultYaml={explicit:!1,version:"1.2"};za.defaultTags={"!!":"tag:yaml.org,2002:"};lv.Directives=za});var Zs=C(Ja=>{"use strict";var uv=G(),jP=Wa();function $P(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let i=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(i)}return!0}function dv(e){let t=new Set;return jP.visit(e,{Value(i,r){r.anchor&&t.add(r.anchor)}}),t}function fv(e,t){for(let i=1;;++i){let r=`${e}${i}`;if(!t.has(r))return r}}function OP(e,t){let i=[],r=new Map,n=null;return{onAnchor:a=>{i.push(a),n??(n=dv(e));let o=fv(t,n);return n.add(o),o},setAnchors:()=>{for(let a of i){let o=r.get(a);if(typeof o=="object"&&o.anchor&&(uv.isScalar(o.node)||uv.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:r}}Ja.anchorIsValid=$P;Ja.anchorNames=dv;Ja.createNodeAnchors=OP;Ja.findNewAnchor=fv});var gd=C(hv=>{"use strict";function Ga(e,t,i,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let n=0,a=r.length;n<a;++n){let o=r[n],s=Ga(e,r,String(n),o);s===void 0?delete r[n]:s!==o&&(r[n]=s)}else if(r instanceof Map)for(let n of Array.from(r.keys())){let a=r.get(n),o=Ga(e,r,n,a);o===void 0?r.delete(n):o!==a&&r.set(n,o)}else if(r instanceof Set)for(let n of Array.from(r)){let a=Ga(e,r,n,n);a===void 0?r.delete(n):a!==n&&(r.delete(n),r.add(a))}else for(let[n,a]of Object.entries(r)){let o=Ga(e,r,n,a);o===void 0?delete r[n]:o!==a&&(r[n]=o)}return e.call(t,i,r)}hv.applyReviver=Ga});var Gi=C(mv=>{"use strict";var HP=G();function pv(e,t,i){if(Array.isArray(e))return e.map((r,n)=>pv(r,String(n),i));if(e&&typeof e.toJSON=="function"){if(!i||!HP.hasAnchor(e))return e.toJSON(t,i);let r={aliasCount:0,count:1,res:void 0};i.anchors.set(e,r),i.onCreate=a=>{r.res=a,delete i.onCreate};let n=e.toJSON(t,i);return i.onCreate&&i.onCreate(n),n}return typeof e=="bigint"&&!i?.keep?Number(e):e}mv.toJS=pv});var ec=C(gv=>{"use strict";var DP=gd(),vv=G(),LP=Gi(),wd=class{constructor(t){Object.defineProperty(this,vv.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:i,maxAliasCount:r,onAnchor:n,reviver:a}={}){if(!vv.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},s=LP.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?DP.applyReviver(a,{"":s},"",s):s}};gv.NodeBase=wd});var Ua=C(wv=>{"use strict";var MP=Zs(),FP=Wa(),An=G(),BP=ec(),VP=Gi(),yd=class extends BP.NodeBase{constructor(t){super(An.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,i){if(i?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;i?.aliasResolveCache?r=i.aliasResolveCache:(r=[],FP.visit(t,{Node:(a,o)=>{(An.isAlias(o)||An.hasAnchor(o))&&r.push(o)}}),i&&(i.aliasResolveCache=r));let n;for(let a of r){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,i){if(!i)return{source:this.source};let{anchors:r,doc:n,maxAliasCount:a}=i,o=this.resolve(n,i);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=r.get(o);if(s||(VP.toJS(o,null,i),s=r.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=tc(n,o,r)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,i,r){let n=`*${this.source}`;if(t){if(MP.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function tc(e,t,i){if(An.isAlias(t)){let r=t.resolve(e),n=i&&r&&i.get(r);return n?n.count*n.aliasCount:0}else if(An.isCollection(t)){let r=0;for(let n of t.items){let a=tc(e,n,i);a>r&&(r=a)}return r}else if(An.isPair(t)){let r=tc(e,t.key,i),n=tc(e,t.value,i);return Math.max(r,n)}return 1}wv.Alias=yd});var ke=C(Nd=>{"use strict";var qP=G(),WP=ec(),zP=Gi(),JP=e=>!e||typeof e!="function"&&typeof e!="object",Ui=class extends WP.NodeBase{constructor(t){super(qP.SCALAR),this.value=t}toJSON(t,i){return i?.keep?this.value:zP.toJS(this.value,t,i)}toString(){return String(this.value)}};Ui.BLOCK_FOLDED="BLOCK_FOLDED";Ui.BLOCK_LITERAL="BLOCK_LITERAL";Ui.PLAIN="PLAIN";Ui.QUOTE_DOUBLE="QUOTE_DOUBLE";Ui.QUOTE_SINGLE="QUOTE_SINGLE";Nd.Scalar=Ui;Nd.isScalarValue=JP});var Ka=C(Nv=>{"use strict";var GP=Ua(),Jr=G(),yv=ke(),UP="tag:yaml.org,2002:";function KP(e,t,i){if(t){let r=i.filter(a=>a.tag===t),n=r.find(a=>!a.format)??r[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return i.find(r=>r.identify?.(e)&&!r.format)}function YP(e,t,i){if(Jr.isDocument(e)&&(e=e.contents),Jr.isNode(e))return e;if(Jr.isPair(e)){let d=i.schema[Jr.MAP].createNode?.(i.schema,null,i);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=i,c;if(r&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new GP.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=UP+t.slice(2));let l=KP(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new yv.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Jr.MAP]:Symbol.iterator in Object(e)?o[Jr.SEQ]:o[Jr.MAP]}a&&(a(l),delete i.onTagObj);let u=l?.createNode?l.createNode(i.schema,e,i):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(i.schema,e,i):new yv.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}Nv.createNode=YP});var rc=C(ic=>{"use strict";var XP=Ka(),si=G(),QP=ec();function bd(e,t,i){let r=i;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=r,r=o}else r=new Map([[a,r]])}return XP.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var bv=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,kd=class extends QP.NodeBase{constructor(t,i){super(t),Object.defineProperty(this,"schema",{value:i,configurable:!0,enumerable:!1,writable:!0})}clone(t){let i=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(i.schema=t),i.items=i.items.map(r=>si.isNode(r)||si.isPair(r)?r.clone(t):r),this.range&&(i.range=this.range.slice()),i}addIn(t,i){if(bv(t))this.add(i);else{let[r,...n]=t,a=this.get(r,!0);if(si.isCollection(a))a.addIn(n,i);else if(a===void 0&&this.schema)this.set(r,bd(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(t){let[i,...r]=t;if(r.length===0)return this.delete(i);let n=this.get(i,!0);if(si.isCollection(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}getIn(t,i){let[r,...n]=t,a=this.get(r,!0);return n.length===0?!i&&si.isScalar(a)?a.value:a:si.isCollection(a)?a.getIn(n,i):void 0}hasAllNullValues(t){return this.items.every(i=>{if(!si.isPair(i))return!1;let r=i.value;return r==null||t&&si.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[i,...r]=t;if(r.length===0)return this.has(i);let n=this.get(i,!0);return si.isCollection(n)?n.hasIn(r):!1}setIn(t,i){let[r,...n]=t;if(n.length===0)this.set(r,i);else{let a=this.get(r,!0);if(si.isCollection(a))a.setIn(n,i);else if(a===void 0&&this.schema)this.set(r,bd(this.schema,n,i));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}};ic.Collection=kd;ic.collectionFromPath=bd;ic.isEmptyPath=bv});var Ya=C(nc=>{"use strict";var ZP=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Sd(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var eR=(e,t,i)=>e.endsWith(`
|
|
6
|
+
`)?Sd(i,t):i.includes(`
|
|
7
7
|
`)?`
|
|
8
|
-
`+
|
|
9
|
-
`)i===
|
|
8
|
+
`+Sd(i,t):(e.endsWith(" ")?"":" ")+i;nc.indentComment=Sd;nc.lineComment=eR;nc.stringifyComment=ZP});var Sv=C(Xa=>{"use strict";var tR="flow",Ed="block",ac="quoted";function iR(e,t,i="flow",{indentAtStart:r,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof r=="number"&&(r>n-Math.max(2,a)?l.push(0):d=n-r);let f,h,v=!1,m=-1,p=-1,b=-1;i===Ed&&(m=kv(e,m,t.length),m!==-1&&(d=m+c));for(let y;y=e[m+=1];){if(i===ac&&y==="\\"){switch(p=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}b=m}if(y===`
|
|
9
|
+
`)i===Ed&&(m=kv(e,m,t.length)),d=m+t.length+c,f=void 0;else{if(y===" "&&h&&h!==" "&&h!==`
|
|
10
10
|
`&&h!==" "){let E=e[m+1];E&&E!==" "&&E!==`
|
|
11
|
-
`&&E!==" "&&(f=m)}if(m>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===
|
|
12
|
-
${t}${e.slice(0,k)}`:(i===
|
|
13
|
-
${t}${e.slice(E+1,k)}`)}return g}function
|
|
14
|
-
`);r=t,n=t+1,a=e[n]}return r}
|
|
15
|
-
`){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function
|
|
11
|
+
`&&E!==" "&&(f=m)}if(m>=d)if(f)l.push(f),d=f+c,f=void 0;else if(i===ac){for(;h===" "||h===" ";)h=y,y=e[m+=1],v=!0;let E=m>b+1?m-2:p-1;if(u[E])return e;l.push(E),u[E]=!0,d=E+c,f=void 0}else v=!0}h=y}if(v&&s&&s(),l.length===0)return e;o&&o();let g=e.slice(0,l[0]);for(let y=0;y<l.length;++y){let E=l[y],k=l[y+1]||e.length;E===0?g=`
|
|
12
|
+
${t}${e.slice(0,k)}`:(i===ac&&u[E]&&(g+=`${e[E]}\\`),g+=`
|
|
13
|
+
${t}${e.slice(E+1,k)}`)}return g}function kv(e,t,i){let r=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+i)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
14
|
+
`);r=t,n=t+1,a=e[n]}return r}Xa.FOLD_BLOCK=Ed;Xa.FOLD_FLOW=tR;Xa.FOLD_QUOTED=ac;Xa.foldFlowLines=iR});var Za=C(Ev=>{"use strict";var Wt=ke(),Ki=Sv(),sc=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),cc=e=>/^(%|---|\.\.\.)/m.test(e);function rR(e,t,i){if(!t||t<0)return!1;let r=t-i,n=e.length;if(n<=r)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
|
|
15
|
+
`){if(a-o>r)return!0;if(o=a+1,n-o<=r)return!1}return!0}function Qa(e,t){let i=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return i;let{implicitKey:r}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(cc(e)?" ":""),o="",s=0;for(let c=0,l=i[c];l;l=i[++c])if(l===" "&&i[c+1]==="\\"&&i[c+2]==="n"&&(o+=i.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(i[c+1]){case"u":{o+=i.slice(s,c);let u=i.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=i.substr(c,6)}c+=5,s=c+1}break;case"n":if(r||i[c+2]==='"'||i.length<n)c+=1;else{for(o+=i.slice(s,c)+`
|
|
16
16
|
|
|
17
17
|
`;i[c+2]==="\\"&&i[c+3]==="n"&&i[c+4]!=='"';)o+=`
|
|
18
|
-
`,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,r?o:
|
|
19
|
-
`)||/[ \t]\n|\n[ \t]/.test(e))return
|
|
20
|
-
${i}`)+"'";return t.implicitKey?r:
|
|
18
|
+
`,c+=2;o+=a,i[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+i.slice(s):i,r?o:Ki.foldFlowLines(o,a,Ki.FOLD_QUOTED,sc(t,!1))}function Pd(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
19
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return Qa(e,t);let i=t.indent||(cc(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
20
|
+
${i}`)+"'";return t.implicitKey?r:Ki.foldFlowLines(r,i,Ki.FOLD_FLOW,sc(t,!1))}function _n(e,t){let{singleQuote:i}=t.options,r;if(i===!1)r=Qa;else{let n=e.includes('"'),a=e.includes("'");n&&!a?r=Pd:a&&!n?r=Qa:r=i?Pd:Qa}return r(e,t)}var Rd;try{Rd=new RegExp(`(^|(?<!
|
|
21
21
|
))
|
|
22
22
|
+(?!
|
|
23
|
-
|$)`,"g")}catch{
|
|
23
|
+
|$)`,"g")}catch{Rd=/\n+(?!\n|$)/g}function oc({comment:e,type:t,value:i},r,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(i))return _n(i,r);let l=r.indent||(r.forceBlockIndent||cc(i)?" ":""),u=o==="literal"?!0:o==="folded"||t===Wt.Scalar.BLOCK_FOLDED?!1:t===Wt.Scalar.BLOCK_LITERAL?!0:!rR(i,c,l.length);if(!i)return u?`|
|
|
24
24
|
`:`>
|
|
25
25
|
`;let d,f;for(f=i.length;f>0;--f){let k=i[f-1];if(k!==`
|
|
26
26
|
`&&k!==" "&&k!==" ")break}let h=i.substring(f),v=h.indexOf(`
|
|
27
27
|
`);v===-1?d="-":i===h||v!==h.length-1?(d="+",a&&a()):d="",h&&(i=i.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(Rd,`$&${l}`));let m=!1,p,b=-1;for(p=0;p<i.length;++p){let k=i[p];if(k===" ")m=!0;else if(k===`
|
|
29
29
|
`)b=p;else break}let g=i.substring(0,b<p?b+1:p);g&&(i=i.substring(g.length),g=g.replace(/\n+/g,`$&${l}`));let E=(m?l?"2":"1":"")+d;if(e&&(E+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let k=i.replace(/\n+/g,`
|
|
30
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),S=!1,R=
|
|
30
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),S=!1,R=sc(r,!0);o!=="folded"&&t!==Wt.Scalar.BLOCK_FOLDED&&(R.onOverflow=()=>{S=!0});let N=Ki.foldFlowLines(`${g}${k}${h}`,l,Ki.FOLD_BLOCK,R);if(!S)return`>${E}
|
|
31
31
|
${l}${N}`}return i=i.replace(/\n+/g,`$&${l}`),`|${E}
|
|
32
|
-
${l}${g}${i}${h}`}function
|
|
33
|
-
`)||u&&/[[\]{},]/.test(a))return
|
|
34
|
-
`)?
|
|
35
|
-
`))return
|
|
36
|
-
${c}`);if(o){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(d),{compat:h,tags:v}=t.doc.schema;if(v.some(f)||h?.some(f))return
|
|
37
|
-
${t.indent}${s}`:s}
|
|
38
|
-
${s}:`):(p=`${p}:`,f&&(p+=
|
|
32
|
+
${l}${g}${i}${h}`}function nR(e,t,i,r){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
|
|
33
|
+
`)||u&&/[[\]{},]/.test(a))return _n(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
34
|
+
`)?_n(a,t):oc(e,t,i,r);if(!s&&!u&&n!==Wt.Scalar.PLAIN&&a.includes(`
|
|
35
|
+
`))return oc(e,t,i,r);if(cc(a)){if(c==="")return t.forceBlockIndent=!0,oc(e,t,i,r);if(s&&c===l)return _n(a,t)}let d=a.replace(/\n+/g,`$&
|
|
36
|
+
${c}`);if(o){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(d),{compat:h,tags:v}=t.doc.schema;if(v.some(f)||h?.some(f))return _n(a,t)}return s?d:Ki.foldFlowLines(d,c,Ki.FOLD_FLOW,sc(t,!1))}function aR(e,t,i,r){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==Wt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Wt.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Wt.Scalar.BLOCK_FOLDED:case Wt.Scalar.BLOCK_LITERAL:return n||a?_n(o.value,t):oc(o,t,i,r);case Wt.Scalar.QUOTE_DOUBLE:return Qa(o.value,t);case Wt.Scalar.QUOTE_SINGLE:return Pd(o.value,t);case Wt.Scalar.PLAIN:return nR(o,t,i,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}Ev.stringifyString=aR});var eo=C(Cd=>{"use strict";var oR=Zs(),Yi=G(),sR=Ya(),cR=Za();function lR(e,t){let i=Object.assign({blockQuote:!0,commentString:sR.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),r;switch(i.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:i.flowCollectionPadding?" ":"",indent:"",indentStep:typeof i.indent=="number"?" ".repeat(i.indent):" ",inFlow:r,options:i}}function uR(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let i,r;if(Yi.isScalar(t)){r=t.value;let n=e.filter(a=>a.identify?.(r));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}i=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else r=t,i=e.find(n=>n.nodeClass&&r instanceof n.nodeClass);if(!i){let n=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${n} value`)}return i}function dR(e,t,{anchors:i,doc:r}){if(!r.directives)return"";let n=[],a=(Yi.isScalar(e)||Yi.isCollection(e))&&e.anchor;a&&oR.anchorIsValid(a)&&(i.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(r.directives.tagString(o)),n.join(" ")}function fR(e,t,i,r){if(Yi.isPair(e))return e.toString(t,i,r);if(Yi.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=Yi.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=uR(t.doc.schema.tags,a));let o=dR(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,i,r):Yi.isScalar(a)?cR.stringifyString(a,t,i,r):a.toString(t,i,r);return o?Yi.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
37
|
+
${t.indent}${s}`:s}Cd.createStringifyContext=lR;Cd.stringify=fR});var xv=C(Cv=>{"use strict";var Ci=G(),Pv=ke(),Rv=eo(),to=Ya();function hR({key:e,value:t},i,r,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=i,f=Ci.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(Ci.isCollection(e)||!Ci.isNode(e)&&typeof e=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let h=!d&&(!e||f&&t==null&&!i.inFlow||Ci.isCollection(e)||(Ci.isScalar(e)?e.type===Pv.Scalar.BLOCK_FOLDED||e.type===Pv.Scalar.BLOCK_LITERAL:typeof e=="object"));i=Object.assign({},i,{allNullValues:!1,implicitKey:!h&&(d||!a),indent:s+c});let v=!1,m=!1,p=Rv.stringify(e,i,()=>v=!0,()=>m=!0);if(!h&&!i.inFlow&&p.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(i.inFlow){if(a||t==null)return v&&r&&r(),p===""?"?":h?`? ${p}`:p}else if(a&&!d||t==null&&h)return p=`? ${p}`,f&&!v?p+=to.lineComment(p,i.indent,l(f)):m&&n&&n(),p;v&&(f=null),h?(f&&(p+=to.lineComment(p,i.indent,l(f))),p=`? ${p}
|
|
38
|
+
${s}:`):(p=`${p}:`,f&&(p+=to.lineComment(p,i.indent,l(f))));let b,g,y;Ci.isNode(t)?(b=!!t.spaceBefore,g=t.commentBefore,y=t.comment):(b=!1,g=null,y=null,t&&typeof t=="object"&&(t=o.createNode(t))),i.implicitKey=!1,!h&&!f&&Ci.isScalar(t)&&(i.indentAtStart=p.length+1),m=!1,!u&&c.length>=2&&!i.inFlow&&!h&&Ci.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(i.indent=i.indent.substring(2));let E=!1,k=Rv.stringify(t,i,()=>E=!0,()=>m=!0),S=" ";if(f||b||g){if(S=b?`
|
|
39
39
|
`:"",g){let R=l(g);S+=`
|
|
40
|
-
${
|
|
40
|
+
${to.indentComment(R,i.indent)}`}k===""&&!i.inFlow?S===`
|
|
41
41
|
`&&y&&(S=`
|
|
42
42
|
|
|
43
43
|
`):S+=`
|
|
44
|
-
${i.indent}`}else if(!h&&
|
|
44
|
+
${i.indent}`}else if(!h&&Ci.isCollection(t)){let R=k[0],N=k.indexOf(`
|
|
45
45
|
`),w=N!==-1,P=i.inFlow??t.flow??t.items.length===0;if(w||!P){let F=!1;if(w&&(R==="&"||R==="!")){let $=k.indexOf(" ");R==="&"&&$!==-1&&$<N&&k[$+1]==="!"&&($=k.indexOf(" ",$+1)),($===-1||N<$)&&(F=!0)}F||(S=`
|
|
46
46
|
${i.indent}`)}}else(k===""||k[0]===`
|
|
47
|
-
`)&&(S="");return p+=S+k,i.inFlow?E&&r&&r():y&&!E?p+=
|
|
47
|
+
`)&&(S="");return p+=S+k,i.inFlow?E&&r&&r():y&&!E?p+=to.lineComment(p,i.indent,l(y)):m&&n&&n(),p}Cv.stringifyPair=hR});var Ad=C(xd=>{"use strict";var Av=Js("process");function pR(e,...t){e==="debug"&&console.log(...t)}function mR(e,t){(e==="debug"||e==="warn")&&(typeof Av.emitWarning=="function"?Av.emitWarning(t):console.warn(t))}xd.debug=pR;xd.warn=mR});var hc=C(fc=>{"use strict";var dc=G(),_v=ke(),lc="<<",uc={identify:e=>e===lc||typeof e=="symbol"&&e.description===lc,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new _v.Scalar(Symbol(lc)),{addToJSMap:Tv}),stringify:()=>lc},vR=(e,t)=>(uc.identify(t)||dc.isScalar(t)&&(!t.type||t.type===_v.Scalar.PLAIN)&&uc.identify(t.value))&&e?.doc.schema.tags.some(i=>i.tag===uc.tag&&i.default);function Tv(e,t,i){let r=Iv(e,i);if(dc.isSeq(r))for(let n of r.items)_d(e,t,n);else if(Array.isArray(r))for(let n of r)_d(e,t,n);else _d(e,t,r)}function _d(e,t,i){let r=Iv(e,i);if(!dc.isMap(r))throw new Error("Merge sources must be maps or map aliases");let n=r.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function Iv(e,t){return e&&dc.isAlias(t)?t.resolve(e.doc,e):t}fc.addMergeToJSMap=Tv;fc.isMergeKey=vR;fc.merge=uc});var Id=C(Ov=>{"use strict";var gR=Ad(),jv=hc(),wR=eo(),$v=G(),Td=Gi();function yR(e,t,{key:i,value:r}){if($v.isNode(i)&&i.addToJSMap)i.addToJSMap(e,t,r);else if(jv.isMergeKey(e,i))jv.addMergeToJSMap(e,t,r);else{let n=Td.toJS(i,"",e);if(t instanceof Map)t.set(n,Td.toJS(r,n,e));else if(t instanceof Set)t.add(n);else{let a=NR(i,n,e),o=Td.toJS(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function NR(e,t,i){if(t===null)return"";if(typeof t!="object")return String(t);if($v.isNode(e)&&i?.doc){let r=wR.createStringifyContext(i.doc,{});r.anchors=new Set;for(let a of i.anchors.keys())r.anchors.add(a.anchor);r.inFlow=!0,r.inStringifyKey=!0;let n=e.toString(r);if(!i.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),gR.warn(i.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),i.mapKeyWarned=!0}return n}return JSON.stringify(t)}Ov.addPairToJSMap=yR});var Xi=C(jd=>{"use strict";var Hv=Ka(),bR=xv(),kR=Id(),pc=G();function SR(e,t,i){let r=Hv.createNode(e,void 0,i),n=Hv.createNode(t,void 0,i);return new mc(r,n)}var mc=class e{constructor(t,i=null){Object.defineProperty(this,pc.NODE_TYPE,{value:pc.PAIR}),this.key=t,this.value=i}clone(t){let{key:i,value:r}=this;return pc.isNode(i)&&(i=i.clone(t)),pc.isNode(r)&&(r=r.clone(t)),new e(i,r)}toJSON(t,i){let r=i?.mapAsMap?new Map:{};return kR.addPairToJSMap(i,r,this)}toString(t,i,r){return t?.doc?bR.stringifyPair(this,t,i,r):JSON.stringify(this)}};jd.Pair=mc;jd.createPair=SR});var $d=C(Lv=>{"use strict";var Gr=G(),Dv=eo(),vc=Ya();function ER(e,t,i){return(t.inFlow??e.flow?RR:PR)(e,t,i)}function PR({comment:e,items:t},i,{blockItemPrefix:r,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=i,u=Object.assign({},i,{indent:a,type:null}),d=!1,f=[];for(let v=0;v<t.length;++v){let m=t[v],p=null;if(Gr.isNode(m))!d&&m.spaceBefore&&f.push(""),gc(i,f,m.commentBefore,d),m.comment&&(p=m.comment);else if(Gr.isPair(m)){let g=Gr.isNode(m.key)?m.key:null;g&&(!d&&g.spaceBefore&&f.push(""),gc(i,f,g.commentBefore,d))}d=!1;let b=Dv.stringify(m,u,()=>p=null,()=>d=!0);p&&(b+=vc.lineComment(b,a,l(p))),d&&p&&(d=!1),f.push(r+b)}let h;if(f.length===0)h=n.start+n.end;else{h=f[0];for(let v=1;v<f.length;++v){let m=f[v];h+=m?`
|
|
48
48
|
${c}${m}`:`
|
|
49
49
|
`}}return e?(h+=`
|
|
50
|
-
`+
|
|
51
|
-
`)),v<e.length-1?b+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((g,y)=>g+y.length+2,2)+(b.length+2)>t.options.lineWidth)),l&&(b+=",")),p&&(b+=
|
|
50
|
+
`+vc.indentComment(l(e),c),s&&s()):d&&o&&o(),h}function RR({items:e},t,{flowChars:i,itemIndent:r}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let v=0;v<e.length;++v){let m=e[v],p=null;if(Gr.isNode(m))m.spaceBefore&&d.push(""),gc(t,d,m.commentBefore,!1),m.comment&&(p=m.comment);else if(Gr.isPair(m)){let g=Gr.isNode(m.key)?m.key:null;g&&(g.spaceBefore&&d.push(""),gc(t,d,g.commentBefore,!1),g.comment&&(l=!0));let y=Gr.isNode(m.value)?m.value:null;y?(y.comment&&(p=y.comment),y.commentBefore&&(l=!0)):m.value==null&&g?.comment&&(p=g.comment)}p&&(l=!0);let b=Dv.stringify(m,c,()=>p=null);l||(l=d.length>u||b.includes(`
|
|
51
|
+
`)),v<e.length-1?b+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((g,y)=>g+y.length+2,2)+(b.length+2)>t.options.lineWidth)),l&&(b+=",")),p&&(b+=vc.lineComment(b,r,s(p))),d.push(b),u=d.length}let{start:f,end:h}=i;if(d.length===0)return f+h;if(!l){let v=d.reduce((m,p)=>m+p.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=f;for(let m of d)v+=m?`
|
|
52
52
|
${a}${n}${m}`:`
|
|
53
53
|
`;return`${v}
|
|
54
|
-
${n}${h}`}else return`${f}${o}${d.join(" ")}${o}${h}`}function
|
|
55
|
-
`:" ")}return
|
|
54
|
+
${n}${h}`}else return`${f}${o}${d.join(" ")}${o}${h}`}function gc({indent:e,options:{commentString:t}},i,r,n){if(r&&n&&(r=r.replace(/^\n+/,"")),r){let a=vc.indentComment(t(r),e);i.push(a.trimStart())}}Lv.stringifyCollection=ER});var Zi=C(Hd=>{"use strict";var CR=$d(),xR=Id(),AR=rc(),Qi=G(),wc=Xi(),_R=ke();function io(e,t){let i=Qi.isScalar(t)?t.value:t;for(let r of e)if(Qi.isPair(r)&&(r.key===t||r.key===i||Qi.isScalar(r.key)&&r.key.value===i))return r}var Od=class extends AR.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Qi.MAP,t),this.items=[]}static from(t,i,r){let{keepUndefined:n,replacer:a}=r,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(i,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(wc.createPair(c,l,r))};if(i instanceof Map)for(let[c,l]of i)s(c,l);else if(i&&typeof i=="object")for(let c of Object.keys(i))s(c,i[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,i){let r;Qi.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new wc.Pair(t,t?.value):r=new wc.Pair(t.key,t.value);let n=io(this.items,r.key),a=this.schema?.sortMapEntries;if(n){if(!i)throw new Error(`Key ${r.key} already set`);Qi.isScalar(n.value)&&_R.isScalarValue(r.value)?n.value.value=r.value:n.value=r.value}else if(a){let o=this.items.findIndex(s=>a(r,s)<0);o===-1?this.items.push(r):this.items.splice(o,0,r)}else this.items.push(r)}delete(t){let i=io(this.items,t);return i?this.items.splice(this.items.indexOf(i),1).length>0:!1}get(t,i){let n=io(this.items,t)?.value;return(!i&&Qi.isScalar(n)?n.value:n)??void 0}has(t){return!!io(this.items,t)}set(t,i){this.add(new wc.Pair(t,i),!0)}toJSON(t,i,r){let n=r?new r:i?.mapAsMap?new Map:{};i?.onCreate&&i.onCreate(n);for(let a of this.items)xR.addPairToJSMap(i,n,a);return n}toString(t,i,r){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Qi.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),CR.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:i})}};Hd.YAMLMap=Od;Hd.findPair=io});var Tn=C(Fv=>{"use strict";var TR=G(),Mv=Zi(),IR={collection:"map",default:!0,nodeClass:Mv.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return TR.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,i)=>Mv.YAMLMap.from(e,t,i)};Fv.map=IR});var er=C(Bv=>{"use strict";var jR=Ka(),$R=$d(),OR=rc(),Nc=G(),HR=ke(),DR=Gi(),Dd=class extends OR.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Nc.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let i=yc(t);return typeof i!="number"?!1:this.items.splice(i,1).length>0}get(t,i){let r=yc(t);if(typeof r!="number")return;let n=this.items[r];return!i&&Nc.isScalar(n)?n.value:n}has(t){let i=yc(t);return typeof i=="number"&&i<this.items.length}set(t,i){let r=yc(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[r];Nc.isScalar(n)&&HR.isScalarValue(i)?n.value=i:this.items[r]=i}toJSON(t,i){let r=[];i?.onCreate&&i.onCreate(r);let n=0;for(let a of this.items)r.push(DR.toJS(a,String(n++),i));return r}toString(t,i,r){return t?$R.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:i}):JSON.stringify(this)}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i)){let o=0;for(let s of i){if(typeof n=="function"){let c=i instanceof Set?s:String(o++);s=n.call(i,c,s)}a.items.push(jR.createNode(s,void 0,r))}}return a}};function yc(e){let t=Nc.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Bv.YAMLSeq=Dd});var In=C(qv=>{"use strict";var LR=G(),Vv=er(),MR={collection:"seq",default:!0,nodeClass:Vv.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return LR.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,i)=>Vv.YAMLSeq.from(e,t,i)};qv.seq=MR});var ro=C(Wv=>{"use strict";var FR=Za(),BR={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,i,r){return t=Object.assign({actualString:!0},t),FR.stringifyString(e,t,i,r)}};Wv.string=BR});var bc=C(Gv=>{"use strict";var zv=ke(),Jv={identify:e=>e==null,createNode:()=>new zv.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new zv.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Jv.test.test(e)?e:t.options.nullStr};Gv.nullTag=Jv});var Ld=C(Kv=>{"use strict";var VR=ke(),Uv={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new VR.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},i){if(e&&Uv.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?i.options.trueStr:i.options.falseStr}};Kv.boolTag=Uv});var jn=C(Yv=>{"use strict";function qR({format:e,minFractionDigits:t,tag:i,value:r}){if(typeof r=="bigint")return String(r);let n=typeof r=="number"?r:Number(r);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!i||i==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Yv.stringifyNumber=qR});var Fd=C(kc=>{"use strict";var WR=ke(),Md=jn(),zR={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:Md.stringifyNumber},JR={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():Md.stringifyNumber(e)}},GR={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 WR.Scalar(parseFloat(e)),i=e.indexOf(".");return i!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-i-1),t},stringify:Md.stringifyNumber};kc.float=GR;kc.floatExp=JR;kc.floatNaN=zR});var Vd=C(Ec=>{"use strict";var Xv=jn(),Sc=e=>typeof e=="bigint"||Number.isInteger(e),Bd=(e,t,i,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),i);function Qv(e,t,i){let{value:r}=e;return Sc(r)&&r>=0?i+r.toString(t):Xv.stringifyNumber(e)}var UR={identify:e=>Sc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,i)=>Bd(e,2,8,i),stringify:e=>Qv(e,8,"0o")},KR={identify:Sc,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,i)=>Bd(e,0,10,i),stringify:Xv.stringifyNumber},YR={identify:e=>Sc(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,i)=>Bd(e,2,16,i),stringify:e=>Qv(e,16,"0x")};Ec.int=KR;Ec.intHex=YR;Ec.intOct=UR});var eg=C(Zv=>{"use strict";var XR=Tn(),QR=bc(),ZR=In(),eC=ro(),tC=Ld(),qd=Fd(),Wd=Vd(),iC=[XR.map,ZR.seq,eC.string,QR.nullTag,tC.boolTag,Wd.intOct,Wd.int,Wd.intHex,qd.floatNaN,qd.floatExp,qd.float];Zv.schema=iC});var rg=C(ig=>{"use strict";var rC=ke(),nC=Tn(),aC=In();function tg(e){return typeof e=="bigint"||Number.isInteger(e)}var Pc=({value:e})=>JSON.stringify(e),oC=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Pc},{identify:e=>e==null,createNode:()=>new rC.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Pc},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Pc},{identify:tg,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:i})=>i?BigInt(e):parseInt(e,10),stringify:({value:e})=>tg(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:Pc}],sC={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},cC=[nC.map,aC.seq].concat(oC,sC);ig.schema=cC});var Jd=C(ng=>{"use strict";var no=Js("buffer"),zd=ke(),lC=Za(),uC={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof no.Buffer=="function")return no.Buffer.from(e,"base64");if(typeof atob=="function"){let i=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(i.length);for(let n=0;n<i.length;++n)r[n]=i.charCodeAt(n);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:i},r,n,a){if(!i)return"";let o=i,s;if(typeof no.Buffer=="function")s=o instanceof no.Buffer?o.toString("base64"):no.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]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=zd.Scalar.BLOCK_LITERAL),t!==zd.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=s.substr(f,c);s=u.join(t===zd.Scalar.BLOCK_LITERAL?`
|
|
55
|
+
`:" ")}return lC.stringifyString({comment:e,type:t,value:s},r,n,a)}};ng.binary=uC});var xc=C(Cc=>{"use strict";var Rc=G(),Gd=Xi(),dC=ke(),fC=er();function ag(e,t){if(Rc.isSeq(e))for(let i=0;i<e.items.length;++i){let r=e.items[i];if(!Rc.isPair(r)){if(Rc.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let n=r.items[0]||new Gd.Pair(new dC.Scalar(null));if(r.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${r.commentBefore}
|
|
56
56
|
${n.key.commentBefore}`:r.commentBefore),r.comment){let a=n.value??n.key;a.comment=a.comment?`${r.comment}
|
|
57
|
-
${a.comment}`:r.comment}r=n}e.items[i]=kc.isPair(r)?r:new zd.Pair(r)}}else t("Expected a sequence for this tag");return e}function tg(e,t,i){let{replacer:r}=i,n=new UR.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=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)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(zd.createPair(s,c,i))}return n}var KR={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:eg,createNode:tg};Sc.createPairs=tg;Sc.pairs=KR;Sc.resolvePairs=eg});var Ud=C(Gd=>{"use strict";var ig=J(),Jd=zi(),ro=Xi(),YR=Qi(),rg=Ec(),Jr=class e extends YR.YAMLSeq{constructor(){super(),this.add=ro.YAMLMap.prototype.add.bind(this),this.delete=ro.YAMLMap.prototype.delete.bind(this),this.get=ro.YAMLMap.prototype.get.bind(this),this.has=ro.YAMLMap.prototype.has.bind(this),this.set=ro.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(ig.isPair(n)?(a=Jd.toJS(n.key,"",i),o=Jd.toJS(n.value,a,i)):a=Jd.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=rg.createPairs(t,i,r),a=new this;return a.items=n.items,a}};Jr.tag="tag:yaml.org,2002:omap";var XR={collection:"seq",identify:e=>e instanceof Map,nodeClass:Jr,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=rg.resolvePairs(e,t),r=[];for(let{key:n}of i.items)ig.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Jr,i)},createNode:(e,t,i)=>Jr.from(e,t,i)};Gd.YAMLOMap=Jr;Gd.omap=XR});var cg=C(Kd=>{"use strict";var ng=be();function ag({value:e,source:t},i){return t&&(e?og:sg).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var og={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 ng.Scalar(!0),stringify:ag},sg={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 ng.Scalar(!1),stringify:ag};Kd.falseTag=sg;Kd.trueTag=og});var lg=C(Pc=>{"use strict";var QR=be(),Yd=Tn(),ZR={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:Yd.stringifyNumber},eC={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():Yd.stringifyNumber(e)}},tC={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 QR.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:Yd.stringifyNumber};Pc.float=tC;Pc.floatExp=eC;Pc.floatNaN=ZR});var dg=C(ao=>{"use strict";var ug=Tn(),no=e=>typeof e=="bigint"||Number.isInteger(e);function Rc(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return n==="-"?-1*a:a}function Xd(e,t,i){let{value:r}=e;if(no(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return ug.stringifyNumber(e)}var iC={identify:no,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>Rc(e,2,2,i),stringify:e=>Xd(e,2,"0b")},rC={identify:no,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>Rc(e,1,8,i),stringify:e=>Xd(e,8,"0")},nC={identify:no,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>Rc(e,0,10,i),stringify:ug.stringifyNumber},aC={identify:no,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>Rc(e,2,16,i),stringify:e=>Xd(e,16,"0x")};ao.int=nC;ao.intBin=iC;ao.intHex=aC;ao.intOct=rC});var Zd=C(Qd=>{"use strict";var Ac=J(),Cc=Ki(),xc=Xi(),Gr=class e extends xc.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;Ac.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new Cc.Pair(t.key,null):i=new Cc.Pair(t,null),xc.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=xc.findPair(this.items,t);return!i&&Ac.isPair(r)?Ac.isScalar(r.key)?r.key.value:r.key:r}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=xc.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Cc.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(Cc.createPair(o,null,r));return a}};Gr.tag="tag:yaml.org,2002:set";var oC={collection:"map",identify:e=>e instanceof Set,nodeClass:Gr,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Gr.from(e,t,i),resolve(e,t){if(Ac.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Gr,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Qd.YAMLSet=Gr;Qd.set=oC});var tf=C(_c=>{"use strict";var sC=Tn();function ef(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function fg(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return sC.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var cC={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:i})=>ef(e,i),stringify:fg},lC={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=>ef(e,!1),stringify:fg},hg={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(hg.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=ef(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};_c.floatTime=lC;_c.intTime=cC;_c.timestamp=hg});var vg=C(mg=>{"use strict";var uC=An(),dC=gc(),fC=_n(),hC=to(),pC=Wd(),pg=cg(),rf=lg(),Tc=dg(),mC=lc(),vC=Ud(),gC=Ec(),wC=Zd(),nf=tf(),yC=[uC.map,fC.seq,hC.string,dC.nullTag,pg.trueTag,pg.falseTag,Tc.intBin,Tc.intOct,Tc.int,Tc.intHex,rf.floatNaN,rf.floatExp,rf.float,pC.binary,mC.merge,vC.omap,gC.pairs,wC.set,nf.intTime,nf.floatTime,nf.timestamp];mg.schema=yC});var Rg=C(sf=>{"use strict";var Ng=An(),NC=gc(),bg=_n(),bC=to(),kC=Hd(),af=Md(),of=Fd(),SC=Kv(),EC=Qv(),kg=Wd(),oo=lc(),Sg=Ud(),Eg=Ec(),gg=vg(),Pg=Zd(),Ic=tf(),wg=new Map([["core",SC.schema],["failsafe",[Ng.map,bg.seq,bC.string]],["json",EC.schema],["yaml11",gg.schema],["yaml-1.1",gg.schema]]),yg={binary:kg.binary,bool:kC.boolTag,float:af.float,floatExp:af.floatExp,floatNaN:af.floatNaN,floatTime:Ic.floatTime,int:of.int,intHex:of.intHex,intOct:of.intOct,intTime:Ic.intTime,map:Ng.map,merge:oo.merge,null:NC.nullTag,omap:Sg.omap,pairs:Eg.pairs,seq:bg.seq,set:Pg.set,timestamp:Ic.timestamp},PC={"tag:yaml.org,2002:binary":kg.binary,"tag:yaml.org,2002:merge":oo.merge,"tag:yaml.org,2002:omap":Sg.omap,"tag:yaml.org,2002:pairs":Eg.pairs,"tag:yaml.org,2002:set":Pg.set,"tag:yaml.org,2002:timestamp":Ic.timestamp};function RC(e,t,i){let r=wg.get(t);if(r&&!e)return i&&!r.includes(oo.merge)?r.concat(oo.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(wg.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return i&&(n=n.concat(oo.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?yg[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(yg).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}sf.coreKnownTags=PC;sf.getTags=RC});var uf=C(Cg=>{"use strict";var cf=J(),CC=An(),xC=_n(),AC=to(),jc=Rg(),_C=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,lf=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?jc.getTags(t,"compat"):t?jc.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?jc.coreKnownTags:{},this.tags=jc.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,cf.MAP,{value:CC.map}),Object.defineProperty(this,cf.SCALAR,{value:AC.string}),Object.defineProperty(this,cf.SEQ,{value:xC.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?_C:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Cg.Schema=lf});var Ag=C(xg=>{"use strict";var TC=J(),df=Qa(),so=Ua();function IC(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=df.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(so.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(TC.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(so.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=df.stringify(e.contents,n,()=>s=null,c);s&&(l+=so.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(df.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
-
`)?(i.push("..."),i.push(
|
|
57
|
+
${a.comment}`:r.comment}r=n}e.items[i]=Rc.isPair(r)?r:new Gd.Pair(r)}}else t("Expected a sequence for this tag");return e}function og(e,t,i){let{replacer:r}=i,n=new fC.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=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)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(Gd.createPair(s,c,i))}return n}var hC={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ag,createNode:og};Cc.createPairs=og;Cc.pairs=hC;Cc.resolvePairs=ag});var Yd=C(Kd=>{"use strict";var sg=G(),Ud=Gi(),ao=Zi(),pC=er(),cg=xc(),Ur=class e extends pC.YAMLSeq{constructor(){super(),this.add=ao.YAMLMap.prototype.add.bind(this),this.delete=ao.YAMLMap.prototype.delete.bind(this),this.get=ao.YAMLMap.prototype.get.bind(this),this.has=ao.YAMLMap.prototype.has.bind(this),this.set=ao.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,i){if(!i)return super.toJSON(t);let r=new Map;i?.onCreate&&i.onCreate(r);for(let n of this.items){let a,o;if(sg.isPair(n)?(a=Ud.toJS(n.key,"",i),o=Ud.toJS(n.value,a,i)):a=Ud.toJS(n,"",i),r.has(a))throw new Error("Ordered maps must not include duplicate keys");r.set(a,o)}return r}static from(t,i,r){let n=cg.createPairs(t,i,r),a=new this;return a.items=n.items,a}};Ur.tag="tag:yaml.org,2002:omap";var mC={collection:"seq",identify:e=>e instanceof Map,nodeClass:Ur,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let i=cg.resolvePairs(e,t),r=[];for(let{key:n}of i.items)sg.isScalar(n)&&(r.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):r.push(n.value));return Object.assign(new Ur,i)},createNode:(e,t,i)=>Ur.from(e,t,i)};Kd.YAMLOMap=Ur;Kd.omap=mC});var hg=C(Xd=>{"use strict";var lg=ke();function ug({value:e,source:t},i){return t&&(e?dg:fg).test.test(t)?t:e?i.options.trueStr:i.options.falseStr}var dg={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 lg.Scalar(!0),stringify:ug},fg={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 lg.Scalar(!1),stringify:ug};Xd.falseTag=fg;Xd.trueTag=dg});var pg=C(Ac=>{"use strict";var vC=ke(),Qd=jn(),gC={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:Qd.stringifyNumber},wC={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():Qd.stringifyNumber(e)}},yC={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 vC.Scalar(parseFloat(e.replace(/_/g,""))),i=e.indexOf(".");if(i!==-1){let r=e.substring(i+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:Qd.stringifyNumber};Ac.float=yC;Ac.floatExp=wC;Ac.floatNaN=gC});var vg=C(so=>{"use strict";var mg=jn(),oo=e=>typeof e=="bigint"||Number.isInteger(e);function _c(e,t,i,{intAsBigInt:r}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(i){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,i);return n==="-"?-1*a:a}function Zd(e,t,i){let{value:r}=e;if(oo(r)){let n=r.toString(t);return r<0?"-"+i+n.substr(1):i+n}return mg.stringifyNumber(e)}var NC={identify:oo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,i)=>_c(e,2,2,i),stringify:e=>Zd(e,2,"0b")},bC={identify:oo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,i)=>_c(e,1,8,i),stringify:e=>Zd(e,8,"0")},kC={identify:oo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,i)=>_c(e,0,10,i),stringify:mg.stringifyNumber},SC={identify:oo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,i)=>_c(e,2,16,i),stringify:e=>Zd(e,16,"0x")};so.int=kC;so.intBin=NC;so.intHex=SC;so.intOct=bC});var tf=C(ef=>{"use strict";var jc=G(),Tc=Xi(),Ic=Zi(),Kr=class e extends Ic.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let i;jc.isPair(t)?i=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?i=new Tc.Pair(t.key,null):i=new Tc.Pair(t,null),Ic.findPair(this.items,i.key)||this.items.push(i)}get(t,i){let r=Ic.findPair(this.items,t);return!i&&jc.isPair(r)?jc.isScalar(r.key)?r.key.value:r.key:r}set(t,i){if(typeof i!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof i}`);let r=Ic.findPair(this.items,t);r&&!i?this.items.splice(this.items.indexOf(r),1):!r&&i&&this.items.push(new Tc.Pair(t))}toJSON(t,i){return super.toJSON(t,i,Set)}toString(t,i,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),i,r);throw new Error("Set items must all have null values")}static from(t,i,r){let{replacer:n}=r,a=new this(t);if(i&&Symbol.iterator in Object(i))for(let o of i)typeof n=="function"&&(o=n.call(i,o,o)),a.items.push(Tc.createPair(o,null,r));return a}};Kr.tag="tag:yaml.org,2002:set";var EC={collection:"map",identify:e=>e instanceof Set,nodeClass:Kr,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,i)=>Kr.from(e,t,i),resolve(e,t){if(jc.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Kr,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};ef.YAMLSet=Kr;ef.set=EC});var nf=C($c=>{"use strict";var PC=jn();function rf(e,t){let i=e[0],r=i==="-"||i==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=r.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return i==="-"?n(-1)*a:a}function gg(e){let{value:t}=e,i=o=>o;if(typeof t=="bigint")i=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return PC.stringifyNumber(e);let r="";t<0&&(r="-",t*=i(-1));let n=i(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),r+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var RC={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:i})=>rf(e,i),stringify:gg},CC={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=>rf(e,!1),stringify:gg},wg={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(wg.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,i,r,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(i,r-1,n,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=rf(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};$c.floatTime=CC;$c.intTime=RC;$c.timestamp=wg});var bg=C(Ng=>{"use strict";var xC=Tn(),AC=bc(),_C=In(),TC=ro(),IC=Jd(),yg=hg(),af=pg(),Oc=vg(),jC=hc(),$C=Yd(),OC=xc(),HC=tf(),of=nf(),DC=[xC.map,_C.seq,TC.string,AC.nullTag,yg.trueTag,yg.falseTag,Oc.intBin,Oc.intOct,Oc.int,Oc.intHex,af.floatNaN,af.floatExp,af.float,IC.binary,jC.merge,$C.omap,OC.pairs,HC.set,of.intTime,of.floatTime,of.timestamp];Ng.schema=DC});var Tg=C(lf=>{"use strict";var Pg=Tn(),LC=bc(),Rg=In(),MC=ro(),FC=Ld(),sf=Fd(),cf=Vd(),BC=eg(),VC=rg(),Cg=Jd(),co=hc(),xg=Yd(),Ag=xc(),kg=bg(),_g=tf(),Hc=nf(),Sg=new Map([["core",BC.schema],["failsafe",[Pg.map,Rg.seq,MC.string]],["json",VC.schema],["yaml11",kg.schema],["yaml-1.1",kg.schema]]),Eg={binary:Cg.binary,bool:FC.boolTag,float:sf.float,floatExp:sf.floatExp,floatNaN:sf.floatNaN,floatTime:Hc.floatTime,int:cf.int,intHex:cf.intHex,intOct:cf.intOct,intTime:Hc.intTime,map:Pg.map,merge:co.merge,null:LC.nullTag,omap:xg.omap,pairs:Ag.pairs,seq:Rg.seq,set:_g.set,timestamp:Hc.timestamp},qC={"tag:yaml.org,2002:binary":Cg.binary,"tag:yaml.org,2002:merge":co.merge,"tag:yaml.org,2002:omap":xg.omap,"tag:yaml.org,2002:pairs":Ag.pairs,"tag:yaml.org,2002:set":_g.set,"tag:yaml.org,2002:timestamp":Hc.timestamp};function WC(e,t,i){let r=Sg.get(t);if(r&&!e)return i&&!r.includes(co.merge)?r.concat(co.merge):r.slice();let n=r;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Sg.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return i&&(n=n.concat(co.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Eg[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Eg).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}lf.coreKnownTags=qC;lf.getTags=WC});var ff=C(Ig=>{"use strict";var uf=G(),zC=Tn(),JC=In(),GC=ro(),Dc=Tg(),UC=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,df=class e{constructor({compat:t,customTags:i,merge:r,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Dc.getTags(t,"compat"):t?Dc.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Dc.coreKnownTags:{},this.tags=Dc.getTags(i,this.name,r),this.toStringOptions=s??null,Object.defineProperty(this,uf.MAP,{value:zC.map}),Object.defineProperty(this,uf.SCALAR,{value:GC.string}),Object.defineProperty(this,uf.SEQ,{value:JC.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?UC:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Ig.Schema=df});var $g=C(jg=>{"use strict";var KC=G(),hf=eo(),lo=Ya();function YC(e,t){let i=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(i.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&i.push("---");let n=hf.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){i.length!==1&&i.unshift("");let c=a(e.commentBefore);i.unshift(lo.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(KC.isNode(e.contents)){if(e.contents.spaceBefore&&r&&i.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);i.push(lo.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=hf.stringify(e.contents,n,()=>s=null,c);s&&(l+=lo.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&i[i.length-1]==="---"?i[i.length-1]=`--- ${l}`:i.push(l)}else i.push(hf.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
|
|
58
|
+
`)?(i.push("..."),i.push(lo.indentComment(c,""))):i.push(`... ${c}`)}else i.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&i[i.length-1]!==""&&i.push(""),i.push(lo.indentComment(a(c),"")))}return i.join(`
|
|
59
59
|
`)+`
|
|
60
|
-
`}
|
|
60
|
+
`}jg.stringifyDocument=YC});var uo=C(Og=>{"use strict";var XC=Ua(),$n=rc(),Rt=G(),QC=Xi(),ZC=Gi(),ex=ff(),tx=$g(),pf=Zs(),ix=gd(),rx=Ka(),mf=vd(),vf=class e{constructor(t,i,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Rt.NODE_TYPE,{value:Rt.DOC});let n=null;typeof i=="function"||Array.isArray(i)?n=i:r===void 0&&i&&(r=i,i=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=a;let{version:o}=a;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new mf.Directives({version:o}),this.setSchema(o,r),this.contents=t===void 0?null:this.createNode(t,n,r)}clone(){let t=Object.create(e.prototype,{[Rt.NODE_TYPE]:{value:Rt.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=Rt.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){On(this.contents)&&this.contents.add(t)}addIn(t,i){On(this.contents)&&this.contents.addIn(t,i)}createAlias(t,i){if(!t.anchor){let r=pf.anchorNames(this);t.anchor=!i||r.has(i)?pf.findNewAnchor(i||"a",r):i}return new XC.Alias(t.anchor)}createNode(t,i,r){let n;if(typeof i=="function")t=i.call({"":t},"",t),n=i;else if(Array.isArray(i)){let p=g=>typeof g=="number"||g instanceof String||g instanceof Number,b=i.filter(p).map(String);b.length>0&&(i=i.concat(b)),n=i}else r===void 0&&i&&(r=i,i=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=r??{},{onAnchor:d,setAnchors:f,sourceObjects:h}=pf.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:h},m=rx.createNode(t,u,v);return s&&Rt.isCollection(m)&&(m.flow=!0),f(),m}createPair(t,i,r={}){let n=this.createNode(t,null,r),a=this.createNode(i,null,r);return new QC.Pair(n,a)}delete(t){return On(this.contents)?this.contents.delete(t):!1}deleteIn(t){return $n.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):On(this.contents)?this.contents.deleteIn(t):!1}get(t,i){return Rt.isCollection(this.contents)?this.contents.get(t,i):void 0}getIn(t,i){return $n.isEmptyPath(t)?!i&&Rt.isScalar(this.contents)?this.contents.value:this.contents:Rt.isCollection(this.contents)?this.contents.getIn(t,i):void 0}has(t){return Rt.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return $n.isEmptyPath(t)?this.contents!==void 0:Rt.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,i){this.contents==null?this.contents=$n.collectionFromPath(this.schema,[t],i):On(this.contents)&&this.contents.set(t,i)}setIn(t,i){$n.isEmptyPath(t)?this.contents=i:this.contents==null?this.contents=$n.collectionFromPath(this.schema,Array.from(t),i):On(this.contents)&&this.contents.setIn(t,i)}setSchema(t,i={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new mf.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new mf.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(i.schema instanceof Object)this.schema=i.schema;else if(r)this.schema=new ex.Schema(Object.assign(r,i));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:i,mapAsMap:r,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=ZC.toJS(this.contents,i??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?ix.applyReviver(o,{"":c},"",c):c}toJSON(t,i){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:i})}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 i=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${i}`)}return tx.stringifyDocument(this,t)}};function On(e){if(Rt.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Og.Document=vf});var po=C(ho=>{"use strict";var fo=class extends Error{constructor(t,i,r,n){super(),this.name=t,this.code=r,this.message=n,this.pos=i}},gf=class extends fo{constructor(t,i,r){super("YAMLParseError",t,i,r)}},wf=class extends fo{constructor(t,i,r){super("YAMLWarning",t,i,r)}},nx=(e,t)=>i=>{if(i.pos[0]===-1)return;i.linePos=i.pos.map(s=>t.linePos(s));let{line:r,col:n}=i.linePos[0];i.message+=` at line ${r}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),r>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);s.length>80&&(s=s.substring(0,79)+`…
|
|
61
61
|
`),o=s+o}if(/[^ ]/.test(o)){let s=1,c=i.linePos[1];c?.line===r&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);i.message+=`:
|
|
62
62
|
|
|
63
63
|
${o}
|
|
64
64
|
${l}
|
|
65
|
-
`}};
|
|
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 i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(
|
|
67
|
-
`+m.comment:s.comment=m.comment);continue}(m.newlineAfterProp||
|
|
68
|
-
`+y.comment:g.comment=y.comment);let E=new
|
|
69
|
-
`+S.comment:l.comment=S.comment),d=S.end;continue}!o&&i.options.strict&&
|
|
70
|
-
`+R:N.comment=R,S.comment=S.comment.substring(R.length+1)}}if(!o&&!E&&!S.found){let R=k?e(i,k,S,n):t(i,S.end,E,null,S,n);l.items.push(R),d=R.range[2],
|
|
71
|
-
`+w.comment:N.comment=w.comment);let F=new
|
|
72
|
-
`+p.comment:l.comment=p.comment),l.range=[r.offset,m,p.offset]}else l.range=[r.offset,m,m];return l}
|
|
65
|
+
`}};ho.YAMLError=fo;ho.YAMLParseError=gf;ho.YAMLWarning=wf;ho.prettifyError=nx});var mo=C(Hg=>{"use strict";function ax(e,{flow:t,indicator:i,next:r,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",h=!1,v=!1,m=null,p=null,b=null,g=null,y=null,E=null,k=null;for(let N of e)switch(v&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&a(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),m&&(l&&N.type!=="comment"&&N.type!=="newline"&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),N.type){case"space":!t&&(i!=="doc-start"||r?.type!=="flow-collection")&&N.source.includes(" ")&&(m=N),u=!0;break;case"comment":{u||a(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let w=N.source.substring(1)||" ";d?d+=f+w:d=w,f="",l=!1;break}case"newline":l?d?d+=N.source:(!E||i!=="seq-item-ind")&&(c=!0):f+=N.source,l=!0,h=!0,(p||b)&&(g=N),u=!0;break;case"anchor":p&&a(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&a(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),p=N,k??(k=N.offset),l=!1,u=!1,v=!0;break;case"tag":{b&&a(N,"MULTIPLE_TAGS","A node can have at most one tag"),b=N,k??(k=N.offset),l=!1,u=!1,v=!0;break}case i:(p||b)&&a(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),E&&a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${t??"collection"}`),E=N,l=i==="seq-item-ind"||i==="explicit-key-ind",u=!1;break;case"comma":if(t){y&&a(N,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),y=N,l=!1,u=!1;break}default:a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),l=!1,u=!1}let S=e[e.length-1],R=S?S.offset+S.source.length:n;return v&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&a(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(l&&m.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:y,found:E,spaceBefore:c,comment:d,hasNewline:h,anchor:p,tag:b,newlineAfterProp:g,end:R,start:k??R}}Hg.resolveProps=ax});var Lc=C(Dg=>{"use strict";function yf(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 i of t.start)if(i.type==="newline")return!0;if(t.sep){for(let i of t.sep)if(i.type==="newline")return!0}if(yf(t.key)||yf(t.value))return!0}return!1;default:return!0}}Dg.containsNewline=yf});var Nf=C(Lg=>{"use strict";var ox=Lc();function sx(e,t,i){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&ox.containsNewline(t)&&i(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Lg.flowIndentCheck=sx});var bf=C(Fg=>{"use strict";var Mg=G();function cx(e,t,i){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let n=typeof r=="function"?r:(a,o)=>a===o||Mg.isScalar(a)&&Mg.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,i))}Fg.mapIncludes=cx});var Jg=C(zg=>{"use strict";var Bg=Xi(),lx=Zi(),Vg=mo(),ux=Lc(),qg=Nf(),dx=bf(),Wg="All mapping items must start at the same column";function fx({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??lx.YAMLMap,s=new o(i.schema);i.atRoot&&(i.atRoot=!1);let c=r.offset,l=null;for(let u of r.items){let{start:d,key:f,sep:h,value:v}=u,m=Vg.resolveProps(d,{indicator:"explicit-key-ind",next:f??h?.[0],offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0}),p=!m.found;if(p){if(f&&(f.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&n(c,"BAD_INDENT",Wg)),!m.anchor&&!m.tag&&!h){l=m.end,m.comment&&(s.comment?s.comment+=`
|
|
67
|
+
`+m.comment:s.comment=m.comment);continue}(m.newlineAfterProp||ux.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==r.indent&&n(c,"BAD_INDENT",Wg);i.atKey=!0;let b=m.end,g=f?e(i,f,m,n):t(i,b,d,null,m,n);i.schema.compat&&qg.flowIndentCheck(r.indent,f,n),i.atKey=!1,dx.mapIncludes(i,s.items,g)&&n(b,"DUPLICATE_KEY","Map keys must be unique");let y=Vg.resolveProps(h??[],{indicator:"map-value-ind",next:v,offset:g.range[2],onError:n,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=y.end,y.found){p&&(v?.type==="block-map"&&!y.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),i.options.strict&&m.start<y.found.offset-1024&&n(g.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let E=v?e(i,v,y,n):t(i,c,h,null,y,n);i.schema.compat&&qg.flowIndentCheck(r.indent,v,n),c=E.range[2];let k=new Bg.Pair(g,E);i.options.keepSourceTokens&&(k.srcToken=u),s.items.push(k)}else{p&&n(g.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),y.comment&&(g.comment?g.comment+=`
|
|
68
|
+
`+y.comment:g.comment=y.comment);let E=new Bg.Pair(g);i.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[r.offset,c,l??c],s}zg.resolveBlockMap=fx});var Ug=C(Gg=>{"use strict";var hx=er(),px=mo(),mx=Nf();function vx({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=a?.nodeClass??hx.YAMLSeq,s=new o(i.schema);i.atRoot&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let c=r.offset,l=null;for(let{start:u,value:d}of r.items){let f=px.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let h=d?e(i,d,f,n):t(i,f.end,u,null,f,n);i.schema.compat&&mx.flowIndentCheck(r.indent,d,n),c=h.range[2],s.items.push(h)}return s.range=[r.offset,c,l??c],s}Gg.resolveBlockSeq=vx});var Hn=C(Kg=>{"use strict";function gx(e,t,i,r){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{i&&!a&&r(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:r(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}Kg.resolveEnd=gx});var Zg=C(Qg=>{"use strict";var wx=G(),yx=Xi(),Yg=Zi(),Nx=er(),bx=Hn(),Xg=mo(),kx=Lc(),Sx=bf(),kf="Block collections are not allowed within flow collections",Sf=e=>e&&(e.type==="block-map"||e.type==="block-seq");function Ex({composeNode:e,composeEmptyNode:t},i,r,n,a){let o=r.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Yg.YAMLMap:Nx.YAMLSeq),l=new c(i.schema);l.flow=!0;let u=i.atRoot;u&&(i.atRoot=!1),i.atKey&&(i.atKey=!1);let d=r.offset+r.start.source.length;for(let p=0;p<r.items.length;++p){let b=r.items[p],{start:g,key:y,sep:E,value:k}=b,S=Xg.resolveProps(g,{flow:s,indicator:"explicit-key-ind",next:y??E?.[0],offset:d,onError:n,parentIndent:r.indent,startOnNewline:!1});if(!S.found){if(!S.anchor&&!S.tag&&!E&&!k){p===0&&S.comma?n(S.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):p<r.items.length-1&&n(S.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),S.comment&&(l.comment?l.comment+=`
|
|
69
|
+
`+S.comment:l.comment=S.comment),d=S.end;continue}!o&&i.options.strict&&kx.containsNewline(y)&&n(y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(p===0)S.comma&&n(S.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(S.comma||n(S.start,"MISSING_CHAR",`Missing , between ${s} items`),S.comment){let R="";e:for(let N of g)switch(N.type){case"comma":case"space":break;case"comment":R=N.source.substring(1);break e;default:break e}if(R){let N=l.items[l.items.length-1];wx.isPair(N)&&(N=N.value??N.key),N.comment?N.comment+=`
|
|
70
|
+
`+R:N.comment=R,S.comment=S.comment.substring(R.length+1)}}if(!o&&!E&&!S.found){let R=k?e(i,k,S,n):t(i,S.end,E,null,S,n);l.items.push(R),d=R.range[2],Sf(k)&&n(R.range,"BLOCK_IN_FLOW",kf)}else{i.atKey=!0;let R=S.end,N=y?e(i,y,S,n):t(i,R,g,null,S,n);Sf(y)&&n(N.range,"BLOCK_IN_FLOW",kf),i.atKey=!1;let w=Xg.resolveProps(E??[],{flow:s,indicator:"map-value-ind",next:k,offset:N.range[2],onError:n,parentIndent:r.indent,startOnNewline:!1});if(w.found){if(!o&&!S.found&&i.options.strict){if(E)for(let $ of E){if($===w.found)break;if($.type==="newline"){n($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}S.start<w.found.offset-1024&&n(w.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else k&&("source"in k&&k.source?.[0]===":"?n(k,"MISSING_CHAR",`Missing space after : in ${s}`):n(w.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let P=k?e(i,k,w,n):w.found?t(i,w.end,E,null,w,n):null;P?Sf(k)&&n(P.range,"BLOCK_IN_FLOW",kf):w.comment&&(N.comment?N.comment+=`
|
|
71
|
+
`+w.comment:N.comment=w.comment);let F=new yx.Pair(N,P);if(i.options.keepSourceTokens&&(F.srcToken=b),o){let $=l;Sx.mapIncludes(i,$.items,N)&&n(R,"DUPLICATE_KEY","Map keys must be unique"),$.items.push(F)}else{let $=new Yg.YAMLMap(i.schema);$.flow=!0,$.items.push(F);let Fe=(P??N).range;$.range=[N.range[0],Fe[1],Fe[2]],l.items.push($)}d=P?P.range[2]:w.end}}let f=o?"}":"]",[h,...v]=r.end,m=d;if(h?.source===f)m=h.offset+h.source.length;else{let p=s[0].toUpperCase()+s.substring(1),b=u?`${p} must end with a ${f}`:`${p} in block collection must be sufficiently indented and end with a ${f}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",b),h&&h.source.length!==1&&v.unshift(h)}if(v.length>0){let p=bx.resolveEnd(v,m,i.options.strict,n);p.comment&&(l.comment?l.comment+=`
|
|
72
|
+
`+p.comment:l.comment=p.comment),l.range=[r.offset,m,p.offset]}else l.range=[r.offset,m,m];return l}Qg.resolveFlowCollection=Ex});var tw=C(ew=>{"use strict";var Px=G(),Rx=ke(),Cx=Zi(),xx=er(),Ax=Jg(),_x=Ug(),Tx=Zg();function Ef(e,t,i,r,n,a){let o=i.type==="block-map"?Ax.resolveBlockMap(e,t,i,r,a):i.type==="block-seq"?_x.resolveBlockSeq(e,t,i,r,a):Tx.resolveFlowCollection(e,t,i,r,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function Ix(e,t,i,r,n){let a=r.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(i.type==="block-seq"){let{anchor:f,newlineAfterProp:h}=r,v=f&&a?f.offset>a.offset?f:a:f??a;v&&(!h||h.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=i.type==="block-map"?"map":i.type==="block-seq"?"seq":i.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===Cx.YAMLMap.tagName&&s==="map"||o===xx.YAMLSeq.tagName&&s==="seq")return Ef(e,t,i,n,o);let c=t.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Ef(e,t,i,n,o)}let l=Ef(e,t,i,n,o,c),u=c.resolve?.(l,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=Px.isNode(u)?u:new Rx.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}ew.composeCollection=Ix});var Rf=C(iw=>{"use strict";var Pf=ke();function jx(e,t,i){let r=t.offset,n=$x(t,e.options.strict,i);if(!n)return{value:"",type:null,comment:"",range:[r,r,r]};let a=n.mode===">"?Pf.Scalar.BLOCK_FOLDED:Pf.Scalar.BLOCK_LITERAL,o=t.source?Ox(t.source):[],s=o.length;for(let m=o.length-1;m>=0;--m){let p=o[m][1];if(p===""||p==="\r")s=m;else break}if(s===0){let m=n.chomp==="+"&&o.length>0?`
|
|
73
73
|
`.repeat(Math.max(1,o.length-1)):"",p=r+n.length;return t.source&&(p+=t.source.length),{value:m,type:a,comment:n.comment,range:[r,p,p]}}let c=t.indent+n.indent,l=t.offset+n.length,u=0;for(let m=0;m<s;++m){let[p,b]=o[m];if(b===""||b==="\r")n.indent===0&&p.length>c&&(c=p.length);else{p.length<c&&i(l+p.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=p.length),u=m,c===0&&!e.atRoot&&i(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=p.length+b.length+1}for(let m=o.length-1;m>=s;--m)o[m][0].length>c&&(s=m+1);let d="",f="",h=!1;for(let m=0;m<u;++m)d+=o[m][0].slice(c)+`
|
|
74
|
-
`;for(let m=u;m<s;++m){let[p,b]=o[m];l+=p.length+b.length+1;let g=b[b.length-1]==="\r";if(g&&(b=b.slice(0,-1)),b&&p.length<c){let E=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-b.length-(g?2:1),"BAD_INDENT",E),p=""}a===
|
|
74
|
+
`;for(let m=u;m<s;++m){let[p,b]=o[m];l+=p.length+b.length+1;let g=b[b.length-1]==="\r";if(g&&(b=b.slice(0,-1)),b&&p.length<c){let E=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;i(l-b.length-(g?2:1),"BAD_INDENT",E),p=""}a===Pf.Scalar.BLOCK_LITERAL?(d+=f+p.slice(c)+b,f=`
|
|
75
75
|
`):p.length>c||b[0]===" "?(f===" "?f=`
|
|
76
76
|
`:!h&&f===`
|
|
77
77
|
`&&(f=`
|
|
@@ -84,65 +84,65 @@ ${l}
|
|
|
84
84
|
`+o[m][0].slice(c);d[d.length-1]!==`
|
|
85
85
|
`&&(d+=`
|
|
86
86
|
`);break;default:d+=`
|
|
87
|
-
`}let v=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function
|
|
87
|
+
`}let v=r+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[r,v,v]}}function $x({offset:e,props:t},i,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let f=1;f<n.length;++f){let h=n[f];if(!s&&(h==="-"||h==="+"))s=h;else{let v=Number(h);!o&&v?o=v:c===-1&&(c=e+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let f=1;f<t.length;++f){let h=t[f];switch(h.type){case"space":l=!0;case"newline":d+=h.source.length;break;case"comment":i&&!l&&r(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=h.source.length,u=h.source.substring(1);break;case"error":r(h,"UNEXPECTED_TOKEN",h.message),d+=h.source.length;break;default:{let v=`Unexpected token in block scalar header: ${h.type}`;r(h,"UNEXPECTED_TOKEN",v);let m=h.source;m&&typeof m=="string"&&(d+=m.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function Ox(e){let t=e.split(/\n( *)/),i=t[0],r=i.match(/^( *)/),a=[r?.[1]?[r[1],i.slice(r[1].length)]:["",i]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}iw.resolveBlockScalar=jx});var xf=C(nw=>{"use strict";var Cf=ke(),Hx=Hn();function Dx(e,t,i){let{offset:r,type:n,source:a,end:o}=e,s,c,l=(f,h,v)=>i(r+f,h,v);switch(n){case"scalar":s=Cf.Scalar.PLAIN,c=Lx(a,l);break;case"single-quoted-scalar":s=Cf.Scalar.QUOTE_SINGLE,c=Mx(a,l);break;case"double-quoted-scalar":s=Cf.Scalar.QUOTE_DOUBLE,c=Fx(a,l);break;default:return i(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=Hx.resolveEnd(o,u,t,i);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function Lx(e,t){let i="";switch(e[0]){case" ":i="a tab character";break;case",":i="flow indicator character ,";break;case"%":i="directive indicator character %";break;case"|":case">":{i=`block scalar indicator ${e[0]}`;break}case"@":case"`":{i=`reserved character ${e[0]}`;break}}return i&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${i}`),rw(e)}function Mx(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),rw(e.slice(1,-1)).replace(/''/g,"'")}function rw(e){let t,i;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
88
88
|
`,"sy"),i=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
89
89
|
`,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,i=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let n=r[1],a=" ",o=t.lastIndex;for(i.lastIndex=o;r=i.exec(e);)r[1]===""?a===`
|
|
90
90
|
`?n+=a:a=`
|
|
91
|
-
`:(n+=a+r[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(e),n+a+(r?.[1]??"")}function
|
|
91
|
+
`:(n+=a+r[1],a=" "),o=i.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(e),n+a+(r?.[1]??"")}function Fx(e,t){let i="";for(let r=1;r<e.length-1;++r){let n=e[r];if(!(n==="\r"&&e[r+1]===`
|
|
92
92
|
`))if(n===`
|
|
93
|
-
`){let{fold:a,offset:o}=
|
|
93
|
+
`){let{fold:a,offset:o}=Bx(e,r);i+=a,r=o}else if(n==="\\"){let a=e[++r],o=Vx[a];if(o)i+=o;else if(a===`
|
|
94
94
|
`)for(a=e[r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="\r"&&e[r+1]===`
|
|
95
|
-
`)for(a=e[++r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=
|
|
95
|
+
`)for(a=e[++r+1];a===" "||a===" ";)a=e[++r+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;i+=qx(e,r+1,s,t),r+=s}else{let s=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),i+=s}}else if(n===" "||n===" "){let a=r,o=e[r+1];for(;o===" "||o===" ";)o=e[++r+1];o!==`
|
|
96
96
|
`&&!(o==="\r"&&e[r+2]===`
|
|
97
|
-
`)&&(i+=r>a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function
|
|
97
|
+
`)&&(i+=r>a?e.slice(a,r+1):n)}else i+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),i}function Bx(e,t){let i="",r=e[t+1];for(;(r===" "||r===" "||r===`
|
|
98
98
|
`||r==="\r")&&!(r==="\r"&&e[t+2]!==`
|
|
99
99
|
`);)r===`
|
|
100
100
|
`&&(i+=`
|
|
101
|
-
`),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var
|
|
102
|
-
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
101
|
+
`),t+=1,r=e[t+1];return i||(i=" "),{fold:i,offset:t}}var Vx={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
102
|
+
`,r:"\r",t:" ",v:"\v",N:"
",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function qx(e,t,i,r){let n=e.substr(t,i),o=n.length===i&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,i+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}nw.resolveFlowScalar=Dx});var sw=C(ow=>{"use strict";var Yr=G(),aw=ke(),Wx=Rf(),zx=xf();function Jx(e,t,i,r){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?Wx.resolveBlockScalar(e,t,r):zx.resolveFlowScalar(t,e.options.strict,r),c=i?e.directives.tagName(i.source,d=>r(i,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Yr.SCALAR]:c?l=Gx(e.schema,n,c,i,r):t.type==="scalar"?l=Ux(e,n,t,r):l=e.schema[Yr.SCALAR];let u;try{let d=l.resolve(n,f=>r(i??t,"TAG_RESOLVE_FAILED",f),e.options);u=Yr.isScalar(d)?d:new aw.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);r(i??t,"TAG_RESOLVE_FAILED",f),u=new aw.Scalar(n)}return u.range=s,u.source=n,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function Gx(e,t,i,r,n){if(i==="!")return e[Yr.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===i)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[i];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,i!=="tag:yaml.org,2002:str"),e[Yr.SCALAR])}function Ux({atKey:e,directives:t,schema:i},r,n,a){let o=i.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(r))||i[Yr.SCALAR];if(i.compat){let s=i.compat.find(c=>c.default&&c.test?.test(r))??i[Yr.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}ow.composeScalar=Jx});var lw=C(cw=>{"use strict";function Kx(e,t,i){if(t){i??(i=t.length);for(let r=i-1;r>=0;--r){let n=t[r];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++r];n?.type==="space";)e+=n.source.length,n=t[++r];break}}return e}cw.emptyScalarPosition=Kx});var fw=C(_f=>{"use strict";var Yx=Ua(),Xx=G(),Qx=tw(),uw=sw(),Zx=Hn(),eA=lw(),tA={composeNode:dw,composeEmptyNode:Af};function dw(e,t,i,r){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=i,l,u=!0;switch(t.type){case"alias":l=iA(e,t,r),(s||c)&&r(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=uw.composeScalar(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Qx.composeCollection(tA,e,t,i,r),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=Af(e,t.offset,void 0,null,i,r)),s&&l.anchor===""&&r(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!Xx.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&r(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function Af(e,t,i,r,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:eA.emptyScalarPosition(t,i,r),indent:-1,source:""},d=uw.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function iA({options:e},{offset:t,source:i,end:r},n){let a=new Yx.Alias(i.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+i.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+i.length,s=Zx.resolveEnd(r,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}_f.composeEmptyNode=Af;_f.composeNode=dw});var mw=C(pw=>{"use strict";var rA=uo(),hw=fw(),nA=Hn(),aA=mo();function oA(e,t,{offset:i,start:r,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new rA.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=aA.resolveProps(r,{indicator:"doc-start",next:n??a?.[0],offset:i,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?hw.composeNode(l,n,u,o):hw.composeEmptyNode(l,u.end,r,null,u,o);let d=c.contents.range[2],f=nA.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[i,d,f.offset],c}pw.composeDoc=oA});var If=C(ww=>{"use strict";var sA=Js("process"),cA=vd(),lA=uo(),vo=po(),vw=G(),uA=mw(),dA=Hn();function go(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:i}=e;return[t,t+(typeof i=="string"?i.length:1)]}function gw(e){let t="",i=!1,r=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":r?`
|
|
103
103
|
|
|
104
104
|
`:`
|
|
105
|
-
`)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var
|
|
106
|
-
${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(
|
|
105
|
+
`)+(a.substring(1)||" "),i=!0,r=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),i=!1;break;default:i||(r=!0),i=!1}}return{comment:t,afterEmptyLine:r}}var Tf=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(i,r,n,a)=>{let o=go(i);a?this.warnings.push(new vo.YAMLWarning(o,r,n)):this.errors.push(new vo.YAMLParseError(o,r,n))},this.directives=new cA.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,i){let{comment:r,afterEmptyLine:n}=gw(this.prelude);if(r){let a=t.contents;if(i)t.comment=t.comment?`${t.comment}
|
|
106
|
+
${r}`:r;else if(n||t.directives.docStart||!a)t.commentBefore=r;else if(vw.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];vw.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${r}
|
|
107
107
|
${s}`:r}else{let o=a.commentBefore;a.commentBefore=o?`${r}
|
|
108
|
-
${o}`:r}}if(i){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:
|
|
109
|
-
${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new
|
|
108
|
+
${o}`:r}}if(i){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:gw(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,i=!1,r=-1){for(let n of t)yield*this.next(n);yield*this.end(i,r)}*next(t){switch(sA.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(i,r,n)=>{let a=go(t);a[0]+=i,this.onError(a,"BAD_DIRECTIVE",r,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let i=uA.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!i.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(i,!1),this.doc&&(yield this.doc),this.doc=i,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let i=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new vo.YAMLParseError(go(t),"UNEXPECTED_TOKEN",i);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new vo.YAMLParseError(go(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let i=dA.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),i.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
|
|
109
|
+
${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.push(new vo.YAMLParseError(go(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,i=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),n=new lA.Document(void 0,r);this.atDirectives&&this.onError(i,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,i,i],this.decorate(n,!1),yield n}}};ww.Composer=Tf});var bw=C(Mc=>{"use strict";var fA=Rf(),hA=xf(),pA=po(),yw=Za();function mA(e,t=!0,i){if(e){let r=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(i)i(s,a,o);else throw new pA.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return hA.resolveFlowScalar(e,t,r);case"block-scalar":return fA.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function vA(e,t){let{implicitKey:i=!1,indent:r,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=yw.stringifyString({type:o,value:e},{implicitKey:i,indent:r>0?" ".repeat(r):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:`
|
|
110
110
|
`}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
|
|
111
111
|
`),u=s.substring(0,l),d=s.substring(l+1)+`
|
|
112
|
-
`,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return
|
|
113
|
-
`}),{type:"block-scalar",offset:a,indent:r,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function
|
|
112
|
+
`,f=[{type:"block-scalar-header",offset:a,indent:r,source:u}];return Nw(f,c)||f.push({type:"newline",offset:-1,indent:r,source:`
|
|
113
|
+
`}),{type:"block-scalar",offset:a,indent:r,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:r,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:r,source:s,end:c};default:return{type:"scalar",offset:a,indent:r,source:s,end:c}}}function gA(e,t,i={}){let{afterKey:r=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=i,s="indent"in e?e.indent:null;if(r&&typeof s=="number"&&(s+=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=yw.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":wA(e,c);break;case'"':jf(e,c,"double-quoted-scalar");break;case"'":jf(e,c,"single-quoted-scalar");break;default:jf(e,c,"scalar")}}function wA(e,t){let i=t.indexOf(`
|
|
114
114
|
`),r=t.substring(0,i),n=t.substring(i+1)+`
|
|
115
|
-
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=r,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:r}];
|
|
116
|
-
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function
|
|
117
|
-
`};delete e.items,Object.assign(e,{type:i,source:t,end:[n]});break}default:{let r="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:r,source:t,end:n})}}}
|
|
115
|
+
`;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=r,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:r}];Nw(s,"end"in e?e.end:void 0)||s.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:s,source:n})}}function Nw(e,t){if(t)for(let i of t)switch(i.type){case"space":case"comment":e.push(i);break;case"newline":return e.push(i),!0}return!1}function jf(e,t,i){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=i,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of r)a.offset+=n;delete e.props,Object.assign(e,{type:i,source:t,end:r});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
117
|
+
`};delete e.items,Object.assign(e,{type:i,source:t,end:[n]});break}default:{let r="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:i,indent:r,source:t,end:n})}}}Mc.createScalarToken=vA;Mc.resolveAsScalar=mA;Mc.setScalarValue=gA});var Sw=C(kw=>{"use strict";var yA=e=>"type"in e?Bc(e):Fc(e);function Bc(e){switch(e.type){case"block-scalar":{let t="";for(let i of e.props)t+=Bc(i);return t+e.source}case"block-map":case"block-seq":{let t="";for(let i of e.items)t+=Fc(i);return t}case"flow-collection":{let t=e.start.source;for(let i of e.items)t+=Fc(i);for(let i of e.end)t+=i.source;return t}case"document":{let t=Fc(e);if(e.end)for(let i of e.end)t+=i.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let i of e.end)t+=i.source;return t}}}function Fc({start:e,key:t,sep:i,value:r}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Bc(t)),i)for(let a of i)n+=a.source;return r&&(n+=Bc(r)),n}kw.stringify=yA});var Cw=C(Rw=>{"use strict";var $f=Symbol("break visit"),NA=Symbol("skip children"),Ew=Symbol("remove item");function Xr(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Pw(Object.freeze([]),e,t)}Xr.BREAK=$f;Xr.SKIP=NA;Xr.REMOVE=Ew;Xr.itemAtPath=(e,t)=>{let i=e;for(let[r,n]of t){let a=i?.[r];if(a&&"items"in a)i=a.items[n];else return}return i};Xr.parentCollection=(e,t)=>{let i=Xr.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],n=i?.[r];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function Pw(e,t,i){let r=i(t,e);if(typeof r=="symbol")return r;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Pw(Object.freeze(e.concat([[n,o]])),a.items[o],i);if(typeof s=="number")o=s-1;else{if(s===$f)return $f;s===Ew&&(a.items.splice(o,1),o-=1)}}typeof r=="function"&&n==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}Rw.visit=Xr});var Vc=C(st=>{"use strict";var Of=bw(),bA=Sw(),kA=Cw(),Hf="\uFEFF",Df="",Lf="",Mf="",SA=e=>!!e&&"items"in e,EA=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function PA(e){switch(e){case Hf:return"<BOM>";case Df:return"<DOC>";case Lf:return"<FLOW_END>";case Mf:return"<SCALAR>";default:return JSON.stringify(e)}}function RA(e){switch(e){case Hf:return"byte-order-mark";case Df:return"doc-mode";case Lf:return"flow-error-end";case Mf: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}
|
|
120
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
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}st.createScalarToken=Of.createScalarToken;st.resolveAsScalar=Of.resolveAsScalar;st.setScalarValue=Of.setScalarValue;st.stringify=bA.stringify;st.visit=kA.visit;st.BOM=Hf;st.DOCUMENT=Df;st.FLOW_END=Lf;st.SCALAR=Mf;st.isCollection=SA;st.isScalar=EA;st.prettyToken=PA;st.tokenType=RA});var Vf=C(Aw=>{"use strict";var wo=Vc();function zt(e){switch(e){case void 0:case" ":case`
|
|
120
|
+
`:case"\r":case" ":return!0;default:return!1}}var xw=new Set("0123456789ABCDEFabcdef"),CA=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),qc=new Set(",[]{}"),xA=new Set(` ,[]{}
|
|
121
|
+
\r `),Ff=e=>!e||xA.has(e),Bf=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,i=!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=!i;let r=this.next??"stream";for(;r&&(i||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,i=this.buffer[t];for(;i===" "||i===" ";)i=this.buffer[++t];return!i||i==="#"||i===`
|
|
122
122
|
`?!0:i==="\r"?this.buffer[t+1]===`
|
|
123
123
|
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let i=this.buffer[t];if(this.indentNext>0){let r=0;for(;i===" ";)i=this.buffer[++r+t];if(i==="\r"){let n=this.buffer[r+t+1];if(n===`
|
|
124
124
|
`||!n&&!this.atEnd)return t+r+1}return i===`
|
|
125
|
-
`||r>=this.indentNext||!i&&!this.atEnd?t+r:-1}if(i==="-"||i==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&
|
|
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]===
|
|
125
|
+
`||r>=this.indentNext||!i&&!this.atEnd?t+r:-1}if(i==="-"||i==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&zt(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]===wo.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let i=t.length,r=t.indexOf("#");for(;r!==-1;){let a=t[r-1];if(a===" "||a===" "){i=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let a=t[i-1];if(a===" "||a===" ")i-=1;else break}let n=(yield*this.pushCount(i))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let i=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-i),yield*this.pushNewline(),"stream"}return yield wo.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 i=this.peek(3);if((i==="---"||i==="...")&&zt(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,i==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!zt(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,i]=this.peek(2);if(!i&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&zt(i)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let i=yield*this.pushIndicators();switch(t[i]){case"#":yield*this.pushCount(t.length-i);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(Ff),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return i+=yield*this.parseBlockScalarHeader(),i+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-i),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,i,r=-1;do t=yield*this.pushNewline(),t>0?(i=yield*this.pushSpaces(!1),this.indentValue=r=i):i=0,i+=yield*this.pushSpaces(!0);while(t+i>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&n[0]!=="#"||r===0&&(n.startsWith("---")||n.startsWith("..."))&&zt(n[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield wo.FLOW_END,yield*this.parseLineStart();let a=0;for(;n[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),n[a]){case void 0:return"flow";case"#":return yield*this.pushCount(n.length-a),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Ff),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||zt(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),i=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;i!==-1&&this.buffer[i+1]==="'";)i=this.buffer.indexOf("'",i+2);else for(;i!==-1;){let a=0;for(;this.buffer[i-1-a]==="\\";)a+=1;if(a%2===0)break;i=this.buffer.indexOf('"',i+1)}let r=this.buffer.substring(0,i),n=r.indexOf(`
|
|
127
127
|
`,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=r.indexOf(`
|
|
128
|
-
`,a)}n!==-1&&(i=n-(r[n-1]==="\r"?2:1))}if(i===-1){if(!this.atEnd)return this.setNext("quoted-scalar");i=this.buffer.length}return yield*this.pushToIndex(i+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let i=this.buffer[++t];if(i==="+")this.blockScalarKeep=!0;else if(i>"0"&&i<="9")this.blockScalarIndent=Number(i)-1;else if(i!=="-")break}return yield*this.pushUntil(i=>
|
|
128
|
+
`,a)}n!==-1&&(i=n-(r[n-1]==="\r"?2:1))}if(i===-1){if(!this.atEnd)return this.setNext("quoted-scalar");i=this.buffer.length}return yield*this.pushToIndex(i+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let i=this.buffer[++t];if(i==="+")this.blockScalarKeep=!0;else if(i>"0"&&i<="9")this.blockScalarIndent=Number(i)-1;else if(i!=="-")break}return yield*this.pushUntil(i=>zt(i)||i==="#")}*parseBlockScalar(){let t=this.pos-1,i=0,r;e:for(let a=this.pos;r=this.buffer[a];++a)switch(r){case" ":i+=1;break;case`
|
|
129
129
|
`:t=a,i=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
130
130
|
`)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(i>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=i:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
|
|
131
131
|
`,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(r=this.buffer[n];r===" ";)r=this.buffer[++n];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
|
|
132
132
|
`;)r=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
|
|
133
|
-
`&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield
|
|
133
|
+
`&&a>=this.pos&&a+1+i>s)t=a;else break}while(!0);return yield wo.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,i=this.pos-1,r=this.pos-1,n;for(;n=this.buffer[++r];)if(n===":"){let a=this.buffer[r+1];if(zt(a)||t&&qc.has(a))break;i=r}else if(zt(n)){let a=this.buffer[r+1];if(n==="\r"&&(a===`
|
|
134
134
|
`?(r+=1,n=`
|
|
135
|
-
`,a=this.buffer[r+1]):i=r),a==="#"||t&&
|
|
136
|
-
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&
|
|
135
|
+
`,a=this.buffer[r+1]):i=r),a==="#"||t&&qc.has(a))break;if(n===`
|
|
136
|
+
`){let o=this.continueScalar(r+1);if(o===-1)break;r=Math.max(r,o-2)}}else{if(t&&qc.has(n))break;i=r}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield wo.SCALAR,yield*this.pushToIndex(i+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,i){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(i&&(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(Ff),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let i=this.flowLevel>0,r=this.charAt(1);if(zt(r)||i&&qc.has(r)){i?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,i=this.buffer[t];for(;!zt(i)&&i!==">";)i=this.buffer[++t];return yield*this.pushToIndex(i===">"?t+1:t,!1)}else{let t=this.pos+1,i=this.buffer[t];for(;i;)if(CA.has(i))i=this.buffer[++t];else if(i==="%"&&xw.has(this.buffer[t+1])&&xw.has(this.buffer[t+2]))i=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 i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};
|
|
138
|
+
`?yield*this.pushCount(2):0}*pushSpaces(t){let i=this.pos-1,r;do r=this.buffer[++i];while(r===" "||t&&r===" ");let n=i-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=i),n}*pushUntil(t){let i=this.pos,r=this.buffer[i];for(;!t(r);)r=this.buffer[++i];return yield*this.pushToIndex(i,!1)}};Aw.Lexer=Bf});var Wf=C(_w=>{"use strict";var qf=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let i=0,r=this.lineStarts.length;for(;i<r;){let a=i+r>>1;this.lineStarts[a]<t?i=a+1:r=a}if(this.lineStarts[i]===t)return{line:i+1,col:1};if(i===0)return{line:0,col:t};let n=this.lineStarts[i-1];return{line:i,col:t-n+1}}}};_w.LineCounter=qf});var Jf=C(Ow=>{"use strict";var AA=Js("process"),Tw=Vc(),_A=Vf();function tr(e,t){for(let i=0;i<e.length;++i)if(e[i].type===t)return!0;return!1}function Iw(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 $w(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 Wc(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 Dn(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 zc(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let i=0;i<t.length;++i)e.push(t[i])}function jw(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!tr(t.start,"explicit-key-ind")&&!tr(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,$w(t.value)?t.value.end?zc(t.value.end,t.sep):t.value.end=t.sep:zc(t.start,t.sep),delete t.sep)}var zf=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 _A.Lexer,this.onNewLine=t}*parse(t,i=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,i))yield*this.next(r);i||(yield*this.end())}*next(t){if(this.source=t,AA.env.LOG_TOKENS&&console.log("|",Tw.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let i=Tw.tokenType(t);if(i)if(i==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=i,yield*this.step(),i){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 r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,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 i=t??this.stack.pop();if(!i)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield i;else{let r=this.peek(1);switch(i.type==="block-scalar"?i.indent="indent"in r?r.indent:0:i.type==="flow-collection"&&r.type==="document"&&(i.indent=0),i.type==="flow-collection"&&jw(i),r.type){case"document":r.value=i;break;case"block-scalar":r.props.push(i);break;case"block-map":{let n=r.items[r.items.length-1];if(n.value){r.items.push({start:[],key:i,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=i;else{Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=r.items[r.items.length-1];n.value?r.items.push({start:[],value:i}):n.value=i;break}case"flow-collection":{let n=r.items[r.items.length-1];!n||n.value?r.items.push({start:[],key:i,sep:[]}):n.sep?n.value=i:Object.assign(n,{key:i,sep:[]});return}default:yield*this.pop(),yield*this.pop(i)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(i.type==="block-map"||i.type==="block-seq")){let n=i.items[i.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&Iw(n.start)===-1&&(i.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<i.indent))&&(r.type==="document"?r.end=n.start:r.items.push({start:n.start}),i.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":{Iw(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 i=this.startBlockValue(t);i?this.stack.push(i):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 i=Wc(this.peek(2)),r=Dn(i),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let i=this.source.indexOf(`
|
|
139
139
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
140
|
-
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){
|
|
140
|
+
`,i)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else if(i.sep)i.sep.push(this.sourceToken);else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){zc(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,n=r&&(i.sep||i.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&i.sep&&!i.value){let o=[];for(let s=0;s<i.sep.length;++s){let c=i.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=i.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||i.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"explicit-key-ind":!i.sep&&!i.explicitKey?(i.start.push(this.sourceToken),i.explicitKey=!0):n||i.value?(a.push(this.sourceToken),t.items.push({start:a,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(i.explicitKey)if(i.sep)if(i.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(tr(i.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if($w(i.key)&&!tr(i.sep,"newline")){let o=Dn(i.start),s=i.key,c=i.sep;c.push(this.sourceToken),delete i.key,delete i.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?i.sep=i.sep.concat(a,this.sourceToken):i.sep.push(this.sourceToken);else if(tr(i.start,"newline"))Object.assign(i,{key:null,sep:[this.sourceToken]});else{let o=Dn(i.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else i.sep?i.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):tr(i.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):i.sep.push(this.sourceToken):Object.assign(i,{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);n||i.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):i.sep?this.stack.push(o):(Object.assign(i,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!i.explicitKey&&i.sep&&!tr(i.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let i=t.items[t.items.length-1];switch(this.type){case"newline":if(i.value){let r="end"in i.value?i.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else i.start.push(this.sourceToken);return;case"space":case"comment":if(i.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(i.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){zc(n,i.start),n.push(this.sourceToken),t.items.pop();return}}i.start.push(this.sourceToken)}return;case"anchor":case"tag":if(i.value||this.indent<=t.indent)break;i.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;i.value||tr(i.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let i=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!i||i.sep?t.items.push({start:[this.sourceToken]}):i.start.push(this.sourceToken);return;case"map-value-ind":!i||i.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):Object.assign(i,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!i||i.value?t.items.push({start:[this.sourceToken]}):i.sep?i.sep.push(this.sourceToken):i.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!i||i.value?t.items.push({start:[],key:n,sep:[]}):i.sep?this.stack.push(n):Object.assign(i,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let n=Wc(r),a=Dn(n);jw(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let i=this.source.indexOf(`
|
|
141
141
|
`)+1;for(;i!==0;)this.onNewLine(this.offset+i),i=this.source.indexOf(`
|
|
142
|
-
`,i)+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 i=
|
|
142
|
+
`,i)+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 i=Wc(t),r=Dn(i);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let i=Wc(t),r=Dn(i);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,i){return this.type!=="comment"||this.indent<=i?!1:t.every(r=>r.type==="newline"||r.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())}}};Ow.Parser=zf});var Fw=C(No=>{"use strict";var Hw=If(),TA=uo(),yo=po(),IA=Ad(),jA=G(),$A=Wf(),Dw=Jf();function Lw(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new $A.LineCounter||null,prettyErrors:t}}function OA(e,t={}){let{lineCounter:i,prettyErrors:r}=Lw(t),n=new Dw.Parser(i?.addNewLine),a=new Hw.Composer(t),o=Array.from(a.compose(n.parse(e)));if(r&&i)for(let s of o)s.errors.forEach(yo.prettifyError(e,i)),s.warnings.forEach(yo.prettifyError(e,i));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Mw(e,t={}){let{lineCounter:i,prettyErrors:r}=Lw(t),n=new Dw.Parser(i?.addNewLine),a=new Hw.Composer(t),o=null;for(let s of a.compose(n.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new yo.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&i&&(o.errors.forEach(yo.prettifyError(e,i)),o.warnings.forEach(yo.prettifyError(e,i))),o}function HA(e,t,i){let r;typeof t=="function"?r=t:i===void 0&&t&&typeof t=="object"&&(i=t);let n=Mw(e,i);if(!n)return null;if(n.warnings.forEach(a=>IA.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:r},i))}function DA(e,t,i){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:i===void 0&&t&&(i=t),typeof i=="string"&&(i=i.length),typeof i=="number"){let n=Math.round(i);i=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=i??t??{};if(!n)return}return jA.isDocument(e)&&!r?e.toString(i):new TA.Document(e,r,i).toString(i)}No.parse=HA;No.parseAllDocuments=OA;No.parseDocument=Mw;No.stringify=DA});var Qr=C(X=>{"use strict";var LA=If(),MA=uo(),FA=ff(),Gf=po(),BA=Ua(),ir=G(),VA=Xi(),qA=ke(),WA=Zi(),zA=er(),JA=Vc(),GA=Vf(),UA=Wf(),KA=Jf(),Jc=Fw(),Bw=Wa();X.Composer=LA.Composer;X.Document=MA.Document;X.Schema=FA.Schema;X.YAMLError=Gf.YAMLError;X.YAMLParseError=Gf.YAMLParseError;X.YAMLWarning=Gf.YAMLWarning;X.Alias=BA.Alias;X.isAlias=ir.isAlias;X.isCollection=ir.isCollection;X.isDocument=ir.isDocument;X.isMap=ir.isMap;X.isNode=ir.isNode;X.isPair=ir.isPair;X.isScalar=ir.isScalar;X.isSeq=ir.isSeq;X.Pair=VA.Pair;X.Scalar=qA.Scalar;X.YAMLMap=WA.YAMLMap;X.YAMLSeq=zA.YAMLSeq;X.CST=JA;X.Lexer=GA.Lexer;X.LineCounter=UA.LineCounter;X.Parser=KA.Parser;X.parse=Jc.parse;X.parseAllDocuments=Jc.parseAllDocuments;X.parseDocument=Jc.parseDocument;X.stringify=Jc.stringify;X.visit=Bw.visit;X.visitAsync=Bw.visitAsync});import{promises as uP}from"node:fs";import od from"node:path";import{promises as Qu}from"fs";import Ie from"path";import{promises as JS}from"fs";import Oa from"path";import{isDeepStrictEqual as ZD}from"util";import{createHash as yP}from"crypto";function zm(e,t,i,r){return t.iteration>=i.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${i.maxIterations}`}:e.type==="invoke_skill"&&!i.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!i.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!i.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&i.confirmationRequiredFor.includes(e.ref)&&!r.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>i.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function Jm(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))Jm(e[t]);return Object.freeze(e)}function Ji(e){return Jm(structuredClone(e))}function cd(e,t,i,r){return e.resolveStep({pkg:Ji(t),state:Ji(i),context:Ji(r)})}function Gm(e,t,i,r,n,a){return e.resolveNext({pkg:Ji(t),state:Ji(i),step:Ji(r),outcome:Ji(n),context:Ji(a)})}function NP(e,t,i){return yP("sha256").update(`${e}:${t}:${i??"adaptive"}`).digest("hex").slice(0,16)}function ld(e,t){return e.definition.orchestration.steps?.find(i=>i.id===t)}function Um(e,t,i,r,n){if(t.status!=="running")return{state:t,action:null,reason:`Run is ${t.status}`};if(t.pending)return{state:t,action:null,reason:`Action already pending: ${t.pending}`};if(t.orchestration==="adaptive")return{state:t,action:null,reason:"Adaptive orchestration requires an Agent candidate"};let a=cd(r,e,t,n);if(!a&&t.currentStep===null)return{state:{...t,status:"completed"},action:null};if(!a)return{state:{...t,status:"failed"},action:null,reason:`Unknown current step: ${t.currentStep}`};let o=ld(e,a.id);if(!o)return{state:{...t,status:"failed"},action:null,reason:`Resolver returned unknown current step: ${a.id}`};let s=t.currentStep===o.id?t:{...t,currentStep:o.id},c={...o.action,id:NP(s.runId,s.iteration,o.id),stepId:o.id};return bP(e,s,c,i)}function bP(e,t,i,r){let n=zm(i,t,e.guardrails,r);return n.allowed?{state:{...t,pending:i.id,status:"waiting"},action:i}:{state:t,action:null,reason:n.reason}}function Km(e,t,i,r,n){if(!t.pending||t.pending!==i.actionId)throw new Error(`Outcome does not match pending action: ${i.actionId}`);let a=t.orchestration==="deterministic"?cd(r,e,t,n):void 0,o=a?ld(e,a.id):void 0;if(t.orchestration==="deterministic"&&!a)throw new Error(`Unknown current step: ${t.currentStep??"(missing)"}`);if(t.orchestration==="deterministic"&&!o)throw new Error(`Resolver returned unknown current step: ${a.id}`);if(i.status==="failed"){let c={...t.retries,[i.actionId]:(t.retries[i.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?Gm(r,e,t,o,i,n):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!ld(e,s))throw new Error(`Resolver returned unknown next step: ${s}`);return{...t,currentStep:s,iteration:t.iteration+1,pending:null,status:s===null&&t.orchestration==="deterministic"?"completed":"running"}}import{promises as ep}from"fs";import fb from"path";var ud={en:{outcome:"Outcome",scope:"Scope",nonGoals:"Non-goals",acceptanceExamples:"Acceptance examples",constraints:"Constraints and invariants",decisions:"Decisions",openQuestions:"Open questions",verificationExpectations:"Verification expectations"},"zh-CN":{outcome:"目标",scope:"范围",nonGoals:"非目标",acceptanceExamples:"验收示例",constraints:"约束与不变量",decisions:"决策",openQuestions:"待解决问题",verificationExpectations:"验证预期"}},Ym={en:{verification:"Verification",currentResult:"Current result",acceptance:"Acceptance",checks:"Checks",blockers:"Blockers",risks:"Risks and skipped work",previousIterations:"Previous iterations",conclusion:"Conclusion"},"zh-CN":{verification:"验证",currentResult:"当前结果",acceptance:"验收",checks:"检查",blockers:"阻塞项",risks:"风险与跳过的工作",previousIterations:"之前的迭代",conclusion:"结论"}},Xm={en:{acceptanceEvidence:"Acceptance evidence",commandsAndResults:"Commands and results",skippedChecks:"Skipped checks",specConsistency:"Spec consistency",knownLimitationsAndRisks:"Known limitations and risks",conclusion:"Conclusion"},"zh-CN":{acceptanceEvidence:"验收证据",commandsAndResults:"命令与结果",skippedChecks:"跳过的检查",specConsistency:"规格一致性",knownLimitationsAndRisks:"已知限制与风险",conclusion:"结论"}},Qm=new Map,dd=new Map;for(let e of Object.keys(ud)){for(let[t,i]of Object.entries(ud[e]))Qm.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(Ym[e]))dd.set(i.toLocaleLowerCase("en-US"),t);for(let[t,i]of Object.entries(Xm[e]))dd.set(i.toLocaleLowerCase("en-US"),t)}function kP(e,t){return ud[e][t]}function fd(e,t){return Ym[e][t]??Xm[e][t]}function Gs(e){return Qm.get(e.trim().toLocaleLowerCase("en-US"))??null}function Zm(e){return dd.get(e.trim().toLocaleLowerCase("en-US"))??null}function Us(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(i=>`# ${kP(e,i)}
|
|
143
143
|
`).join(`
|
|
144
|
-
`)}function
|
|
145
|
-
`,i)}import
|
|
144
|
+
`)}function qt(e,t,i){return e==="zh-CN"?i:t}var Gl=Rn(Qr(),1);import{promises as ib}from"fs";import mi from"path";import{execFileSync as YA}from"child_process";import bo from"path";function rr(e,t){return YA("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function XA(e,t){let i=bo.normalize(e),r=bo.normalize(t);return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function fe(e){try{let t=bo.resolve(rr(e,["rev-parse","--show-toplevel"])),r=rr(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=r?bo.resolve(r.slice(9)):t,a=null;try{a=rr(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!XA(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Vw(e){try{rr(e,["rev-parse","--is-inside-work-tree"]);let t=rr(e,["worktree","list","--porcelain"]).split(/\r?\n/u),i=[],r=null;for(let n of t)n.startsWith("worktree ")?(r&&i.push(r),r={root:bo.resolve(n.slice(9)),branch:null,detached:!1}):r&&n.startsWith("branch refs/heads/")?r.branch=n.slice(18):r&&n==="detached"&&(r.detached=!0);return r&&i.push(r),i}catch{return[]}}function Jt(e){return Vw(e).map(t=>t.root)}function ko(e,t){try{return rr(e,["check-ref-format","--branch",t]),rr(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function xi(e,t){try{let i=rr(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(i)?i:null}catch{return null}}import{createHash as t_}from"node:crypto";import{promises as Gt}from"node:fs";import Ct from"node:path";import{TextDecoder as i_}from"node:util";import Uf from"path";var QA=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),ZA=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function e_(e){return e.toLowerCase().startsWith(".env")}function ci(e){let i=e.replaceAll("\\","/").split("/").filter(Boolean).map(r=>r.toLowerCase());return i.some(r=>e_(r))?"environment-file":i.some(r=>ZA.has(r))?"credential-config":i.includes(".git")?"git-metadata":i.some(r=>QA.has(r))?"dependency-or-cache":i.join("/")===".comet/config.yaml"?"comet-config":i.join("/")===".comet/current-change.json"?"comet-selection":null}function Kf(e,t){let i=ci(t);if(i)return i;let r=Uf.resolve(e.projectRoot,...t.split("/")),n=Uf.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||r===Uf.resolve(e.configFile)?"native-runtime":null}function nr(e){return e!==0&&e!==0n&&e!=="0"}function vt(e,t){return nr(e.dev)&&nr(t.dev)&&nr(e.ino)&&nr(t.ino)}function z(e,t){let i=nr(e.dev)&&nr(t.dev);if(i&&e.dev!==t.dev)return!1;let r=nr(e.ino)&&nr(t.ino);return r&&e.ino!==t.ino?!1:i&&r?!0:e.birthtime===t.birthtime}var So=1024*1024;function Yf(e,t){let i=Ct.relative(e,t);return i===""||!Ct.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ct.sep}`)}function r_(e){let t=Ct.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||Ct.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let i=e.toLowerCase(),r=ci(e);if(r||i==="runtime"||i.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${r??"native-runtime"}): ${e}`);return e}function n_(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function a_(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Gc(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function qw(e){let t=await Gt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Gt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function o_(e,t){let i=Ct.resolve(e),r=Ct.resolve(t);if(!Yf(i,r))throw new Error("Native artifact path is outside its root");let n=[await qw(i)],a=i;for(let o of Ct.relative(i,r).split(Ct.sep).filter(Boolean)){a=Ct.join(a,o);let s=await qw(a);if(!Yf(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Ww(e){for(let t of e){let i=await Gt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!a_(t,i)||await Gt.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Z(e){let t=r_(e.ref),i=e.maxBytes===null?null:n_(e.maxBytes??So),r=Ct.resolve(e.root,...t.split("/")),n=await o_(e.root,Ct.dirname(r));await e.hooks?.afterParentChainCaptured?.();let a=await Gt.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(i!==null&&a.size>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);let o=await Gt.realpath(r);if(!Yf(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Gt.open(r,"r");try{let[c,l,u]=await Promise.all([s.stat(),Gt.lstat(r),Gt.realpath(r)]);if(await Ww(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Gc(a,c)||!Gc(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,h=Buffer.allocUnsafe(i===null?64*1024:Math.min(64*1024,i+1));for(;;){let y=i===null?h.length:i+1-f,E=await s.read(h,0,Math.min(h.length,y),null);if(E.bytesRead===0)break;if(f+=E.bytesRead,i!==null&&f>i)throw new Error(`Native artifact exceeds ${i} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,E.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,m,p]=await Promise.all([s.stat(),Gt.lstat(r),Gt.realpath(r)]);if(await Ww(n),!m.isFile()||m.isSymbolicLink()||p!==o||!Gc(c,v)||!Gc(c,m))throw new Error(`Native artifact changed while reading: ${t}`);let b=Buffer.concat(d,f),g;try{g=new i_("utf-8",{fatal:!0}).decode(b)}catch(y){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:y})}return{ref:t,size:f,hash:e.includeHash===!1?null:t_("sha256").update(b).digest("hex"),text:g}}finally{await s.close()}}import{randomUUID as s_}from"crypto";import{promises as Ve}from"fs";import Ut from"path";function Xf(e,t){let i=Ut.relative(e,t);return i===""||!Ut.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Ut.sep}`)}function c_(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Qf(e,t){return z({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function l_(e,t){return Qf(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function zw(e){let t=await Ve.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await Ve.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Eo(e){for(let t of e){let i=await Ve.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!c_(t,i)||await Ve.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function u_(e,t){let i=Ut.resolve(e),r=Ut.resolve(t);if(!Xf(i,r))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await zw(i)],a=Ut.relative(i,r).split(Ut.sep).filter(Boolean),o=i;for(let s of a){await Eo(n),o=Ut.join(o,s);try{await Ve.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await zw(o);if(!Xf(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Eo(n),n}async function d_(e){let t;try{t=await Ve.open(e,"r"),await t.sync()}catch(i){let r=i.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(r??""))throw i}finally{await t?.close()}}async function Jw(e,t,i={}){let r=Ut.dirname(e),n=i.containedRoot?await u_(i.containedRoot,r):null;n||await Ve.mkdir(r,{recursive:!0});let a=Ut.join(r,`.${Ut.basename(e)}.${s_()}.tmp`),o,s,c;try{if(await i.beforeTemporaryOpen?.(),o=await Ve.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([Ve.lstat(a),Ve.realpath(a)]);if(await Eo(n),!l.isFile()||l.isSymbolicLink()||!Qf(s,l)||!Xf(n[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!Qf(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await i.beforeCommit?.(),n){await Eo(n);let l=await Ve.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!l_(l,c))throw new Error("Native atomic write temporary file changed before commit")}i.exclusive?(await Ve.link(a,e),await Ve.unlink(a)):await Ve.rename(a,e),await d_(r)}catch(l){if(await o?.close(),!n)await Ve.rm(a,{force:!0});else try{await Eo(n),await Ve.rm(a,{force:!0})}catch{}throw l}}async function he(e,t,i={}){await Jw(e,t,i)}async function Gw(e,t,i={}){await Jw(e,t,i)}async function ee(e,t,i={}){await he(e,JSON.stringify(t,null,2)+`
|
|
145
|
+
`,i)}import V_ from"path";var Po=Rn(Qr(),1);import ar from"path";var Ro=64*1024,Kc=1024,Yc=64,Uw=1024,Kw=64,Qw=5,Uc={learning:!0,retrieval:!0},Zw={provider:"local"},f_=12e4,Yw=6e5,h_=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".dsh/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],p_=["**/.idea/**","**/.vscode/**",".codex/skills/**","**/node_modules/**","**/.next/**","**/.nuxt/**","**/.output/**","**/.svelte-kit/**","**/.vite/**","**/.parcel-cache/**","**/.turbo/**","**/.nx/cache/**","**/dist/**","**/build/**","**/out/**","**/coverage/**","**/.nyc_output/**","**/target/**","**/.gradle/**","**/.cxx/**","**/.externalNativeBuild/**","**/captures/**","**/__pycache__/**","**/.pytest_cache/**","**/.mypy_cache/**","**/.ruff_cache/**","**/.tox/**","**/.nox/**","**/.venv/**","**/venv/**","**/obj/**","**/CMakeFiles/**","**/cmake-build-*/**","**/.cache/**","**/tmp/**","**/temp/**","**/logs/**","**/*.tsbuildinfo","**/*.log","**/.DS_Store","**/Thumbs.db"],m_=[...h_,...p_].sort((e,t)=>e.localeCompare(t,"en"));var Kt={include:["**/*"],exclude:[...m_],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Ln={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`,memory:"# Project policy for automatic personal-memory learning and retrieval.","memory.learning":`# Allows workflow events in this project to form new personal memories automatically.
|
|
147
147
|
# learning: true | false`,"memory.retrieval":`# Allows personal memories to be injected into Agent context for this project.
|
|
148
148
|
# retrieval: true | false`,knowledge:"# Project knowledge retrieval provider used by ordinary Comet tasks.","knowledge.provider":`# Provider for project knowledge.
|
|
@@ -166,48 +166,48 @@ ${i.comment}`:i.comment}this.doc.range[2]=i.offset;break}default:this.errors.pus
|
|
|
166
166
|
# 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。
|
|
167
167
|
# 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
|
|
168
168
|
# 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
|
|
169
|
-
# 可选值:true | false`}};function
|
|
170
|
-
`)){let s=
|
|
169
|
+
# 可选值:true | false`}};function ey(e,t){return Ln[t][e]}function v_(e,t,i,r){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in Ln.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in Ln.en)return s}if(a===4&&t==="knowledge"&&r==="remote"){let s=`knowledge.remote.${o}`;if(s in Ln.en)return s}if(a===4&&t==="knowledge"&&r==="local"){let s=`knowledge.local.${o}`;if(s in Ln.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&i==="snapshot"){let s=`native.snapshot.${o}`;if(s in Ln.en)return s}return null}function Co(e,t){let i=[],r=null,n=null,a=null;for(let o of(0,Po.stringify)(e).trimEnd().split(`
|
|
170
|
+
`)){let s=v_(o,r,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of ey(s,t).split(`
|
|
171
171
|
`))i.push(`${c}${l}`)}i.push(o),/^[a-z_]+:/u.test(o)?(o.startsWith("native:")?r="native":o.startsWith("classic:")?r="classic":o.startsWith("hook:")?r="hook":o.startsWith("memory:")?r="memory":o.startsWith("knowledge:")?r="knowledge":r=null,n=null,a=null):/^ {2}[a-z_]+:/u.test(o)&&(r==="native"&&(n=o.startsWith(" snapshot:")?"snapshot":null),r==="knowledge"&&(a=o.startsWith(" local:")?"local":o.startsWith(" remote:")?"remote":null))}return i.push(""),i.join(`
|
|
172
|
-
`)}function ZA(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||rr.posix.isAbsolute(i)||rr.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function Dn(e){let t=ZA(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Yw(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function Gc(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||rr.posix.isAbsolute(r)||rr.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function xi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Xw(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function Uc(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>zc)throw new Error(`${t} exceeds ${zc} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>Jc)throw new Error(`${t} contains more than ${Jc} wildcard tokens`);return e}function Jw(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(r=>Uc(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function Xf(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function e_(e){if(e===void 0)return{...Ut,include:[...Ut.include],exclude:[...Ut.exclude]};let t=xi(e,"native.snapshot");return{include:Jw(t.include,"native.snapshot.include",Ut.include),exclude:Jw(t.exclude,"native.snapshot.exclude",Ut.exclude),max_files:Xf(t.max_files,Ut.max_files,"native.snapshot.max_files"),max_total_bytes:Xf(t.max_total_bytes,Ut.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Xf(t.max_duration_ms,Ut.max_duration_ms,"native.snapshot.max_duration_ms")}}function t_(e){if(e===void 0)return;let t=xi(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=xi(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:i,fromArtifactRoot:Dn(r),toArtifactRoot:Dn(n),stage:a,...o?{cleanup:o}:{}}}function i_(e){if(e===void 0)return;let t=xi(e,"native.finish");if(t.pull_request===void 0)return{};let i=xi(t.pull_request,"native.finish.pull_request");if(i.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(i.command)||i.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(i.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let r=i.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(rr.posix.isAbsolute(r[0])||rr.win32.isAbsolute(r[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=i.timeout_ms??UA;if(!Number.isSafeInteger(n)||n<1||n>zw)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${zw}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function r_(e,t={}){let i=xi(e,"native"),r=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??Gw;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=t_(i.pending_root_move),c=i_(i.finish);return{artifact_root:Dn(r),language:Xw(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:e_(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function n_(e){let t=xi(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Yw(t.artifact_layout),language:Xw(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function a_(e){let i=xi(e,"hook").allow_paths??[];if(!Array.isArray(i))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(i.map((r,n)=>Gc(r,`hook.allow_paths[${n}]`)))]}}function o_(e){if(e===void 0)return{...Wc};let t=xi(e,"memory"),i=t.learning??Wc.learning,r=t.retrieval??Wc.retrieval;if(typeof i!="boolean")throw new Error("memory.learning must be true or false");if(typeof r!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:i,retrieval:r}}function Qf(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function s_(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||i.includes("\\")||i.includes("\0")||rr.posix.isAbsolute(i)||rr.win32.isAbsolute(i)||i.startsWith("~")||i.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!i.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(i.length>qw)throw new Error(`${t} exceeds ${qw} characters`);let r=0;for(let n=0;n<i.length;n+=1)i[n]==="?"?r+=1:i[n]==="*"&&(r+=1,i[n+1]==="*"&&(n+=1));if(r>Ww)throw new Error(`${t} contains more than ${Ww} wildcard tokens`);return i}function c_(e){let i=Qf(e,"knowledge.local").include??[];if(!Array.isArray(i))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(i.map((r,n)=>s_(r,`knowledge.local.include[${n}]`)))]}}function l_(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let i=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),r=i==="localhost"||i==="127.0.0.1"||i==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&r))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function u_(e){let t=Qf(e,"knowledge.remote"),i=l_(t.endpoint),r=t.token_env;if(r!==void 0&&(typeof r!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(r)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:i,...r===void 0?{}:{token_env:r},...n===void 0?{}:{scope:n},timeout_ms:a}}function d_(e){if(e===void 0)return{...Uw};let t=Qf(e,"knowledge"),i=t.provider??"local";if(i!=="local"&&i!=="remote")throw new Error("knowledge.provider must be local or remote");let r=t.local===void 0?void 0:c_(t.local);if(i==="local")return{provider:i,...r?{local:r}:{}};let n=t.remote===void 0?void 0:u_(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:i,...r?{local:r}:{},remote:n}}function f_(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function h_(e,t,i,r,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:i,knowledge:r,...n?{native:n}:{},...a?{classic:a}:{}}}function Mn(e,t={}){let i=(0,So.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=f_(n.ambient_resume),o=n.hook===void 0?void 0:a_(n.hook),s=o_(n.memory),c=d_(n.knowledge),l=n.native===void 0?void 0:r_(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:n_(n.classic),d=h_(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function Qw(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function Zw(e){let t=e.knowledge??{...Uw};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...Wc},knowledge:{provider:t.provider,...t.local&&t.local.include.length>0?{local:{include:[...t.local.include]}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:Qw(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function vt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Ro(e,t){let i=Zw(t),r=Mn((0,So.stringify)(i)).config;if(!r)throw new Error("Unsupported Comet project schema");let n={...e,schema:r.schema,default_workflow:r.default_workflow,workflows:r.workflows,ambient_resume:r.ambient_resume};if(r.hook&&(n.hook={...vt(e.hook),allow_paths:[...r.hook.allow_paths]}),r.memory){let a=vt(e.memory);n.memory={...a,learning:r.memory.learning,retrieval:r.memory.retrieval}}if(r.knowledge){let a=vt(e.knowledge),o={...a,provider:r.knowledge.provider};if(r.knowledge.local&&r.knowledge.local.include.length>0?o.local={...vt(a.local),include:[...r.knowledge.local.include]}:delete o.local,r.knowledge.remote){let c={...vt(a.remote),endpoint:r.knowledge.remote.endpoint,timeout_ms:r.knowledge.remote.timeout_ms,...r.knowledge.remote.token_env===void 0?{}:{token_env:r.knowledge.remote.token_env},...r.knowledge.remote.scope===void 0?{}:{scope:r.knowledge.remote.scope}};r.knowledge.remote.token_env===void 0&&delete c.token_env,r.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(r.native){let a=vt(e.native),o={...a,artifact_root:r.native.artifact_root,language:r.native.language,clarification_mode:r.native.clarification_mode,archive_confirmation:r.native.archive_confirmation,max_verify_failures:r.native.max_verify_failures};if(r.native.finish?.pull_request){let s=vt(a.finish);o.finish={...s,pull_request:{...vt(s.pull_request),provider:r.native.finish.pull_request.provider,command:[...r.native.finish.pull_request.command],timeout_ms:r.native.finish.pull_request.timeout_ms}}}else{let s={...vt(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,r.native.pending_root_move){let s=vt(a.pending_root_move),c=Qw(r.native.pending_root_move),l=vt(s.cleanup),u=vt(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return r.classic&&(n.classic={...vt(e.classic),artifact_layout:r.classic.artifact_layout,language:r.classic.language,context_compression:r.classic.context_compression,review_mode:r.classic.review_mode,auto_transition:r.classic.auto_transition}),n}import{createHash as m_}from"crypto";import{promises as Xc}from"fs";import nr from"path";import{constants as Kc,promises as Xr}from"fs";var Kt=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function Zf(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function ey(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Co(e){return{dev:e.dev,ino:e.ino,birthtime:Zf(e)}}function Yc(e,t){let i=Co(e),r=Co(t);return mt(i,r)?z(i,r):z(i,r)&&Zf(e)===Zf(t)&&ey(e)===ey(t)&&e.size===t.size}async function Qr(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await Xr.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Kt("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Kt("too-large",`${r} exceeds ${t} bytes`);let o=await Xr.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:Co(a)});let s=process.platform==="win32"?Kc.O_RDONLY:Kc.O_RDONLY|Kc.O_NOFOLLOW|Kc.O_NONBLOCK,c;try{c=await Xr.open(e,s)}catch(l){throw l.code==="ELOOP"?new Kt("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),Xr.lstat(e,{bigint:n}),Xr.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Yc(a,l)||!Yc(a,u))throw new Kt("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:Co(l)}),await i.hooks?.afterOpen?.();let f=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let g=t+1-h,{bytesRead:y}=await c.read(v,0,Math.min(v.length,g),null);if(y===0)break;if(h+=y,h>t)throw new Kt("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,y)))}await i.hooks?.beforeFinalCheck?.();let[m,p,b]=await Promise.all([c.stat({bigint:n}),Xr.lstat(e,{bigint:n}),Xr.realpath(e)]);if(!p.isFile()||p.isSymbolicLink()||b!==o||!Yc(a,m)||!Yc(a,p))throw new Kt("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:b,identity:Co(m)}),{bytes:Buffer.concat(f,h),stat:m,realPath:b}}finally{await c.close()}}function p_(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function eh(e,t){let i=nr.relative(e,t);return i===""||!nr.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${nr.sep}`)}async function ty(e,t){let i=nr.resolve(e),r=await Xc.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Xc.realpath(i)}async function iy(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=nr.join(n,i[a]);let o;try{o=await Xc.lstat(n)}catch(u){if(p_(u))return{exists:!1,kind:"missing"};throw u}let s=nr.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await Xc.realpath(n);if(!eh(t,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Ln(e,t,i){let r=Gc(t,i.label),n=nr.resolve(e),a=await ty(n,i.label),o=r.split("/"),s=nr.resolve(n,...o);if(!eh(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await iy(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function ar(e,t,i,r){let n=await Ln(e,t,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await ty(n.projectRoot,r.label);return Qr(n.target,i,{...r,verify:async(o,s)=>{if(!eh(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await iy(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var xo=".comet/config.yaml";function th(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function v_(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Qc(e,t={}){return(await Ao(e,t)).document}async function ry(e){try{return(await ar(e,xo,Eo,{label:xo})).bytes}catch(t){if(v_(t))return null;throw t}}function ny(e){return e?{exists:!0,sha256:m_("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Zc(e){return ny(await ry(e))}async function Ao(e,t={}){let i=await ry(e);return{document:i?Mn(i.toString("utf8"),t):null,identity:ny(i)}}async function ih(e){return(await Qc(e))?.config??null}var pV=16*1024;async function rh(e,t){if(!t)return;let i=await Zc(e);if(!th(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{existsSync as ay,promises as or}from"fs";import U from"path";import N_ from"os";var el=".comet/config.yaml",b_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function nh(e){try{return await or.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function k_(e){try{let t=await or.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Bn(e,t){let i=U.relative(e,t);return i===""||!U.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${U.sep}`)}async function Fn(e){let t=[],i=e;for(;!await nh(i);){let n=U.dirname(i);if(n===i)break;t.push(U.basename(i)),i=n}let r=await or.realpath(i);return U.resolve(r,...t.reverse())}async function ah(e){try{return(await or.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function oh(e){let t=U.resolve(e);try{(await or.stat(t)).isDirectory()||(t=U.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=U.resolve(N_.homedir());for(;;){if(!(t===r&&i!==r)){let o=U.join(t,...el.split("/")),s=t===i||await k_(o);if(await nh(o)&&s)return t}if(await nh(U.join(t,".git")))return t;let a=U.dirname(t);if(a===t)return i;t=a}}function tl(e){return Dn(e)}async function S_(e,t){let i=tl(t),r=U.resolve(e,...i.split("/")),n=await or.realpath(e),a=await Fn(r);if(!Bn(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function Ve(e,t){let i=tl(t),r=await S_(e,i),n=U.join(r,"comet");if(await ah(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Fn(r),Fn(n)]);if(!Bn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=U.resolve(e),c=U.join(s,".comet","runtime","native");if(await ah(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([or.realpath(s),Fn(c)]);if(!Bn(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:U.join(e,...el.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:U.join(n,"specs"),changesDir:U.join(n,"changes"),archiveDir:U.join(n,"archive"),runtimeDir:c,changesRuntimeDir:U.join(c,"changes"),locksDir:U.join(c,"locks"),transactionsDir:U.join(c,"transactions")}}function sy(e){if(!b_.test(e))throw new Error(`Invalid Native change name: ${e}`)}function qe(e,t){sy(t);let i=U.join(e.changesRuntimeDir,t);if(!O(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function Zr(e,t){sy(t);let i=U.join(e.changesDir,t,"runtime");if(!O(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function H(e,t){let i=qe(e,t);if(ay(i))return i;let r=Zr(e,t);return ay(r)?r:i}async function oy(e){try{let t=await or.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function To(e,t){let i=qe(e,t),r=Zr(e,t),[n,a]=await Promise.all([oy(i),oy(r)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:i,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:r,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:i,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:i}:a==="directory"?{status:"available",layout:"legacy",path:r}:{status:"missing",layout:"missing",path:i}}function sr(e,t){if(!t.startsWith("runtime/")||U.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=U.resolve(e,...t.slice(8).split("/"));if(!O(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function j(e,t){let i=U.resolve(t);if(O(e.runtimeDir,i))return e.runtimeDir;if(O(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function O(e,t){return Bn(U.resolve(e),U.resolve(t))}async function T(e,t){let i=U.resolve(e),r=U.resolve(t);if(!Bn(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await ah(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Fn(i),Fn(r)]);if(!Bn(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var sh=Ut;var il=Uc;async function we(e){let t=(await Qc(e))?.config??null;return t?.native?t:null}async function Vn(e){let t=await we(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function cr(e,t,i={}){let r=await Ao(e,{allowPartialProject:!0}),n=Ro(r.document?.value??{},t),a=E_.join(e,...el.split("/"));await fe(a,Po(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await rh(e,r.identity)}})}import{promises as bI}from"fs";import kI from"path";import{AsyncLocalStorage as P_}from"async_hooks";import{randomUUID as dy}from"crypto";import{promises as Ct}from"fs";import fy from"os";import he from"path";var ly=16*1024,ch=".coordinator",R_=5e3,uy=new P_,rl=new Map;function C_(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function x_(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let i=e;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return i}function hy(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function lh(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return mt(i,r)?z(i,r):z(i,r)&&e.size===t.size}function nl(e,t){return lh(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function A_(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&nl(e.identity,t.identity)}async function ci(e){let t,i;try{let r=await Qr(e,ly,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof Kt?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${ly} bytes: ${e}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:r}):new Error(`Native lock changed while reading: ${e}`,{cause:r}):r}return{file:e,owner:x_(JSON.parse(t.toString("utf8")),e),identity:hy(i)}}async function __(e){return(await ci(e))?.owner??null}function uh(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==fy.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=H_(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function T_(e,t){try{await Ct.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await Ct.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function al(e,t){let i=await ci(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!nl(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Ct.mkdir(t,{recursive:!0});let r=he.join(t,`${he.basename(e.file)}.${e.owner.id}.${dy()}.removed`);try{await Ct.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await ci(r);if(!n||n.owner.id!==e.owner.id||!lh(n.identity,e.identity))throw await T_(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Ct.rm(r,{force:!0}),"removed"}function py(e){return{id:dy(),pid:process.pid,hostname:fy.hostname(),createdAt:new Date().toISOString(),operation:e}}async function my(e,t){let i;try{i=await Ct.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await __(e);throw new Error(`Native lock is already held: ${e}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:r})}throw r}try{return await i.writeFile(JSON.stringify(t,null,2)+`
|
|
173
|
-
`,"utf8"),await i.sync(),
|
|
174
|
-
${
|
|
172
|
+
`)}function g_(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||ar.posix.isAbsolute(i)||ar.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be a project-relative path`);if(i===".")return[];let r=i.replaceAll("\\","/").split("/");if(r.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(r.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return r}function Mn(e){let t=g_(e,"native.artifact_root");return t.length===0?".":t.join("/")}function ty(e,t="docs"){let i=e??t;if(i!=="legacy"&&i!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return i}function Xc(e,t,i=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim().replaceAll("\\","/");if(r.length===0||ar.posix.isAbsolute(r)||ar.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be relative to its declared path base`);let n=r.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!i&&/[*?]/u.test(r))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function Ai(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function iy(e,t,i){let r=e??t;if(r!=="en"&&r!=="zh-CN")throw new Error(`${i} must be en or zh-CN`);return r}function Qc(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>Kc)throw new Error(`${t} exceeds ${Kc} characters`);let i=0;for(let r=0;r<e.length;r+=1)e[r]==="?"?i+=1:e[r]==="*"&&(i+=1,e[r+1]==="*"&&(r+=1));if(i>Yc)throw new Error(`${t} contains more than ${Yc} wildcard tokens`);return e}function Xw(e,t,i){if(e===void 0)return[...i];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(r=>Qc(r,t)))].sort((r,n)=>r.localeCompare(n,"en"))}function Zf(e,t,i){let r=e??t;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${i} must be a positive integer`);return r}function w_(e){if(e===void 0)return{...Kt,include:[...Kt.include],exclude:[...Kt.exclude]};let t=Ai(e,"native.snapshot");return{include:Xw(t.include,"native.snapshot.include",Kt.include),exclude:Xw(t.exclude,"native.snapshot.exclude",Kt.exclude),max_files:Zf(t.max_files,Kt.max_files,"native.snapshot.max_files"),max_total_bytes:Zf(t.max_total_bytes,Kt.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Zf(t.max_duration_ms,Kt.max_duration_ms,"native.snapshot.max_duration_ms")}}function y_(e){if(e===void 0)return;let t=Ai(e,"native.pending_root_move"),i=t.id,r=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof i!="string"||!/^[a-f0-9-]{8,}$/u.test(i))throw new Error("native.pending_root_move.id is invalid");if(typeof r!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=Ai(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:i,fromArtifactRoot:Mn(r),toArtifactRoot:Mn(n),stage:a,...o?{cleanup:o}:{}}}function N_(e){if(e===void 0)return;let t=Ai(e,"native.finish");if(t.pull_request===void 0)return{};let i=Ai(t.pull_request,"native.finish.pull_request");if(i.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(i.command)||i.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(i.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let r=i.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(ar.posix.isAbsolute(r[0])||ar.win32.isAbsolute(r[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=i.timeout_ms??f_;if(!Number.isSafeInteger(n)||n<1||n>Yw)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Yw}`);return{pull_request:{provider:"repository-command",command:r,timeout_ms:n}}}function b_(e,t={}){let i=Ai(e,"native"),r=i.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof r!="string")throw new Error("native.artifact_root must be a string");let n=i.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=i.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=i.max_verify_failures??Qw;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=y_(i.pending_root_move),c=N_(i.finish);return{artifact_root:Mn(r),language:iy(i.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:w_(i.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function k_(e){let t=Ai(e,"classic"),i=t.context_compression??"off";if(i!=="off"&&i!=="beta")throw new Error("classic.context_compression must be off or beta");let r=t.review_mode??"standard";if(r!=="off"&&r!=="standard"&&r!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:ty(t.artifact_layout),language:iy(t.language,"zh-CN","classic.language"),context_compression:i,review_mode:r,auto_transition:n}}function S_(e){let i=Ai(e,"hook").allow_paths??[];if(!Array.isArray(i))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(i.map((r,n)=>Xc(r,`hook.allow_paths[${n}]`)))]}}function E_(e){if(e===void 0)return{...Uc};let t=Ai(e,"memory"),i=t.learning??Uc.learning,r=t.retrieval??Uc.retrieval;if(typeof i!="boolean")throw new Error("memory.learning must be true or false");if(typeof r!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:i,retrieval:r}}function eh(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function P_(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim();if(i.length===0||i.includes("\\")||i.includes("\0")||ar.posix.isAbsolute(i)||ar.win32.isAbsolute(i)||i.startsWith("~")||i.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!i.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(i.length>Uw)throw new Error(`${t} exceeds ${Uw} characters`);let r=0;for(let n=0;n<i.length;n+=1)i[n]==="?"?r+=1:i[n]==="*"&&(r+=1,i[n+1]==="*"&&(n+=1));if(r>Kw)throw new Error(`${t} contains more than ${Kw} wildcard tokens`);return i}function R_(e){let i=eh(e,"knowledge.local").include??[];if(!Array.isArray(i))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(i.map((r,n)=>P_(r,`knowledge.local.include[${n}]`)))]}}function C_(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let i=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),r=i==="localhost"||i==="127.0.0.1"||i==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&r))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function x_(e){let t=eh(e,"knowledge.remote"),i=C_(t.endpoint),r=t.token_env;if(r!==void 0&&(typeof r!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(r)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:i,...r===void 0?{}:{token_env:r},...n===void 0?{}:{scope:n},timeout_ms:a}}function A_(e){if(e===void 0)return{...Zw};let t=eh(e,"knowledge"),i=t.provider??"local";if(i!=="local"&&i!=="remote")throw new Error("knowledge.provider must be local or remote");let r=t.local===void 0?void 0:R_(t.local);if(i==="local")return{provider:i,...r?{local:r}:{}};let n=t.remote===void 0?void 0:x_(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:i,...r?{local:r}:{},remote:n}}function __(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function T_(e,t,i,r,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:i,knowledge:r,...n?{native:n}:{},...a?{classic:a}:{}}}function Fn(e,t={}){let i=(0,Po.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${i.errors[0].message}`);let r=i.toJS();if(r==null)return{value:{},config:null,ambient_resume:!0};if(typeof r!="object"||Array.isArray(r))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=r,a=__(n.ambient_resume),o=n.hook===void 0?void 0:S_(n.hook),s=E_(n.memory),c=A_(n.knowledge),l=n.native===void 0?void 0:b_(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:k_(n.classic),d=T_(n,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function ry(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function ny(e){let t=e.knowledge??{...Zw};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...Uc},knowledge:{provider:t.provider,...t.local&&t.local.include.length>0?{local:{include:[...t.local.include]}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:ry(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function gt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function xo(e,t){let i=ny(t),r=Fn((0,Po.stringify)(i)).config;if(!r)throw new Error("Unsupported Comet project schema");let n={...e,schema:r.schema,default_workflow:r.default_workflow,workflows:r.workflows,ambient_resume:r.ambient_resume};if(r.hook&&(n.hook={...gt(e.hook),allow_paths:[...r.hook.allow_paths]}),r.memory){let a=gt(e.memory);n.memory={...a,learning:r.memory.learning,retrieval:r.memory.retrieval}}if(r.knowledge){let a=gt(e.knowledge),o={...a,provider:r.knowledge.provider};if(r.knowledge.local&&r.knowledge.local.include.length>0?o.local={...gt(a.local),include:[...r.knowledge.local.include]}:delete o.local,r.knowledge.remote){let c={...gt(a.remote),endpoint:r.knowledge.remote.endpoint,timeout_ms:r.knowledge.remote.timeout_ms,...r.knowledge.remote.token_env===void 0?{}:{token_env:r.knowledge.remote.token_env},...r.knowledge.remote.scope===void 0?{}:{scope:r.knowledge.remote.scope}};r.knowledge.remote.token_env===void 0&&delete c.token_env,r.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(r.native){let a=gt(e.native),o={...a,artifact_root:r.native.artifact_root,language:r.native.language,clarification_mode:r.native.clarification_mode,archive_confirmation:r.native.archive_confirmation,max_verify_failures:r.native.max_verify_failures};if(r.native.finish?.pull_request){let s=gt(a.finish);o.finish={...s,pull_request:{...gt(s.pull_request),provider:r.native.finish.pull_request.provider,command:[...r.native.finish.pull_request.command],timeout_ms:r.native.finish.pull_request.timeout_ms}}}else{let s={...gt(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,r.native.pending_root_move){let s=gt(a.pending_root_move),c=ry(r.native.pending_root_move),l=gt(s.cleanup),u=gt(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return r.classic&&(n.classic={...gt(e.classic),artifact_layout:r.classic.artifact_layout,language:r.classic.language,context_compression:r.classic.context_compression,review_mode:r.classic.review_mode,auto_transition:r.classic.auto_transition}),n}import{createHash as j_}from"crypto";import{promises as tl}from"fs";import or from"path";import{constants as Zc,promises as Zr}from"fs";var Yt=class extends Error{reason;constructor(t,i,r){super(i,r),this.name="RaceSafeReadError",this.reason=t}};function th(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function ay(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Ao(e){return{dev:e.dev,ino:e.ino,birthtime:th(e)}}function el(e,t){let i=Ao(e),r=Ao(t);return vt(i,r)?z(i,r):z(i,r)&&th(e)===th(t)&&ay(e)===ay(t)&&e.size===t.size}async function en(e,t,i={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let r=i.label??"file",n=i.bigint===!0,a=await Zr.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Yt("not-regular-file",`${r} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Yt("too-large",`${r} exceeds ${t} bytes`);let o=await Zr.realpath(e);await i.verify?.("pre-open",{realPath:o,identity:Ao(a)});let s=process.platform==="win32"?Zc.O_RDONLY:Zc.O_RDONLY|Zc.O_NOFOLLOW|Zc.O_NONBLOCK,c;try{c=await Zr.open(e,s)}catch(l){throw l.code==="ELOOP"?new Yt("not-regular-file",`${r} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),Zr.lstat(e,{bigint:n}),Zr.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!el(a,l)||!el(a,u))throw new Yt("changed",`${r} changed while opening`);await i.verify?.("post-open",{realPath:d,identity:Ao(l)}),await i.hooks?.afterOpen?.();let f=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let g=t+1-h,{bytesRead:y}=await c.read(v,0,Math.min(v.length,g),null);if(y===0)break;if(h+=y,h>t)throw new Yt("too-large",`${r} exceeds ${t} bytes`);f.push(Buffer.from(v.subarray(0,y)))}await i.hooks?.beforeFinalCheck?.();let[m,p,b]=await Promise.all([c.stat({bigint:n}),Zr.lstat(e,{bigint:n}),Zr.realpath(e)]);if(!p.isFile()||p.isSymbolicLink()||b!==o||!el(a,m)||!el(a,p))throw new Yt("changed",`${r} changed while reading`);return await i.verify?.("post-read",{realPath:b,identity:Ao(m)}),{bytes:Buffer.concat(f,h),stat:m,realPath:b}}finally{await c.close()}}function I_(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function ih(e,t){let i=or.relative(e,t);return i===""||!or.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${or.sep}`)}async function oy(e,t){let i=or.resolve(e),r=await tl.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return tl.realpath(i)}async function sy(e,t,i,r){let n=e;for(let a=0;a<i.length;a++){n=or.join(n,i[a]);let o;try{o=await tl.lstat(n)}catch(u){if(I_(u))return{exists:!1,kind:"missing"};throw u}let s=or.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${r.label} crosses a symbolic link or junction at ${s}`);let c=a===i.length-1;if(!c&&!o.isDirectory())throw new Error(`${r.label} ancestor ${s} must be a real directory`);if(c&&(r.expected==="file"&&!o.isFile()||r.expected==="directory"&&!o.isDirectory()||r.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${r.label} must be a real ${r.expected}`);let l=await tl.realpath(n);if(!ih(t,l))throw new Error(`${r.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Bn(e,t,i){let r=Xc(t,i.label),n=or.resolve(e),a=await oy(n,i.label),o=r.split("/"),s=or.resolve(n,...o);if(!ih(n,s))throw new Error(`${i.label} must stay inside the project root`);let c=await sy(n,a,o,i);return{projectRoot:n,target:s,relative:r,exists:c.exists,kind:c.kind}}async function sr(e,t,i,r){let n=await Bn(e,t,{label:r.label,expected:"file"});if(!n.exists){let o=new Error(`${r.label} does not exist`);throw o.code="ENOENT",o}let a=await oy(n.projectRoot,r.label);return en(n.target,i,{...r,verify:async(o,s)=>{if(!ih(a,s.realPath))throw new Error(`${r.label} resolves outside the project root`);await sy(n.projectRoot,a,n.relative.split("/"),{label:r.label,expected:"file"})}})}var _o=".comet/config.yaml";function rh(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function $_(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function il(e,t={}){return(await To(e,t)).document}async function cy(e){try{return(await sr(e,_o,Ro,{label:_o})).bytes}catch(t){if($_(t))return null;throw t}}function ly(e){return e?{exists:!0,sha256:j_("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function rl(e){return ly(await cy(e))}async function To(e,t={}){let i=await cy(e);return{document:i?Fn(i.toString("utf8"),t):null,identity:ly(i)}}async function nh(e){return(await il(e))?.config??null}var qV=16*1024;async function ah(e,t){if(!t)return;let i=await rl(e);if(!rh(i,t))throw new Error("Project config changed before commit; rerun the operation")}import{existsSync as uy,promises as cr}from"fs";import K from"path";import L_ from"os";var nl=".comet/config.yaml",M_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function oh(e){try{return await cr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function F_(e){try{let t=await cr.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function qn(e,t){let i=K.relative(e,t);return i===""||!K.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${K.sep}`)}async function Vn(e){let t=[],i=e;for(;!await oh(i);){let n=K.dirname(i);if(n===i)break;t.push(K.basename(i)),i=n}let r=await cr.realpath(i);return K.resolve(r,...t.reverse())}async function sh(e){try{return(await cr.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ch(e){let t=K.resolve(e);try{(await cr.stat(t)).isDirectory()||(t=K.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let i=t,r=K.resolve(L_.homedir());for(;;){if(!(t===r&&i!==r)){let o=K.join(t,...nl.split("/")),s=t===i||await F_(o);if(await oh(o)&&s)return t}if(await oh(K.join(t,".git")))return t;let a=K.dirname(t);if(a===t)return i;t=a}}function al(e){return Mn(e)}async function B_(e,t){let i=al(t),r=K.resolve(e,...i.split("/")),n=await cr.realpath(e),a=await Vn(r);if(!qn(n,a))throw new Error("native.artifact_root resolves outside the project root");return r}async function qe(e,t){let i=al(t),r=await B_(e,i),n=K.join(r,"comet");if(await sh(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Vn(r),Vn(n)]);if(!qn(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=K.resolve(e),c=K.join(s,".comet","runtime","native");if(await sh(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([cr.realpath(s),Vn(c)]);if(!qn(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:K.join(e,...nl.split("/")),artifactRoot:r,artifactRootRef:i,nativeRoot:n,specsDir:K.join(n,"specs"),changesDir:K.join(n,"changes"),archiveDir:K.join(n,"archive"),runtimeDir:c,changesRuntimeDir:K.join(c,"changes"),locksDir:K.join(c,"locks"),transactionsDir:K.join(c,"transactions")}}function fy(e){if(!M_.test(e))throw new Error(`Invalid Native change name: ${e}`)}function We(e,t){fy(t);let i=K.join(e.changesRuntimeDir,t);if(!O(e.changesRuntimeDir,i))throw new Error("Native change Runtime path escaped");return i}function tn(e,t){fy(t);let i=K.join(e.changesDir,t,"runtime");if(!O(e.changesDir,i))throw new Error("Legacy Native change Runtime path escaped");return i}function H(e,t){let i=We(e,t);if(uy(i))return i;let r=tn(e,t);return uy(r)?r:i}async function dy(e){try{let t=await cr.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function jo(e,t){let i=We(e,t),r=tn(e,t),[n,a]=await Promise.all([dy(i),dy(r)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:i,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:r,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:i,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:i}:a==="directory"?{status:"available",layout:"legacy",path:r}:{status:"missing",layout:"missing",path:i}}function lr(e,t){if(!t.startsWith("runtime/")||K.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let i=K.resolve(e,...t.slice(8).split("/"));if(!O(e,i))throw new Error(`Native Runtime ref escaped: ${t}`);return i}function j(e,t){let i=K.resolve(t);if(O(e.runtimeDir,i))return e.runtimeDir;if(O(e.nativeRoot,i))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function O(e,t){return qn(K.resolve(e),K.resolve(t))}async function T(e,t){let i=K.resolve(e),r=K.resolve(t);if(!qn(i,r))throw new Error(`Path is outside the Native root: ${t}`);if(await sh(i))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Vn(i),Vn(r)]);if(!qn(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return r}var lh=Kt;var ol=Qc;async function ye(e){let t=(await il(e))?.config??null;return t?.native?t:null}async function Wn(e){let t=await ye(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function ur(e,t,i={}){let r=await To(e,{allowPartialProject:!0}),n=xo(r.document?.value??{},t),a=V_.join(e,...nl.split("/"));await he(a,Co(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await i.beforeCommit?.(),await ah(e,r.identity)}})}import{promises as MI}from"fs";import FI from"path";import{AsyncLocalStorage as q_}from"async_hooks";import{randomUUID as vy}from"crypto";import{promises as xt}from"fs";import gy from"os";import pe from"path";var py=16*1024,uh=".coordinator",W_=5e3,my=new q_,sl=new Map;function z_(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function J_(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let i=e;if(typeof i.id!="string"||i.id.length===0||typeof i.pid!="number"||!Number.isSafeInteger(i.pid)||i.pid<1||typeof i.hostname!="string"||i.hostname.length===0||typeof i.createdAt!="string"||i.createdAt.length===0||typeof i.operation!="string"||i.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return i}function wy(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function dh(e,t){let i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return vt(i,r)?z(i,r):z(i,r)&&e.size===t.size}function cl(e,t){return dh(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function G_(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&cl(e.identity,t.identity)}async function li(e){let t,i;try{let r=await en(e,py,{bigint:!0,label:"Native lock"});t=r.bytes,i=r.stat}catch(r){if(r.code==="ENOENT")return null;throw r instanceof Yt?r.reason==="too-large"?new Error(`Native lock metadata exceeds ${py} bytes: ${e}`,{cause:r}):r.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:r}):new Error(`Native lock changed while reading: ${e}`,{cause:r}):r}return{file:e,owner:J_(JSON.parse(t.toString("utf8")),e),identity:wy(i)}}async function U_(e){return(await li(e))?.owner??null}function fh(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==gy.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=eT(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function K_(e,t){try{await xt.lstat(t);return}catch(i){if(i.code!=="ENOENT")throw i}try{await xt.rename(e,t)}catch(i){if(i.code!=="ENOENT")throw i}}async function ll(e,t){let i=await li(e.file);if(!i)return"missing";if(i.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!cl(i.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await xt.mkdir(t,{recursive:!0});let r=pe.join(t,`${pe.basename(e.file)}.${e.owner.id}.${vy()}.removed`);try{await xt.rename(e.file,r)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await li(r);if(!n||n.owner.id!==e.owner.id||!dh(n.identity,e.identity))throw await K_(r,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await xt.rm(r,{force:!0}),"removed"}function yy(e){return{id:vy(),pid:process.pid,hostname:gy.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Ny(e,t){let i;try{i=await xt.open(e,"wx")}catch(r){if(r.code==="EEXIST"){let n=await U_(e);throw new Error(`Native lock is already held: ${e}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:r})}throw r}try{return await i.writeFile(JSON.stringify(t,null,2)+`
|
|
173
|
+
`,"utf8"),await i.sync(),wy(await i.stat({bigint:!0}))}finally{await i.close()}}async function Y_(e,t){let i=await T(e.runtimeDir,e.locksDir);await xt.mkdir(i,{recursive:!0});let r=await T(e.runtimeDir,pe.join(i,uh));await xt.mkdir(r,{recursive:!0});let n=yy(t),a=pe.join(r,`.${n.id}.tmp`),o=pe.join(r,`${n.id}.claim`);try{let s=await Ny(a,n);await xt.rename(a,o);let c=await li(o);if(!c||!dh(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:i,owner:n,identity:c.identity}}finally{await xt.rm(a,{force:!0})}}async function X_(e){let t=pe.dirname(e.file),i=!1,r=pe.basename(e.file);for(let n of await xt.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=pe.join(t,n.name);if(pe.resolve(a)!==pe.resolve(e.file))try{let o=await li(a),s=fh(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await ll(o,t);continue}n.name<r&&(i=!0)}catch{n.name<r&&(i=!0)}}return i}async function by(e){let t=await li(e.file);if(t){if(t.owner.id!==e.owner.id||!cl(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await ll(t,pe.dirname(e.file))}}async function Q_(e,t){let i=Date.now()+W_;for(;;){let r=await Y_(e,t);if(!await X_(r))return r;if(await by(r),Date.now()>=i)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function Z_(e){let t=sl.get(e)??Promise.resolve(),i,r=new Promise(a=>{i=a}),n=t.then(()=>r);return sl.set(e,n),await t,()=>{i(),sl.get(e)===n&&sl.delete(e)}}async function ul(e,t,i){let r=pe.resolve(e.locksDir),n=my.getStore();if(n?.has(r))return i();let a=await Z_(r);try{let o=await Q_(e,t),s=new Map(n??[]);return s.set(r,o),await my.run(s,async()=>{try{return await i()}finally{await by(o)}})}finally{a()}}async function zn(e,t,i){let r=[...new Map(e.map(a=>[pe.resolve(a.locksDir),a])).values()].sort((a,o)=>pe.resolve(a.locksDir).localeCompare(pe.resolve(o.locksDir))),n=async a=>{let o=r[a];return o?ul(o,t,()=>n(a+1)):i()};return n(0)}async function dr(e,t,i){return ul(e,`acquire ${t}`,async()=>{let r=await T(e.runtimeDir,e.locksDir);await xt.mkdir(r,{recursive:!0});let n=await T(e.runtimeDir,pe.join(r,z_(t))),a=yy(i),o=await Ny(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:r,owner:a,identity:o}})}async function fr(e){await li(e.file)&&await ul({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${pe.basename(e.file)}`,async()=>{let t=await li(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!cl(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let i=pe.join(e.locksDir,uh);await ll(t,i)})}function eT(e){try{return process.kill(e,0),!0}catch(t){let i=t.code;return i==="ESRCH"?!1:i==="EPERM"?!0:null}}async function $o(e){return fh(await li(e))}async function hh(e,t,i){return ul(e,`take over ${pe.basename(t)}`,async()=>{let r=await T(e.runtimeDir,e.locksDir),n=await T(e.runtimeDir,t);if(pe.resolve(pe.dirname(n))!==pe.resolve(r))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await li(n),o=fh(a);if(o.status==="missing")return{status:"missing"};if(i&&!G_(i,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=pe.join(r,uh);return await ll(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}import{promises as oI}from"node:fs";import Eh from"node:path";import zT from"node:path";import Iy from"node:path";import ky from"node:path";import{createHash as tT}from"crypto";function Xt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function iT(e,t){t.has(e)&&Xt("cyclic structures are not supported"),t.add(e);try{let i=Object.keys(e);for(let r=0;r<e.length;r+=1)Object.prototype.hasOwnProperty.call(e,r)||Xt("sparse arrays are not supported");return(i.length!==e.length||i.some((r,n)=>r!==String(n)))&&Xt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Xt("symbol properties are not supported"),`[${e.map(r=>ph(r,t)).join(",")}]`}finally{t.delete(e)}}function rT(e,t){let i=Object.getPrototypeOf(e);i!==Object.prototype&&i!==null&&Xt("only plain objects are supported"),t.has(e)&&Xt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Xt("symbol properties are not supported"),t.add(e);try{let r=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=r[o];return(!s||!("value"in s))&&Xt("accessor properties are not supported"),`${JSON.stringify(o)}:${ph(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function ph(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||Xt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?iT(e,t):rT(e,t);case"bigint":case"function":case"symbol":case"undefined":return Xt(`${typeof e} values are not supported`)}return Xt("unsupported value type")}function Oo(e){return ph(e,new Set)}function D(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return tT("sha256").update(`${e}
|
|
174
|
+
${Oo(t)}`).digest("hex")}var nT="comet.native.acceptance.v1",aT=/^acceptance-[a-f0-9]{64}$/u,oT=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),sT=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,cT=/^[a-f0-9]{64}$/u,lT=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;function uT(e,t){return e<t?-1:e>t?1:0}var _i=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Do=Object.freeze({maxCriteria:1024}),Sy="<!-- comet-native:acceptance-evidence:start -->",Ey="<!-- comet-native:acceptance-evidence:end -->";function Py(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{value:i,truncated:!0}}function Ry(e,t){let i=t.toString(36),r=D("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${i}.${r}`}function dT(e){if(!cT.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=lT.exec(e.cursor);if(!t)throw new Error("Native acceptance cursor is invalid");if(t[1]!==e.acceptanceHash)throw new Error("Native acceptance cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==D("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:i}))throw new Error("Native acceptance cursor integrity check failed");return i}function fT(e,t){let i=Py(e.text,_i.maxTextBytes),r=e.context.slice(0,_i.maxContextItems).map(n=>Py(n,_i.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:r.map(n=>n.value),text:i.value,contextTruncated:e.context.length>r.length||r.some(n=>n.truncated),textTruncated:i.truncated,verificationStatus:t}}function xy(e){let t=dT({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),i=[],r=[...new Set(e.failedCheckIds??[])].sort(uT),n=r.slice(0,_i.maxFailedCheckIds),a=e.criteria.slice(t,t+_i.maxItems);for(let c of a){let l=[...i,fT(c,e.verificationStatuses?.get(c.id)??"unverified")],u=t+l.length,d={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:l,failedAcceptanceIds:l.filter(f=>f.verificationStatus==="failed").map(f=>f.id),missingAcceptanceIds:l.filter(f=>f.verificationStatus==="missing").map(f=>f.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:u<e.criteria.length?Ry(e.acceptanceHash,u):null,limits:{..._i}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>_i.maxSerializedBytes){if(i.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}i.push(l.at(-1))}if(e.criteria.length>0&&i.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+i.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:i,failedAcceptanceIds:i.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:i.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:r.length>n.length,nextCursor:o<e.criteria.length?Ry(e.acceptanceHash,o):null,limits:{..._i}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>_i.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function vh(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function mh(e,t){let i=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!i)return t;let r=i[1][0];return t===null?{marker:r,length:i[1].length}:r===t.marker&&i[1].length>=t.length&&i[2].trim().length===0?null:t}function Cy(e){return e.includes("-->")||e.includes("--!>")}function*Jn(e){let t=null,i=!1,r=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
|
|
175
175
|
`),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
|
|
176
|
-
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=
|
|
177
|
-
`),[],r)),"Brief",r)}function
|
|
178
|
-
`),o.context,r)),o=null}};for(let{line:c,body:l}of
|
|
179
|
-
`).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=Py(o),c=eT(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function eT(e){let t=Py([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(t,null,2)}var tT=/^A[1-9]\d*$/u;function xy(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Cy.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Cy.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function iT(e,t){return e.localeCompare(t,"en")}function ll(e){let t=xy(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>iT(a.capability,o.capability));if(new Set(i.map(a=>a.capability)).size!==i.length)throw new Error("Native acceptance sources contain duplicate capabilities");let r=sl(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=xy(a.source,`Native spec source for ${a.capability}`);r.push(...cl(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of r){a.text=$o(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(r.length===0)throw new Error("Native change must define at least one acceptance criterion");return r.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function Ay(e){let t=e.map(({id:i})=>i);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let i=0;i<t.length;i+=1)if(!tT.test(t[i])||t[i]!==`A${i+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function _y(e,t){return e.length===t.length&&e.every((i,r)=>i.source===t[r]?.source&&i.text===t[r]?.text)}var fl=En(Yr(),1);import{promises as rT}from"node:fs";var zn="comet.native.v4",Ho="comet.native.local-execution.v4";var Ty=["multi-session","single-session"];function gh(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var nT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,aT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,oT=/^A[1-9][0-9]*$/u,sT=/^[a-f0-9]{64}$/u,cT=new Set(["schema","name","language","phase","status","state_version","brief","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),dl=class extends Error{constructor(i,r){super(`Native state version conflict: expected ${i}, got ${r}`);this.expectedStateVersion=i;this.actualStateVersion=r;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function Ye(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Xe(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Ae(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function yh(e,t){return e===null?null:Ae(e,t)}function lT(e,t){let i=Ae(e,t);if(!sT.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function Jn(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function pe(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function uT(e,t){return e===null?null:pe(e,t,Number.MIN_SAFE_INTEGER)}function Re(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function li(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function hl(e,t){return li(e,t,(i,r)=>Ae(i,`${t}[${r}]`))}function en(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Gn(e,t){let i=Ae(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function Nh(e,t,i=!1){let r=Ae(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function xt(e,t){let i=Ye(e,t);return Xe(i,new Set(["text","truncated"]),t),{text:Ae(i.text,`${t}.text`,{empty:!0}),truncated:Jn(i.truncated,`${t}.truncated`)}}function dT(e,t){let i=`Native spec_changes[${t}]`,r=Ye(e,i);Xe(r,new Set(["capability","operation","source"]),i);let n=Ae(r.capability,`${i}.capability`);if(!aT.test(n))throw new Error(`${i}.capability is invalid`);let a=Re(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:Nh(r.source,`${i}.source`);if(a==="remove"&&o!==null)throw new Error(`${i} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${i} ${a} requires a source`);return{capability:n,operation:a,source:o}}function fT(e){let t="Native workspace",i=Ye(e,t);Xe(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=Re(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=yh(i.change_branch,`${t}.change_branch`),a=yh(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:Re(i.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function hT(e){let t="Native loop",i=Ye(e,t);Xe(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=hl(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);return en(r,`${t}.previous_unresolved_ids`),{stage:Re(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:pe(i.goal_cycle,`${t}.goal_cycle`,1),iteration:pe(i.iteration,`${t}.iteration`),attempt:pe(i.attempt,`${t}.attempt`),retry_epoch:pe(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:pe(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:pe(i.no_progress_count,`${t}.no_progress_count`),execution_failure_count:pe(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:yh(i.next_action,`${t}.next_action`)}}function pT(e,t){let i=`Native acceptance[${t}]`,r=Ye(e,i);Xe(r,new Set(["id","source","text","result","reason"]),i);let n=Ae(r.id,`${i}.id`);if(!oT.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:Nh(r.source,`${i}.source`),text:Ae(r.text,`${i}.text`),result:Re(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:xt(r.reason,`${i}.reason`)}}function mT(e,t){let i=`Native builder_handoff.checks[${t}]`,r=Ye(e,i);return Xe(r,new Set(["name","result","note"]),i),{name:xt(r.name,`${i}.name`),result:Re(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:xt(r.note,`${i}.note`)}}function vT(e){let t="Native builder_handoff",i=Ye(e,t);Xe(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let r=hl(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);en(r,`${t}.addressed_acceptance_ids`);let n=i.review===null||i.review===void 0?null:Ye(i.review,`${t}.review`);return n&&Xe(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:Ae(i.candidate_id,`${t}.candidate_id`),identity_provider:Ae(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:Ae(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:pe(i.iteration,`${t}.iteration`,1),summary:xt(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:li(i.checks,`${t}.checks`,mT),checks_truncated:Jn(i.checks_truncated,`${t}.checks_truncated`),known_limits:li(i.known_limits,`${t}.known_limits`,(a,o)=>xt(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Jn(i.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:Re(n.status,["passed"],`${t}.review.status`),summary:xt(n.summary,`${t}.review.summary`),reviewer_execution_ref:Ae(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Gn(i.submitted_at,`${t}.submitted_at`)}}function gT(e,t){let i=`Native blockers[${t}]`,r=Ye(e,i);Xe(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=hl(r.acceptance_ids,`${i}.acceptance_ids`);return en(n,`${i}.acceptance_ids`),{owner:Re(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:xt(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:Re(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function wT(e,t){let i=`Native verification.checks[${t}]`,r=Ye(e,i);return Xe(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:Ae(r.id,`${i}.id`),name:xt(r.name,`${i}.name`),argv_display:li(r.argv_display,`${i}.argv_display`,(n,a)=>xt(n,`${i}.argv_display[${a}]`)),argv_truncated:Jn(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:Nh(r.cwd_ref,`${i}.cwd_ref`,!0),status:Re(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:uT(r.exit_code,`${i}.exit_code`),duration_ms:pe(r.duration_ms,`${i}.duration_ms`)}}function yT(e){let t="Native verification",i=Ye(e,t);Xe(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=li(i.checks,`${t}.checks`,wT);en(r.map(a=>a.id),`${t}.checks IDs`);let n=Ae(i.identity_provider,`${t}.identity_provider`);return{candidate_id:Ae(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:Ae(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:pe(i.iteration,`${t}.iteration`,1),attempt:pe(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":Re(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:Re(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:xt(i.summary,`${t}.summary`),risks:li(i.risks,`${t}.risks`,(a,o)=>xt(a,`${t}.risks[${o}]`)),risks_truncated:Jn(i.risks_truncated,`${t}.risks_truncated`),completed_at:Gn(i.completed_at,`${t}.completed_at`)}}function Iy(e,t){let i=`Native history[${t}]`,r=Ye(e,i);Xe(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=hl(r.unresolved_ids,`${i}.unresolved_ids`);return en(n,`${i}.unresolved_ids`),{goal_cycle:pe(r.goal_cycle,`${i}.goal_cycle`,1),iteration:pe(r.iteration,`${i}.iteration`),attempt:pe(r.attempt,`${i}.attempt`),outcome:Re(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:xt(r.summary,`${i}.summary`),completed_at:Gn(r.completed_at,`${i}.completed_at`)}}function NT(e){let t="Native history_overflow.outcome_counts",i=Ye(e,t),r=["pass","fail","blocked","execution-error","recovery"];return Xe(i,new Set(r),t),{pass:pe(i.pass,`${t}.pass`),fail:pe(i.fail,`${t}.fail`),blocked:pe(i.blocked,`${t}.blocked`),"execution-error":pe(i["execution-error"],`${t}.execution-error`),recovery:pe(i.recovery,`${t}.recovery`)}}function bT(e){let t="Native history_overflow",i=Ye(e,t);Xe(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=pe(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:Gn(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:Gn(i.last_dropped_at,`${t}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=NT(i.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==r)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:r,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function kT(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function ST(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function st(e){let t=Ye(e,"Native portable state");if(Xe(t,cT,"Native portable state"),t.schema!==zn)throw new Error(`Native portable state schema must be ${zn}`);let i=Ae(t.name,"Native state name");if(!nT.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=li(t.spec_changes,"Native spec_changes",dT);en(r.map(s=>s.capability),"Native spec change capabilities");let n=li(t.acceptance,"Native acceptance",pT);en(n.map(s=>s.id),"Native acceptance IDs");let a=li(t.history,"Native history",Iy);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:zn,name:i,language:Re(t.language,["en","zh-CN"],"Native state language"),phase:Re(t.phase,["shape","build","verify","archive"],"Native state phase"),status:Re(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:pe(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:lT(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:Re(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:r,workspace:fT(t.workspace),loop:hT(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:vT(t.builder_handoff),blockers:li(t.blockers,"Native blockers",gT),verification:t.verification===null?null:yT(t.verification),history:a,history_overflow:bT(t.history_overflow),verification_result:Re(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:Re(t.verification_report,["verification.md"],"Native verification_report"),archived:Jn(t.archived,"Native archived"),created_at:Gn(t.created_at,"Native created_at")};return kT(o),ST(o),o}function Un(e,t){let i=st(e),r=Iy(t,i.history.length),n=[...i.history,r],a={...i.history_overflow,outcome_counts:{...i.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return st({...i,history:n,history_overflow:a})}function ET(e,t){let i=(0,fl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function Qe(e){let t=await rT.readFile(e,"utf8");return st(ET(t,"Native portable state"))}async function pl(e,t,i={}){let r=st(t);await fe(e,(0,fl.stringify)(r),i)}var ul=new Map;async function PT(e,t){let i=ul.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);ul.set(e,a),await i;try{return await t()}finally{r(),ul.get(e)===a&&ul.delete(e)}}async function tn(e){return PT(e.file,async()=>{let t=pe(e.expectedStateVersion,"Native expected state version",1),i=st(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await Qe(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new dl(t,r.state_version);return await pl(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Qe(e.file);if(n.state_version!==t)throw new dl(t,n.state_version)}}),i})}function RT(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function dr(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(RT(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{text:i,truncated:!0}}var ye="comet.native.v3",Ne="comet.native.v2",Ze="comet.native.v1",fr="comet.native.transition.v3",_i="comet.native.transition.v2",rn="comet.native.transition.v1";var ml="comet.native.portable-migration.v1",xT=new Set(["schema","id","change","fromSchema","status","createdAt"]),AT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_T=/^[a-z0-9][a-z0-9-]{7,127}$/u,TT=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),IT=new Set([Ze,Ne,ye]);function jT(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function $T(e,t){let i=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(i.valueOf()))throw new Error(`${t} must be a valid timestamp`);return i.toISOString()}function OT(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function HT(e){return e.schema===Ze?nn(e):e.schema===Ne?ui(e):ct(e)}function DT(e){return CT.posix.normalize(e.replaceAll("\\","/"))}function MT(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:DT(t.source)})}function LT(e){return e==="shape"?"shape":"build"}function FT(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function BT(e,t,i){return e==="zh-CN"?`从旧版 ${t} ${i} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${i} state; prior Loop, verification results, and execution records were not inherited.`}function jy(e){let t=HT(e.state);Ay(e.acceptance);let i=LT(t.phase),r=i==="shape"?0:1,n=$T(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return st({schema:zn,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:MT(t),workspace:e.workspace,loop:{stage:i==="shape"?"shape":"building",goal_cycle:1,iteration:r,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:FT(t.language,i)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:r,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:dr(BT(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:gh(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function bh(e){let t=jT(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!xT.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==ml)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!_T.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!AT.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!IT.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!TT.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:ml,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:OT(t.createdAt,"Native portable migration transaction createdAt")}}function $y(e){switch(bh(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var vl="comet.native.archive-transaction.v4",Oy="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",qT=new RegExp(`^portable-archive-(${Oy})\\.json$`,"u"),WT=new RegExp(`^portable-migration-(${Oy})\\.json$`,"u"),zT=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,JT=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,GT=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),UT=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),KT=new Set(["capability","operation","source","content"]),Hy=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Dy(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function My(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${i} fields are invalid`)}function YT(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=Dy(e,i);if(My(r,KT,i),typeof r.capability!="string"||!Hy.test(r.capability))throw new Error(`${i}.capability is invalid`);if(!["create","modify","remove"].includes(String(r.operation)))throw new Error(`${i}.operation is invalid`);let n=r.operation;if(n==="remove"){if(r.source!==null||r.content!==null)throw new Error(`${i} remove requires source and content null`);return{capability:r.capability,operation:n,source:null,content:null}}if(typeof r.source!="string"||r.source.length===0||r.source.includes("\\")||r.source.startsWith("/")||/^[A-Za-z]:/u.test(r.source)||r.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${i}.${n} source is invalid`);if(typeof r.content!="string")throw new Error(`${i}.${n} content is invalid`);return{capability:r.capability,operation:n,source:r.source,content:r.content}}function XT(e){let t=Dy(e,"Native portable Archive transaction");if(My(t,UT,"Native portable Archive transaction"),t.schema!==vl)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!zT.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Hy.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!JT.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!GT.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let i=t.spec_changes.map(YT);if(new Set(i.map(({capability:n})=>n)).size!==i.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>i.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let r=new Date(t.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:vl,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:i,created_at:t.created_at}}function an(e){let t=qT.exec(e);if(t)return{kind:"archive",change:t[1]};let i=WT.exec(e);return i?{kind:"migration",change:i[1]}:null}function hr(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=an(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return kh.join(e.transactionsDir,i)}async function Do(e,t){let i=an(t);if(!i)return null;let r=await Q({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=kh.join(e.transactionsDir,t);if(i.kind==="archive"){let s=XT(n);if(s.change!==i.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:i.change,file:a,journal:s}}let o=bh(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}async function gl(e,t){let i=hr(e,t);try{return await Do(e,kh.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Ly(e){let t;try{t=await VT.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.map(({name:i})=>i).filter(i=>an(i)!==null).sort((i,r)=>i.localeCompare(r,"en"))}function Fy(e){return e.kind==="archive"||e.journal.status!=="committed"}import{promises as Mo}from"fs";import At from"path";import{TextDecoder as iI}from"util";import{createHash as QT}from"node:crypto";import{constants as wl,promises as W}from"node:fs";import K from"node:path";import{TextDecoder as ZT}from"node:util";function We(e,t){let i=K.relative(e,t);return i===""||!K.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${K.sep}`)}function By(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Yn(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Vy(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Kn(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function pr(e,t){let i=await W.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await W.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function mr(e,t,i){let r=K.resolve(e),n=K.resolve(t);if(!We(r,n))throw new Error(`${i} is outside its managed root`);let a=[await pr(r,i)],o=r;for(let s of K.relative(r,n).split(K.sep).filter(Boolean)){await ge(a,i),o=K.join(o,s);let c=await pr(o,i);if(!We(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await ge(a,i),a}async function ge(e,t){for(let i of e){let r=await W.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!Yn(i,r)||await W.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function eI(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function ie(e){let t=By(e.maxBytes),i=K.resolve(e.file),r=await mr(e.root,K.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>pr(K.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await ge(r,e.label);let a=await W.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=Vy(a),s=await W.realpath(i);if(!We(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>We(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?wl.O_RDONLY:wl.O_RDONLY|wl.O_NOFOLLOW|wl.O_NONBLOCK,l=await W.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([W.lstat(i),W.realpath(i)]);if(await ge(r,e.label),await ge(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Kn(o,u)||!Kn(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await eI(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,m,p]=await Promise.all([l.stat(),W.lstat(i),W.realpath(i)]);if(await ge(r,e.label),await ge(n,e.label),!m.isFile()||m.isSymbolicLink()||p!==s||!Kn(o,v)||!Kn(o,m))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:QT("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function yl(e){let t=await ie(e),i;try{i=new ZT("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e.label} is not valid UTF-8`,{cause:r})}return{...t,text:i}}async function gt(e){let t=await mr(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await W.readdir(e.directory,{withFileTypes:!0});else{let r=By(e.maxEntries);i=[];let n=await W.opendir(e.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${e.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await ge(t,e.label),{entries:i,verify:()=>ge(t,e.label)}}async function Xt(e){let t=await mr(e.root,e.directory,e.label);return{verify:()=>ge(t,e.label)}}async function tI(e){let t=K.resolve(e.directory),i=K.resolve(e.quarantine);if(K.dirname(i)!==K.dirname(t)||!We(K.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let r=await mr(e.root,K.dirname(t),e.label),n=await pr(t,e.label);if(!We(r[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await ge(r,e.label);let a=await W.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!Yn(n,a)||await W.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await W.lstat(i),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await W.rename(t,i),await ge(r,e.label);let o=await W.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!Yn(n,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await W.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:i,parentChain:r,identity:n}}async function qy(e){await tI(e)}async function Nl(e){let t=K.resolve(e.file),i=await mr(e.root,K.dirname(t),e.label),r=await W.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let n=Vy(r),a=await W.realpath(t);if(!We(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await ie({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([W.lstat(t),W.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!Kn(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await ge(i,e.label);let[l,u]=await Promise.all([W.lstat(t),W.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Kn(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await W.rm(t),await ge(i,e.label)}async function Sh(e){let t=K.resolve(e.directory),i=await mr(e.root,K.dirname(t),e.label),r=await pr(t,e.label);if(!We(i[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await ge(i,e.label);let n=await W.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!Yn(r,n)||await W.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before removal`);await W.rmdir(t),await ge(i,e.label)}async function di(e){let t=K.resolve(e.root),i=K.resolve(e.directory);if(!We(t,i))throw new Error(`${e.label} is outside its managed root`);let r=[await pr(t,e.label)],n=t;for(let a of K.relative(t,i).split(K.sep).filter(Boolean)){await ge(r,e.label),n=K.join(n,a);try{await W.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await pr(n,e.label);if(!We(r[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);r.push(o)}await ge(r,e.label)}async function Eh(e){let t=K.resolve(e.root),i=K.resolve(e.source),r=K.resolve(e.target);if(i===r||!We(t,i)||!We(t,r)||We(i,r)||We(r,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await di({root:t,directory:K.dirname(r),label:`${e.label} target parent`});let n=await mr(t,K.dirname(i),e.label),a=await mr(t,K.dirname(r),e.label),o=await pr(i,e.label);if(!We(n[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await W.lstat(r),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([ge(n,e.label),ge(a,e.label)]);let s=await W.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!Yn(o,s)||await W.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await W.rename(i,r),await Promise.all([ge(n,e.label),ge(a,e.label)]);let c=await W.lstat(r);if(!c.isDirectory()||c.isSymbolicLink()||!Yn(o,c)||!We(n[0].realPath,await W.realpath(r)))throw new Error(`${e.label} source identity changed while moving`);try{throw await W.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function vr(e){let t=await ie({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await Vw(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await W.lstat(e.target)}catch(n){if(n.code==="ENOENT")return;throw n}throw new Error(`${e.label} target changed before commit`)}if((await ie({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let i=await ie({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(i.hash!==t.hash||i.size!==t.size)throw new Error(`${e.label} target could not be verified`);return i}var rI=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),nI=new Set(["id","type","source","target","staged","backup"]),aI=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),oI=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),sI=new Set(["sequence","timestamp","type","operationId"]),Gy=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),Uy=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),cI=256*1024,lI=1024*1024,Ky=16*1024,kl=1024,Ch=64*1024*1024,uI=2e4,Yy=new iI("utf-8",{fatal:!0});function Lo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Fo(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Qn(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ph(e,t){if(typeof e!="string"||e.length===0||At.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function bl(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Wy(e,t){if(Ph(e,t),e.includes("\\")||e!==At.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function dI(e,t){let i=Lo(e,`transaction operations[${t}]`);if(Fo(i,nI,`transaction operations[${t}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${t}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Ph(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Ph(i[r],`transaction operation ${i.id} ${r}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function El(e){let t=Lo(e,"Native Archive transaction journal");if(Fo(t,aI,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!Gy.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!Qn(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(bl(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=t.operations.map((s,c)=>{let l=Lo(s,`Archive transaction operations[${c}]`);if(Fo(l,oI,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);Wy(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Wy(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&bl(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(bl(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);bl(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:i}}function xh(e){let t=Lo(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return El(t);if(Fo(t,rI,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!Gy.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!At.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!At.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!Qn(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let i=t.operations.map(dI),r=i.map(n=>n.id);if(new Set(r).size!==r.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:i}}function Xy(e,t){let i=Lo(e,`Native transaction event at line ${t}`);if(Fo(i,sI,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!Qn(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!Uy.has(i.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let r=i.type==="operation-started"||i.type==="operation-completed";if(r&&(typeof i.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.operationId)||Buffer.byteLength(i.operationId,"utf8")>256)||!r&&i.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:i.sequence,timestamp:i.timestamp,type:i.type,...typeof i.operationId=="string"?{operationId:i.operationId}:{}}}function fI(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let r=0;r<e.length;r+=1){let n=t[r],a=e[r];if(n==="0"){if(!/[0-9]/u.test(a))return!1}else if(a!==n)return!1}let i=[[5,2,1,12],[8,2,1,31],[11,2,0,23],[14,2,0,59],[17,2,0,59],[20,3,0,999]];for(let[r,n,a,o]of i){if(e.length<=r)continue;let s=e.slice(r,Math.min(r+n,e.length));if(!Array.from({length:o-a+1},(l,u)=>String(a+u).padStart(n,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!Qn(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||Qn(e)}function Xn(e,t){return e.length<t.length&&t.startsWith(e)}function hI(e){let t='","operationId":"';if(Xn(e,t))return!0;if(!e.startsWith(t))return!1;let i=e.slice(t.length),r=i.indexOf('"');if(r===-1)return i.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(i);let n=i.slice(0,r);return/^[a-z0-9][a-z0-9-]*$/u.test(n)?Xn(i.slice(r),'"}'):!1}function pI(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>Ky)return!1;let i=`{"sequence":${t},"timestamp":"`;if(Xn(e,i))return!0;if(!e.startsWith(i))return!1;let r=e.slice(i.length),n=r.slice(0,Math.min(24,r.length));if(!fI(n))return!1;if(r.length<24)return!0;if(!Qn(n))return!1;let a='","type":"',o=r.slice(24);if(Xn(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of Uy){if(Xn(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(hI(l))return!0}else if(Xn(l,'"}'))return!0}return!1}function mI(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>Ky)throw new Error(`Native transaction event at line ${t} is too large`);return Xy(JSON.parse(e),t)}function vI(e){let t=e.split(`
|
|
180
|
-
`),i=t.at(-1)==="";if(i&&t.pop(),t.length>
|
|
176
|
+
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!i&&r===null,index:s},s+=1,t!==null)t=mh(l,t);else if(i)Cy(l)&&(i=!1);else if(r!==null)new RegExp(`</${r}\\s*>`,"iu").test(l)&&(r=null);else{let d=mh(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!Cy(f))i=!0;else{let h=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);h&&n.has(h[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${h[1]}\\s*>`,"iu").test(f)&&(r=h[1])}}}if(c===-1)break;o=c+1}}function hT(e){return[...Jn(e)].map(({line:t,body:i})=>({line:t,body:i}))}function Ho(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function pT(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function gh(e,t,i,r=[],n="content-hash"){let a=Ho(i),o=t.replaceAll("\\","/").trim(),s=r.map(Ho);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${D(nT,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function wh(e,t,i="content-hash"){let r=new Set;for(let n of e){let a=i==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(r.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);r.add(a)}return e}function mT(e){let t=null,i=null,r=0,n=0;for(let{line:a,body:o,index:s}of Jn(e)){n=s+1;let c=o?vh(a):null;c?.level===1&&(Gs(c.text)==="acceptanceExamples"?(r+=1,r===1&&(t=s+1)):t!==null&&i===null&&(i=s))}if(r===0||t===null)return null;if(r!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:i??n}}function dl(e,t="brief.md",i=Do.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native brief acceptance budget is invalid");let n=mT(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of Jn(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(f===null)continue;let h=f[1].length;a=a===null?h:Math.min(a,h)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of Jn(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;f&&f[1].length===a?(c(),s=[f[2]]):s!==null&&s.push(l)}return c(),wh(o.map(l=>gh("brief-example",t,l.join(`
|
|
177
|
+
`),[],r)),"Brief",r)}function fl(e,t="spec.md",i=Do.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(gh("spec-scenario",t,[o.title,...o.body].join(`
|
|
178
|
+
`),o.context,r)),o=null}};for(let{line:c,body:l}of Jn(e)){let u=l?vh(c):null,d=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let f=Ho(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:f,body:[],context:a.map(h=>h.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&l&&o.body.push(c)}return s(),wh(n,"Specification",r)}function Ay(e,t="spec.md",i=Do.maxCriteria,r="content-hash"){if(!Number.isSafeInteger(i)||i<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=i)throw new Error(`Native acceptance exceeds its ${i}-criterion acceptance budget`);n.push(gh("spec-must",t,s.parts.join(" "),s.context,r)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:d}of Jn(e)){let f=d?vh(u):null;if(f){for(c(),o!==null&&f.level<=o&&(o=null);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f),/^Scenario\s*:/iu.test(f.text)&&(o=f.level);continue}let h=u.trim();if(!d||o!==null||l()){c();continue}if(h.length===0||mh(u,null)!==null||h.startsWith("<!--")||h==="-->"||h==="--!>"||/^<\/?[A-Za-z][^>]*>$/u.test(h)||/^<[A-Za-z][^>]*>.*<\/[A-Za-z][^>]*>$/u.test(h)||/^(?:[-*_]\s*){3,}$/u.test(h)||/^\|?(?:\s*:?-{3,}:?\s*\|)+\s*$/u.test(h)){c();continue}let v=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(v){c(),s={parts:[v[1]],context:a.map(m=>m.text)};continue}if(/^\|.*\|$/u.test(h)){c(),s={parts:[h],context:a.map(m=>m.text)},c();continue}s===null?s={parts:[h],context:a.map(m=>m.text)}:s.parts.push(h)}return c(),wh(n,"Specification mandatory requirements",r)}function vT(e,t){let i=e.trim().replaceAll("\\","/");if(i.length===0||pT(i)||ky.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(i)||i.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let r=ky.posix.normalize(i);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(r.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!sT.test(r))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return r}function gT(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let i=e,r=Object.keys(i).filter(n=>!oT.has(n));if(r.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${r.join(", ")}`);return i}function _y(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((i,r)=>{let n=gT(i,r),a=n.acceptance_id;if(typeof a!="string"||!aT.test(a))throw new Error(`Acceptance evidence entry ${r} has an invalid acceptance_id`);if(t.has(a))throw new Error(`Native acceptance evidence has duplicate acceptance_id: ${a}`);if(t.add(a),!Array.isArray(n.evidence_refs))throw new Error(`Acceptance evidence ${a} requires an evidence_refs array`);let o=n.evidence_refs.map(l=>{if(typeof l!="string"||l.trim().length===0)throw new Error(`Acceptance evidence ${a} has a non-empty string requirement`);return vT(l,a)});if(new Set(o).size!==o.length)throw new Error(`Acceptance evidence ${a} has a duplicate evidence ref`);let s=n.status;if(s!=="passed"&&s!=="failed")throw new Error(`Acceptance evidence ${a} status is invalid`);let c;if(Object.prototype.hasOwnProperty.call(n,"skipped_reason")){if(typeof n.skipped_reason!="string"||n.skipped_reason.trim().length===0)throw new Error(`Acceptance evidence ${a} skipped_reason must be a non-empty string`);c=n.skipped_reason.trim()}if(s==="passed"&&o.length===0)throw new Error(`Acceptance evidence ${a} passed status requires evidence_refs`);if(s==="failed"&&o.length===0&&c===void 0)throw new Error(`Acceptance evidence ${a} failed status requires evidence_refs or a skipped_reason`);if(s==="passed"&&c!==void 0)throw new Error(`Acceptance evidence ${a} passed status has invalid fields`);return{acceptance_id:a,status:s,evidence_refs:o,...c===void 0?{}:{skipped_reason:c}}})}function Ty(e){let t=hT(e);if(t.some(({line:l,body:u})=>!u&&(l===Sy||l===Ey)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let r=t.flatMap(({line:l,body:u},d)=>u&&l===Sy?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===Ey?[d]:[]);if(r.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(r[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(r[0]+1,n[0]).map(({line:l})=>l).join(`
|
|
179
|
+
`).trim();if(a.length===0)throw new Error("Native acceptance evidence block is empty");let o;try{o=JSON.parse(a)}catch(l){throw new Error(`Native acceptance evidence block is invalid JSON: ${l.message}`,{cause:l})}let s=_y(o),c=wT(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function wT(e){let t=_y([...e]).map(i=>({...i,evidence_refs:[...i.evidence_refs].sort()})).sort((i,r)=>i.acceptance_id.localeCompare(r.acceptance_id));return JSON.stringify(t,null,2)}var yT=/^A[1-9]\d*$/u;function jy(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Iy.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Iy.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function NT(e,t){return e.localeCompare(t,"en")}function hl(e){let t=jy(e.briefSource??"brief.md","Native brief source"),i=[...e.specs??[]].sort((a,o)=>NT(a.capability,o.capability));if(new Set(i.map(a=>a.capability)).size!==i.length)throw new Error("Native acceptance sources contain duplicate capabilities");let r=dl(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of i){let o=jy(a.source,`Native spec source for ${a.capability}`);r.push(...fl(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of r){a.text=Ho(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(r.length===0)throw new Error("Native change must define at least one acceptance criterion");return r.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function $y(e){let t=e.map(({id:i})=>i);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let i=0;i<t.length;i+=1)if(!yT.test(t[i])||t[i]!==`A${i+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function Oy(e,t){return e.length===t.length&&e.every((i,r)=>i.source===t[r]?.source&&i.text===t[r]?.text)}var vl=Rn(Qr(),1);import{promises as bT}from"node:fs";var Gn="comet.native.v4",Lo="comet.native.local-execution.v4";var Hy=["multi-session","single-session"];function yh(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var kT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ST=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ET=/^A[1-9][0-9]*$/u,PT=/^[a-f0-9]{64}$/u,RT=new Set(["schema","name","language","phase","status","state_version","brief","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),ml=class extends Error{constructor(i,r){super(`Native state version conflict: expected ${i}, got ${r}`);this.expectedStateVersion=i;this.actualStateVersion=r;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function Xe(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Qe(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function _e(e,t,i){if(typeof e!="string"||!i?.empty&&e.length===0)throw new Error(`${t} must be ${i?.empty?"a string":"a non-empty string"}`);return e}function bh(e,t){return e===null?null:_e(e,t)}function CT(e,t){let i=_e(e,t);if(!PT.test(i))throw new Error(`${t} must be a SHA-256 hash`);return i}function Un(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function me(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function xT(e,t){return e===null?null:me(e,t,Number.MIN_SAFE_INTEGER)}function Se(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function ui(e,t,i){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,n)=>i(r,n))}function gl(e,t){return ui(e,t,(i,r)=>_e(i,`${t}[${r}]`))}function rn(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Kn(e,t){let i=_e(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO date or timestamp`);return i}function kh(e,t,i=!1){let r=_e(e,t);if(r.includes("\\")||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").includes("..")||!i&&(r==="."||r.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return r}function At(e,t){let i=Xe(e,t);return Qe(i,new Set(["text","truncated"]),t),{text:_e(i.text,`${t}.text`,{empty:!0}),truncated:Un(i.truncated,`${t}.truncated`)}}function AT(e,t){let i=`Native spec_changes[${t}]`,r=Xe(e,i);Qe(r,new Set(["capability","operation","source"]),i);let n=_e(r.capability,`${i}.capability`);if(!ST.test(n))throw new Error(`${i}.capability is invalid`);let a=Se(r.operation,["create","modify","remove"],`${i}.operation`),o=r.source===null?null:kh(r.source,`${i}.source`);if(a==="remove"&&o!==null)throw new Error(`${i} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${i} ${a} requires a source`);return{capability:n,operation:a,source:o}}function _T(e){let t="Native workspace",i=Xe(e,t);Qe(i,new Set(["isolation","change_branch","target_branch","finish"]),t);let r=Se(i.isolation,["current","branch","worktree"],`${t}.isolation`),n=bh(i.change_branch,`${t}.change_branch`),a=bh(i.target_branch,`${t}.target_branch`),o=i.finish===null?null:Se(i.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(r==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(r==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(r!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:r,change_branch:n,target_branch:a,finish:o}}function TT(e){let t="Native loop",i=Xe(e,t);Qe(i,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let r=gl(i.previous_unresolved_ids,`${t}.previous_unresolved_ids`);rn(r,`${t}.previous_unresolved_ids`);let n=i.stop_reason===void 0?void 0:Se(i.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:Se(i.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:me(i.goal_cycle,`${t}.goal_cycle`,1),iteration:me(i.iteration,`${t}.iteration`),attempt:me(i.attempt,`${t}.attempt`),retry_epoch:me(i.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:me(i.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:me(i.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:me(i.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:r,next_action:bh(i.next_action,`${t}.next_action`)}}function IT(e,t){let i=`Native acceptance[${t}]`,r=Xe(e,i);Qe(r,new Set(["id","source","text","result","reason"]),i);let n=_e(r.id,`${i}.id`);if(!ET.test(n))throw new Error(`${i}.id must use A1, A2, ...`);return{id:n,source:kh(r.source,`${i}.source`),text:_e(r.text,`${i}.text`),result:Se(r.result,["pending","passed","failed","blocked"],`${i}.result`),reason:r.reason===null?null:At(r.reason,`${i}.reason`)}}function jT(e,t){let i=`Native builder_handoff.checks[${t}]`,r=Xe(e,i);return Qe(r,new Set(["name","result","note"]),i),{name:At(r.name,`${i}.name`),result:Se(r.result,["passed","failed","not-run"],`${i}.result`),note:r.note===null?null:At(r.note,`${i}.note`)}}function $T(e){let t="Native builder_handoff",i=Xe(e,t);Qe(i,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let r=gl(i.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);rn(r,`${t}.addressed_acceptance_ids`);let n=i.review===null||i.review===void 0?null:Xe(i.review,`${t}.review`);return n&&Qe(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:_e(i.candidate_id,`${t}.candidate_id`),identity_provider:_e(i.identity_provider,`${t}.identity_provider`),builder_execution_ref:_e(i.builder_execution_ref,`${t}.builder_execution_ref`),iteration:me(i.iteration,`${t}.iteration`,1),summary:At(i.summary,`${t}.summary`),addressed_acceptance_ids:r,checks:ui(i.checks,`${t}.checks`,jT),checks_truncated:Un(i.checks_truncated,`${t}.checks_truncated`),known_limits:ui(i.known_limits,`${t}.known_limits`,(a,o)=>At(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Un(i.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:Se(n.status,["passed"],`${t}.review.status`),summary:At(n.summary,`${t}.review.summary`),reviewer_execution_ref:_e(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Kn(i.submitted_at,`${t}.submitted_at`)}}function OT(e,t){let i=`Native blockers[${t}]`,r=Xe(e,i);Qe(r,new Set(["owner","reason","acceptance_ids","resolution_action"]),i);let n=gl(r.acceptance_ids,`${i}.acceptance_ids`);return rn(n,`${i}.acceptance_ids`),{owner:Se(r.owner,["builder","runtime","verifier","user","external"],`${i}.owner`),reason:At(r.reason,`${i}.reason`),acceptance_ids:n,resolution_action:Se(r.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${i}.resolution_action`)}}function HT(e,t){let i=`Native verification.checks[${t}]`,r=Xe(e,i);return Qe(r,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),i),{id:_e(r.id,`${i}.id`),name:At(r.name,`${i}.name`),argv_display:ui(r.argv_display,`${i}.argv_display`,(n,a)=>At(n,`${i}.argv_display[${a}]`)),argv_truncated:Un(r.argv_truncated,`${i}.argv_truncated`),cwd_ref:kh(r.cwd_ref,`${i}.cwd_ref`,!0),status:Se(r.status,["passed","failed","interrupted"],`${i}.status`),exit_code:xT(r.exit_code,`${i}.exit_code`),duration_ms:me(r.duration_ms,`${i}.duration_ms`)}}function DT(e){let t="Native verification",i=Xe(e,t);Qe(i,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let r=ui(i.checks,`${t}.checks`,HT);rn(r.map(a=>a.id),`${t}.checks IDs`);let n=_e(i.identity_provider,`${t}.identity_provider`);return{candidate_id:_e(i.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:_e(i.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:me(i.iteration,`${t}.iteration`,1),attempt:me(i.attempt,`${t}.attempt`,1),assurance:i.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":Se(i.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:Se(i.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:r,summary:At(i.summary,`${t}.summary`),risks:ui(i.risks,`${t}.risks`,(a,o)=>At(a,`${t}.risks[${o}]`)),risks_truncated:Un(i.risks_truncated,`${t}.risks_truncated`),completed_at:Kn(i.completed_at,`${t}.completed_at`)}}function Dy(e,t){let i=`Native history[${t}]`,r=Xe(e,i);Qe(r,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),i);let n=gl(r.unresolved_ids,`${i}.unresolved_ids`);return rn(n,`${i}.unresolved_ids`),{goal_cycle:me(r.goal_cycle,`${i}.goal_cycle`,1),iteration:me(r.iteration,`${i}.iteration`),attempt:me(r.attempt,`${i}.attempt`),outcome:Se(r.outcome,["pass","fail","blocked","execution-error","recovery"],`${i}.outcome`),unresolved_ids:n,summary:At(r.summary,`${i}.summary`),completed_at:Kn(r.completed_at,`${i}.completed_at`)}}function LT(e){let t="Native history_overflow.outcome_counts",i=Xe(e,t),r=["pass","fail","blocked","execution-error","recovery"];return Qe(i,new Set(r),t),{pass:me(i.pass,`${t}.pass`),fail:me(i.fail,`${t}.fail`),blocked:me(i.blocked,`${t}.blocked`),"execution-error":me(i["execution-error"],`${t}.execution-error`),recovery:me(i.recovery,`${t}.recovery`)}}function MT(e){let t="Native history_overflow",i=Xe(e,t);Qe(i,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let r=me(i.dropped_entries,`${t}.dropped_entries`),n=i.first_dropped_at===null?null:Kn(i.first_dropped_at,`${t}.first_dropped_at`),a=i.last_dropped_at===null?null:Kn(i.last_dropped_at,`${t}.last_dropped_at`);if(r===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(r>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=LT(i.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==r)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:r,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function FT(e){let t=new Set(e.acceptance.map(i=>i.id));for(let i of e.loop.previous_unresolved_ids)if(!t.has(i))throw new Error(`Native loop references unknown acceptance ID ${i}`);for(let i of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(i))throw new Error(`Native builder handoff references unknown ID ${i}`);for(let i of e.blockers)for(let r of i.acceptance_ids)if(!t.has(r))throw new Error(`Native blocker references unknown ID ${r}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let r=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!r&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function BT(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let i=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(i!==null&&e.loop.stage!==i)throw new Error(`Native status ${e.status} requires loop stage ${i}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(r=>r.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(r=>r.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function ct(e){let t=Xe(e,"Native portable state");if(Qe(t,RT,"Native portable state"),t.schema!==Gn)throw new Error(`Native portable state schema must be ${Gn}`);let i=_e(t.name,"Native state name");if(!kT.test(i))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let r=ui(t.spec_changes,"Native spec_changes",AT);rn(r.map(s=>s.capability),"Native spec change capabilities");let n=ui(t.acceptance,"Native acceptance",IT);rn(n.map(s=>s.id),"Native acceptance IDs");let a=ui(t.history,"Native history",Dy);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Gn,name:i,language:Se(t.language,["en","zh-CN"],"Native state language"),phase:Se(t.phase,["shape","build","verify","archive"],"Native state phase"),status:Se(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:me(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:CT(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:Se(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:r,workspace:_T(t.workspace),loop:TT(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:$T(t.builder_handoff),blockers:ui(t.blockers,"Native blockers",OT),verification:t.verification===null?null:DT(t.verification),history:a,history_overflow:MT(t.history_overflow),verification_result:Se(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:Se(t.verification_report,["verification.md"],"Native verification_report"),archived:Un(t.archived,"Native archived"),created_at:Kn(t.created_at,"Native created_at")};return FT(o),BT(o),o}function Yn(e,t){let i=ct(e),r=Dy(t,i.history.length),n=[...i.history,r],a={...i.history_overflow,outcome_counts:{...i.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return ct({...i,history:n,history_overflow:a})}function VT(e,t){let i=(0,vl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`${t} is invalid YAML: ${i.errors[0].message}`);return i.toJS({mapAsMap:!1})}async function Ze(e){let t=await bT.readFile(e,"utf8");return ct(VT(t,"Native portable state"))}async function wl(e,t,i={}){let r=ct(t);await he(e,(0,vl.stringify)(r),i)}var pl=new Map;async function qT(e,t){let i=pl.get(e)??Promise.resolve(),r,n=new Promise(o=>{r=o}),a=i.then(()=>n);pl.set(e,a),await i;try{return await t()}finally{r(),pl.get(e)===a&&pl.delete(e)}}async function nn(e){return qT(e.file,async()=>{let t=me(e.expectedStateVersion,"Native expected state version",1),i=ct(e.next);if(i.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let r=await Ze(e.file);if(r.state_version===i.state_version&&JSON.stringify(r)===JSON.stringify(i))return r;if(r.state_version!==t)throw new ml(t,r.state_version);return await wl(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Ze(e.file);if(n.state_version!==t)throw new ml(t,n.state_version)}}),i})}function WT(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function hr(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(WT(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let i="",r=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(r+a>t)break;i+=n,r+=a}return{text:i,truncated:!0}}var Ne="comet.native.v3",be="comet.native.v2",et="comet.native.v1",pr="comet.native.transition.v3",Ti="comet.native.transition.v2",an="comet.native.transition.v1";var yl="comet.native.portable-migration.v1",JT=new Set(["schema","id","change","fromSchema","status","createdAt"]),GT=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,UT=/^[a-z0-9][a-z0-9-]{7,127}$/u,KT=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),YT=new Set([et,be,Ne]);function XT(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function QT(e,t){let i=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(i.valueOf()))throw new Error(`${t} must be a valid timestamp`);return i.toISOString()}function ZT(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function eI(e){return e.schema===et?on(e):e.schema===be?di(e):lt(e)}function tI(e){return zT.posix.normalize(e.replaceAll("\\","/"))}function iI(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:tI(t.source)})}function rI(e){return e==="shape"?"shape":"build"}function nI(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function aI(e,t,i){return e==="zh-CN"?`从旧版 ${t} ${i} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${i} state; prior Loop, verification results, and execution records were not inherited.`}function Ly(e){let t=eI(e.state);$y(e.acceptance);let i=rI(t.phase),r=i==="shape"?0:1,n=QT(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return ct({schema:Gn,name:t.name,language:t.language,phase:i,status:"active",state_version:1,brief:"brief.md",spec_changes:iI(t),workspace:e.workspace,loop:{stage:i==="shape"?"shape":"building",goal_cycle:1,iteration:r,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:nI(t.language,i)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:r,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:hr(aI(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:yh(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Sh(e){let t=XT(e,"Native portable migration transaction"),i=Object.keys(t).filter(r=>!JT.has(r));if(i.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${i.join(", ")}`);if(t.schema!==yl)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!UT.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!GT.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!YT.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!KT.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:yl,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:ZT(t.createdAt,"Native portable migration transaction createdAt")}}function My(e){switch(Sh(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var Nl="comet.native.archive-transaction.v4",Fy="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",sI=new RegExp(`^portable-archive-(${Fy})\\.json$`,"u"),cI=new RegExp(`^portable-migration-(${Fy})\\.json$`,"u"),lI=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,uI=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dI=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),fI=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),hI=new Set(["capability","operation","source","content"]),By=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Vy(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function qy(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${i} fields are invalid`)}function pI(e,t){let i=`Native portable Archive spec_changes[${t}]`,r=Vy(e,i);if(qy(r,hI,i),typeof r.capability!="string"||!By.test(r.capability))throw new Error(`${i}.capability is invalid`);if(!["create","modify","remove"].includes(String(r.operation)))throw new Error(`${i}.operation is invalid`);let n=r.operation;if(n==="remove"){if(r.source!==null||r.content!==null)throw new Error(`${i} remove requires source and content null`);return{capability:r.capability,operation:n,source:null,content:null}}if(typeof r.source!="string"||r.source.length===0||r.source.includes("\\")||r.source.startsWith("/")||/^[A-Za-z]:/u.test(r.source)||r.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${i}.${n} source is invalid`);if(typeof r.content!="string")throw new Error(`${i}.${n} content is invalid`);return{capability:r.capability,operation:n,source:r.source,content:r.content}}function mI(e){let t=Vy(e,"Native portable Archive transaction");if(qy(t,fI,"Native portable Archive transaction"),t.schema!==Nl)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!lI.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!By.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!uI.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!dI.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let i=t.spec_changes.map(pI);if(new Set(i.map(({capability:n})=>n)).size!==i.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>i.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let r=new Date(t.created_at);if(Number.isNaN(r.valueOf())||r.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Nl,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:i,created_at:t.created_at}}function sn(e){let t=sI.exec(e);if(t)return{kind:"archive",change:t[1]};let i=cI.exec(e);return i?{kind:"migration",change:i[1]}:null}function mr(e,t){let i=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,r=sn(i);if(!r||r.kind!==t.kind||r.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Eh.join(e.transactionsDir,i)}async function Mo(e,t){let i=sn(t);if(!i)return null;let r=await Z({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(r.text),a=Eh.join(e.transactionsDir,t);if(i.kind==="archive"){let s=mI(n);if(s.change!==i.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:i.change,file:a,journal:s}}let o=Sh(n);if(o.change!==i.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:i.change,file:a,journal:o}}async function bl(e,t){let i=mr(e,t);try{return await Mo(e,Eh.basename(i))}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Wy(e){let t;try{t=await oI.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.map(({name:i})=>i).filter(i=>sn(i)!==null).sort((i,r)=>i.localeCompare(r,"en"))}function zy(e){return e.kind==="archive"||e.journal.status!=="committed"}import{promises as Fo}from"fs";import _t from"path";import{TextDecoder as NI}from"util";import{createHash as vI}from"node:crypto";import{constants as kl,promises as W}from"node:fs";import Y from"node:path";import{TextDecoder as gI}from"node:util";function ze(e,t){let i=Y.relative(e,t);return i===""||!Y.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Y.sep}`)}function Jy(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Qn(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Gy(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Xn(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function vr(e,t){let i=await W.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await W.realpath(e),dev:i.dev,ino:i.ino,birthtimeMs:i.birthtimeMs}}async function gr(e,t,i){let r=Y.resolve(e),n=Y.resolve(t);if(!ze(r,n))throw new Error(`${i} is outside its managed root`);let a=[await vr(r,i)],o=r;for(let s of Y.relative(r,n).split(Y.sep).filter(Boolean)){await we(a,i),o=Y.join(o,s);let c=await vr(o,i);if(!ze(a[0].realPath,c.realPath))throw new Error(`${i} parent resolves outside its managed root: ${o}`);a.push(c)}return await we(a,i),a}async function we(e,t){for(let i of e){let r=await W.lstat(i.path);if(!r.isDirectory()||r.isSymbolicLink()||!Qn(i,r)||await W.realpath(i.path)!==i.realPath)throw new Error(`${t} parent changed during I/O: ${i.path}`)}}async function wI(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function re(e){let t=Jy(e.maxBytes),i=Y.resolve(e.file),r=await gr(e.root,Y.dirname(i),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>vr(Y.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await we(r,e.label);let a=await W.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=Gy(a),s=await W.realpath(i);if(!ze(r[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>ze(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?kl.O_RDONLY:kl.O_RDONLY|kl.O_NOFOLLOW|kl.O_NONBLOCK,l=await W.open(i,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([W.lstat(i),W.realpath(i)]);if(await we(r,e.label),await we(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Xn(o,u)||!Xn(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await wI(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,m,p]=await Promise.all([l.stat(),W.lstat(i),W.realpath(i)]);if(await we(r,e.label),await we(n,e.label),!m.isFile()||m.isSymbolicLink()||p!==s||!Xn(o,v)||!Xn(o,m))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:vI("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function Sl(e){let t=await re(e),i;try{i=new gI("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e.label} is not valid UTF-8`,{cause:r})}return{...t,text:i}}async function wt(e){let t=await gr(e.root,e.directory,e.label),i;if(e.maxEntries===void 0)i=await W.readdir(e.directory,{withFileTypes:!0});else{let r=Jy(e.maxEntries);i=[];let n=await W.opendir(e.directory);try{for await(let a of n)if(i.push(a),i.length>r)throw new Error(`${e.label} exceeds ${r} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await we(t,e.label),{entries:i,verify:()=>we(t,e.label)}}async function Qt(e){let t=await gr(e.root,e.directory,e.label);return{verify:()=>we(t,e.label)}}async function yI(e){let t=Y.resolve(e.directory),i=Y.resolve(e.quarantine);if(Y.dirname(i)!==Y.dirname(t)||!ze(Y.resolve(e.root),i)||i===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let r=await gr(e.root,Y.dirname(t),e.label),n=await vr(t,e.label);if(!ze(r[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await we(r,e.label);let a=await W.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!Qn(n,a)||await W.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await W.lstat(i),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await W.rename(t,i),await we(r,e.label);let o=await W.lstat(i);if(!o.isDirectory()||o.isSymbolicLink()||!Qn(n,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(i);try{throw await W.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:i,parentChain:r,identity:n}}async function Uy(e){await yI(e)}async function El(e){let t=Y.resolve(e.file),i=await gr(e.root,Y.dirname(t),e.label),r=await W.lstat(t);if(!r.isFile()||r.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let n=Gy(r),a=await W.realpath(t);if(!ze(i[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await re({root:e.root,file:t,maxBytes:e.maxBytes,label:e.label});if(o.hash!==e.expectedHash||o.size!==e.expectedSize)throw new Error(`${e.label} changed before removal`);let[s,c]=await Promise.all([W.lstat(t),W.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!Xn(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await we(i,e.label);let[l,u]=await Promise.all([W.lstat(t),W.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Xn(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await W.rm(t),await we(i,e.label)}async function Ph(e){let t=Y.resolve(e.directory),i=await gr(e.root,Y.dirname(t),e.label),r=await vr(t,e.label);if(!ze(i[0].realPath,r.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await we(i,e.label);let n=await W.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!Qn(r,n)||await W.realpath(t)!==r.realPath)throw new Error(`${e.label} changed before removal`);await W.rmdir(t),await we(i,e.label)}async function fi(e){let t=Y.resolve(e.root),i=Y.resolve(e.directory);if(!ze(t,i))throw new Error(`${e.label} is outside its managed root`);let r=[await vr(t,e.label)],n=t;for(let a of Y.relative(t,i).split(Y.sep).filter(Boolean)){await we(r,e.label),n=Y.join(n,a);try{await W.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await vr(n,e.label);if(!ze(r[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);r.push(o)}await we(r,e.label)}async function Rh(e){let t=Y.resolve(e.root),i=Y.resolve(e.source),r=Y.resolve(e.target);if(i===r||!ze(t,i)||!ze(t,r)||ze(i,r)||ze(r,i))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await fi({root:t,directory:Y.dirname(r),label:`${e.label} target parent`});let n=await gr(t,Y.dirname(i),e.label),a=await gr(t,Y.dirname(r),e.label),o=await vr(i,e.label);if(!ze(n[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await W.lstat(r),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([we(n,e.label),we(a,e.label)]);let s=await W.lstat(i);if(!s.isDirectory()||s.isSymbolicLink()||!Qn(o,s)||await W.realpath(i)!==o.realPath)throw new Error(`${e.label} source changed before move`);await W.rename(i,r),await Promise.all([we(n,e.label),we(a,e.label)]);let c=await W.lstat(r);if(!c.isDirectory()||c.isSymbolicLink()||!Qn(o,c)||!ze(n[0].realPath,await W.realpath(r)))throw new Error(`${e.label} source identity changed while moving`);try{throw await W.lstat(i),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function wr(e){let t=await re({root:e.sourceRoot,file:e.source,maxBytes:e.maxBytes,label:e.label,hooks:e.hooks,forbiddenRoots:e.forbiddenRoots});if(e.expectedHash!==void 0&&t.hash!==e.expectedHash)throw new Error(`${e.label} content changed before copy`);await Gw(e.target,t.bytes,{containedRoot:e.targetRoot,exclusive:e.exclusive,beforeCommit:async()=>{if(await e.hooks?.beforeTargetCommit?.(),e.expectedTargetHash===void 0)return;if(e.expectedTargetHash===null){try{await W.lstat(e.target)}catch(n){if(n.code==="ENOENT")return;throw n}throw new Error(`${e.label} target changed before commit`)}if((await re({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} existing target`})).hash!==e.expectedTargetHash)throw new Error(`${e.label} target changed before commit`)}});let i=await re({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(i.hash!==t.hash||i.size!==t.size)throw new Error(`${e.label} target could not be verified`);return i}var bI=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),kI=new Set(["id","type","source","target","staged","backup"]),SI=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),EI=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),PI=new Set(["sequence","timestamp","type","operationId"]),Qy=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),Zy=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),RI=256*1024,CI=1024*1024,eN=16*1024,Rl=1024,Ah=64*1024*1024,xI=2e4,tN=new NI("utf-8",{fatal:!0});function Bo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Vo(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function ea(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Ch(e,t){if(typeof e!="string"||e.length===0||_t.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Pl(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Ky(e,t){if(Ch(e,t),e.includes("\\")||e!==_t.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function AI(e,t){let i=Bo(e,`transaction operations[${t}]`);if(Vo(i,kI,`transaction operations[${t}]`),typeof i.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.id))throw new Error(`transaction operations[${t}].id is invalid`);if(i.type!=="write"&&i.type!=="remove"&&i.type!=="move")throw new Error(`transaction operation ${i.id} has an invalid type`);Ch(i.target,`transaction operation ${i.id} target`);for(let r of["source","staged","backup"])i[r]!==void 0&&Ch(i[r],`transaction operation ${i.id} ${r}`);if(i.type==="write"){if(i.staged===void 0||i.source!==void 0)throw new Error(`write operation ${i.id} requires staged and forbids source`)}else if(i.type==="remove"){if(i.source!==void 0||i.staged!==void 0)throw new Error(`remove operation ${i.id} forbids source and staged`)}else if(i.source===void 0||i.staged!==void 0||i.backup!==void 0)throw new Error(`move operation ${i.id} requires source and forbids staged and backup`);return i}function xl(e){let t=Bo(e,"Native Archive transaction journal");if(Vo(t,SI,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!Qy.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!ea(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Pl(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let i=t.operations.map((s,c)=>{let l=Bo(s,`Archive transaction operations[${c}]`);if(Vo(l,EI,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);Ky(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Ky(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Pl(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(Pl(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);Pl(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),r=i.map(s=>s.id);if(new Set(r).size!==r.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=i.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||i.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of i.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:i}}function _h(e){let t=Bo(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return xl(t);if(Vo(t,bI,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!Qy.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!_t.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!_t.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!ea(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let i=t.operations.map(AI),r=i.map(n=>n.id);if(new Set(r).size!==r.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:i}}function iN(e,t){let i=Bo(e,`Native transaction event at line ${t}`);if(Vo(i,PI,`Native transaction event at line ${t}`),i.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!ea(i.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof i.type!="string"||!Zy.has(i.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let r=i.type==="operation-started"||i.type==="operation-completed";if(r&&(typeof i.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(i.operationId)||Buffer.byteLength(i.operationId,"utf8")>256)||!r&&i.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:i.sequence,timestamp:i.timestamp,type:i.type,...typeof i.operationId=="string"?{operationId:i.operationId}:{}}}function _I(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let r=0;r<e.length;r+=1){let n=t[r],a=e[r];if(n==="0"){if(!/[0-9]/u.test(a))return!1}else if(a!==n)return!1}let i=[[5,2,1,12],[8,2,1,31],[11,2,0,23],[14,2,0,59],[17,2,0,59],[20,3,0,999]];for(let[r,n,a,o]of i){if(e.length<=r)continue;let s=e.slice(r,Math.min(r+n,e.length));if(!Array.from({length:o-a+1},(l,u)=>String(a+u).padStart(n,"0")).some(l=>l.startsWith(s)))return!1}return e.length>=10&&!ea(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||ea(e)}function Zn(e,t){return e.length<t.length&&t.startsWith(e)}function TI(e){let t='","operationId":"';if(Zn(e,t))return!0;if(!e.startsWith(t))return!1;let i=e.slice(t.length),r=i.indexOf('"');if(r===-1)return i.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(i);let n=i.slice(0,r);return/^[a-z0-9][a-z0-9-]*$/u.test(n)?Zn(i.slice(r),'"}'):!1}function II(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>eN)return!1;let i=`{"sequence":${t},"timestamp":"`;if(Zn(e,i))return!0;if(!e.startsWith(i))return!1;let r=e.slice(i.length),n=r.slice(0,Math.min(24,r.length));if(!_I(n))return!1;if(r.length<24)return!0;if(!ea(n))return!1;let a='","type":"',o=r.slice(24);if(Zn(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of Zy){if(Zn(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(TI(l))return!0}else if(Zn(l,'"}'))return!0}return!1}function jI(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>eN)throw new Error(`Native transaction event at line ${t} is too large`);return iN(JSON.parse(e),t)}function $I(e){let t=e.split(`
|
|
180
|
+
`),i=t.at(-1)==="";if(i&&t.pop(),t.length>Rl)throw new Error(`Native transaction event log exceeds ${Rl} events`);let r=[];for(let n=0;n<t.length;n+=1){let a=n+1,o=t[n],s=o.endsWith("\r")?o.slice(0,-1):o,c=!i&&n===t.length-1;try{r.push(jI(s,a))}catch(l){if(c){let u=!1;try{JSON.parse(s),u=!0}catch{}if(!u&&II(s,a))break}throw new Error(`Invalid Native transaction event at line ${a}`,{cause:l})}}return r}function rN(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
181
181
|
`)}
|
|
182
|
-
`}function gI(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return At.join(e.transactionsDir,t)}function Pl(e,t){let i=gI(e,t);return{directory:i,journal:At.join(i,"transaction.json"),events:At.join(i,"events.jsonl"),staged:At.join(i,"staged"),backups:At.join(i,"backups")}}async function fi(e,t){let i=Pl(e,t);return await Promise.all(Object.values(i).map(r=>T(e.runtimeDir,r))),i}function wI(e,t){if(t.length===0||At.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i="runtime/",r=t==="runtime"||t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=t==="runtime"?"":r?t.slice(i.length):t,o=At.resolve(n,...a.split(/[\\/]/u));if(!O(n,o))throw new Error(`Unsafe Native transaction ref: ${t}`);return o}async function gr(e,t){let i=wI(e,t);return T(j(e,i),i)}async function on(e){try{return await Mo.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ah(e,t,i={}){let r=await fi(e,t);try{await Mo.lstat(r.events)}catch(n){if(n.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw n}try{let n=await ie({root:e.runtimeDir,file:r.events,maxBytes:lI,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=Yy.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=vI(a),s=Qy(o);return{exists:!0,hash:n.hash,size:n.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:n}):n}}async function zy(e,t,i){let r=await Ah(e,t);if(r.exists!==i.exists||r.hash!==i.hash||r.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function _t(e,t,i,r){let n=await fi(e,t),a=await Ah(e,t),o=a.events.find(c=>c.type===i&&c.operationId===r);if(o)return a.needsRepair&&await fe(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>zy(e,t,a)}),o;if(a.events.length>=kl)throw new Error(`Native transaction event log ${t} exceeds ${kl} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...r?{operationId:r}:{}};return Xy(s,s.sequence),await Mo.mkdir(n.directory,{recursive:!0}),await fe(n.events,Qy([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>zy(e,t,a)}),s}async function Zy(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=xh(t);let i=await fi(e,t.id);await Mo.mkdir(i.staged,{recursive:!0}),await Mo.mkdir(i.backups,{recursive:!0}),await Z(i.journal,t,{containedRoot:e.runtimeDir}),await _t(e,t.id,"prepared")}async function wt(e,t,i={}){let r=await fi(e,t),n=await ie({root:e.runtimeDir,file:r.journal,maxBytes:cI,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(Yy.decode(n.bytes)),o=xh(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function wr(e,t,i={}){return(await Ah(e,t,i)).events}async function Sl(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=xh({...t,status:i});return await Z((await fi(e,t.id)).journal,r,{containedRoot:e.runtimeDir}),r}async function Rh(e,t,i){try{return await ie({root:j(e,t),file:t,maxBytes:Ch,label:i})}catch(r){if(r.code==="ENOENT")return null;throw r}}async function _h(e,t,i,r){let n=await Rh(e,t,`${r} source`);if(!n)throw new Error(`${r} source does not exist`);let a=await Rh(e,i,`${r} target`);await di({root:j(e,i),directory:At.dirname(i),label:`${r} target parent`}),await vr({sourceRoot:j(e,t),source:t,targetRoot:j(e,i),target:i,maxBytes:Ch,label:r,expectedHash:n.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function eN(e,t,i){let r=await Rh(e,t,i);r&&await Nl({root:j(e,t),file:t,maxBytes:Ch,expectedHash:r.hash,expectedSize:r.size,label:i})}async function Jy(e,t){if(!t.backup)return;let i=await gr(e,t.target),r=await gr(e,t.backup);!await on(i)||await on(r)||await _h(e,i,r,`Legacy Native transaction backup ${t.id}`)}async function yI(e,t){let i=await gr(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await Jy(e,t),await _h(e,await gr(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await Jy(e,t),await eN(e,i,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let r=await gr(e,t.source),[n,a]=await Promise.all([on(r),on(i)]);if(!n&&a){await(await gt({root:j(e,i),directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:uI})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!n)throw new Error(`Move source does not exist: ${t.source}`);await Eh({root:j(e,r),source:r,target:i,label:`Legacy Native transaction move ${t.id}`})}async function tN(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=t.status==="prepared"?await Sl(e,t,"applying"):t,n=await wr(e,t.id),a=new Set(n.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of r.operations)a.has(s.id)||(await _t(e,r.id,"operation-started",s.id),await yI(e,s),await _t(e,r.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return r=await wt(e,r.id),r}async function NI(e,t){let i=await gr(e,t.target),r=t.backup?await gr(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await gr(e,t.source);if(await on(i)){if(await on(n))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await Eh({root:j(e,i),source:i,target:n,label:`Legacy Native transaction rollback move ${t.id}`})}return}r&&await on(r)?await _h(e,r,i,`Legacy Native transaction rollback restore ${t.id}`):await eN(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function Rl(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=await wr(e,t.id);if(i.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let r=await Sl(e,t,"rolling-back");await _t(e,r.id,"rollback-started");let n=new Set(i.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...r.operations].reverse())n.has(a.id)&&await NI(e,a);return await _t(e,r.id,"rollback-completed"),r=await Sl(e,r,"rolled-back"),r}async function Zn(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await _t(e,t.id,i),i==="commit"?Sl(e,t,"committed"):t}async function SI(e,t,i){let r;try{r=await bI.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await wt(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(an(n.name))try{let a=await Do(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(Fy(a))return!0}catch{return!0}return!1}async function EI(e,t){let i=Date.now()+5e3,r=kI.join(e.locksDir,"root-move.lock");for(;;)try{return await lr(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Io(r);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function oe(e,t,i,r){let n=await EI(e,t);try{if(await Vn(e.projectRoot),await SI(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await ur(n)}}function iN(e){return Number.isSafeInteger(e)&&e>=1}async function rN(e){if(!iN(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!iN(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((r,n)=>JSON.stringify(r)===JSON.stringify(n));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as Tl}from"crypto";import{spawn as hN}from"node:child_process";import{promises as se}from"fs";import V from"path";import{createHash as nN}from"crypto";import{createReadStream as PI}from"fs";async function Qt(e){let t=nN("sha256");for await(let i of PI(e))t.update(i);return t.digest("hex")}function M(e){return nN("sha256").update(e).digest("hex")}var Cl={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Hh=1e3,RI=8*1024*1024,CI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xI=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),AI=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),_I=new Set(["schema","include","exclude","hash"]),TI=new Set(["provider","gitSelection","physicalSelection","projection"]),II=new Set(["provider","selection"]),jI=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),$I=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),OI=new Set(["schema","status","before","after"]),HI=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),DI=new Set(["path","hash","size","type","gitObjectId"]),MI=new Set(["path","size","type","reason"]),LI=new Set(["ref","hash","count"]),FI=new Set(["change-created","legacy-migration","explicit"]),BI=new Set(["file","directory","other"]),VI=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),Il=/^[a-f0-9]{64}$/u,pN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,qI=new Set(["EACCES","EPERM"]),na=64*1024,$h=64*1024,WI=6e4,zI=1e3,JI=2,Dh={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},GI={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function mN(e){let t=e.deadlineMs??WI;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function Zt(e){return Math.max(0,e.deadlineAt-Date.now())}function L(e){return Zt(e)>=1}function Th(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function ia(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function UI(e){let t={...GI,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function KI(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,n=r&&V.win32.isAbsolute(r)?V.win32.resolve(r):"C:\\Windows",a=V.win32.join(n,"System32","taskkill.exe");if(!V.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,h=!1)=>{c||(c=!0,u&&clearTimeout(u),h&&l?.kill("SIGKILL"),s(f))};try{l=hN(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),zI),u.unref()}catch{d(!1)}});for(let s=0;s<JI;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}function Mh(e,t,i,r){let n=Zt(e);if(n<1)throw Th();let a=e.gitProcess,o=hN(a.command,[...a.argsPrefix??[],"-C",t,...i],{cwd:t,stdio:[r?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",h=>{s=h});let u=new Promise(h=>{o.once("close",h)}),d=setTimeout(()=>{c=!0,l=KI(o,a).then(()=>({error:null}),h=>({error:h}))},n);d.unref();let f=u.then(async h=>{if(clearTimeout(d),c){let v=await l;throw v?.error?Th(v.error):Th()}return{code:h,spawnError:s}});return{child:o,completion:f}}function vN(e){let t={...Dh,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function xl(e,t,i,r=$h){let{child:n,completion:a}=Mh(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",h=>{let v=Math.max(0,r-l);v>0&&o.push(Buffer.from(h).subarray(0,v)),l+=h.byteLength,l>r&&(u=!0)}),n.stderr.on("data",h=>{if(c>=na)return;let v=na-c,m=Buffer.from(h).subarray(0,v);s.push(m),c+=m.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function Ih(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Vo(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=Mh(e,t,i,r.stdin!==void 0),c=[],l=Tl("sha256"),u=[],d=0,f=0,h=0,v=0,m=Buffer.alloc(0),p=!1,b=!1,g=!1,y=E=>{let k=0;for(;k<E.byteLength;){let S=E.indexOf(0,k),R=S<0?E.byteLength:S,N=E.subarray(k,R);if(!p&&N.byteLength>0&&(m.byteLength+N.byteLength>r.maxRecordBytes?(m=Buffer.alloc(0),p=!0,b=!0):m=Buffer.concat([m,N])),S<0)break;v+=1,m.byteLength===0&&!p&&(g=!0);let w=m.byteLength+1;!p&&v<=r.maxRecords&&h+w<=r.maxBytes?(c.push(m),h+=w):b=!0,m=Buffer.alloc(0),p=!1,k=S+1}};o.stdout.on("data",E=>{l.update(E),f+=E.byteLength,f>r.maxBytes&&(b=!0);let k=r.outputChunkBytes;if(k===void 0){y(E);return}for(let S=0;S<E.byteLength;S+=k)y(E.subarray(S,Math.min(E.byteLength,S+k)))}),o.stderr.on("data",E=>{if(d>=na)return;let k=na-d,S=Buffer.from(E).subarray(0,k);u.push(S),d+=S.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:E,spawnError:k})=>{let S=r.acceptedExitCodes??[0];if(E!==null&&S.includes(E)&&k===null&&!g&&m.byteLength===0&&!p){n({records:c,digest:l.digest("hex"),overflow:b,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${k?`: ${k.message}`:g||m.byteLength>0||p?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function Al(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function YI(e,t,i){if(i.length===0)return new Set;let r=await Vo(e,t,["check-ignore","--no-index","-z","--stdin"],{...Dh,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(r.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(r.records.map(n=>{let a=Al(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function XI(e,t,i){let{child:r,completion:n}=Mh(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=na)return;let d=na-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function ra(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||V.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||V.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function QI(e,t){return e.map(i=>{let r=ra(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function ZI(e){let t=V.resolve(e);for(;;){try{return await se.lstat(V.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=V.dirname(t);if(i===t)return!1;t=i}}async function gN(e,t,i,r={}){let n=V.resolve(t.projectRoot),a=V.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let h=V.relative(n,V.resolve(f)).replaceAll("\\","/"),v=ra(h);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await Vo(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await Vo(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await Vo(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function wN(e){return{stageBefore:Ih(e.stagedBefore),combined:Ih(e.combined),stageAfter:Ih(e.stagedAfter)}}async function yN(e,t,i=Dh,r={}){let n=V.resolve(t.projectRoot);if(!await ZI(n))return null;let a;try{a=await xl(e,n,["rev-parse","--is-inside-work-tree"])}catch(g){throw ia(g)?g:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:g})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await gN(e,t,i,r)}catch(g){throw ia(g)?g:new Error("Native Git snapshot provider failed after repository detection",{cause:g})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,h=g=>{for(let y of g){let E=Al(y),k=E.indexOf(" ");if(k<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let S=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(E.slice(0,k))?.groups;if(!S)throw new Error("Native Git snapshot provider returned a malformed staged header");let R=ra(E.slice(k+1));if(R===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(R),S.stage==="0"&&d.set(R,S.objectId),S.mode==="160000"&&S.stage==="0"&&f.add(R)}};h(s.records),h(l.records);let v=c.records.map(Al),m=QI(v,"combined"),p=new Set(m.filter(g=>!u.has(g))),b=new Set(m.filter((g,y)=>!u.has(g)&&v[y].endsWith("/")));for(let g of f)b.delete(g);return{tracked:u,trackedObjectIds:d,untracked:p,gitlinks:f,nestedRepositories:b,omissions:[],overflow:null,evidence:null,initialFence:wN(o)}}function Nr(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function aN(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function ej(e,t){return!Nr(e.stageBefore,e.stageAfter)||!Nr(e.stageAfter,t.stageBefore)||!Nr(e.combined,t.combined)||!Nr(t.stageBefore,t.stageAfter)}async function NN(e,t,i,r,n){let a;try{a=await gN(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw ia(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=wN(a),c=aN(o)||aN(s),l=ej(o,s);c&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),r.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(r.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:M(`comet.native.git-selection-overflow.v2
|
|
183
|
-
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var
|
|
184
|
-
${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):
|
|
185
|
-
${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:y,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:h,unstable:v}}}function
|
|
186
|
-
`)}function
|
|
187
|
-
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function
|
|
182
|
+
`}function OI(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return _t.join(e.transactionsDir,t)}function Al(e,t){let i=OI(e,t);return{directory:i,journal:_t.join(i,"transaction.json"),events:_t.join(i,"events.jsonl"),staged:_t.join(i,"staged"),backups:_t.join(i,"backups")}}async function hi(e,t){let i=Al(e,t);return await Promise.all(Object.values(i).map(r=>T(e.runtimeDir,r))),i}function HI(e,t){if(t.length===0||_t.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let i="runtime/",r=t==="runtime"||t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=t==="runtime"?"":r?t.slice(i.length):t,o=_t.resolve(n,...a.split(/[\\/]/u));if(!O(n,o))throw new Error(`Unsafe Native transaction ref: ${t}`);return o}async function yr(e,t){let i=HI(e,t);return T(j(e,i),i)}async function cn(e){try{return await Fo.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Th(e,t,i={}){let r=await hi(e,t);try{await Fo.lstat(r.events)}catch(n){if(n.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw n}try{let n=await re({root:e.runtimeDir,file:r.events,maxBytes:CI,label:`Native transaction event log ${t}`,hooks:i.hooks}),a;try{a=tN.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=$I(a),s=rN(o);return{exists:!0,hash:n.hash,size:n.size,events:o,canonicalSource:s,needsRepair:a!==s}}catch(n){throw n.code==="ENOENT"?new Error(`Native transaction event log ${t} changed while reading`,{cause:n}):n}}async function Yy(e,t,i){let r=await Th(e,t);if(r.exists!==i.exists||r.hash!==i.hash||r.size!==i.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function Tt(e,t,i,r){let n=await hi(e,t),a=await Th(e,t),o=a.events.find(c=>c.type===i&&c.operationId===r);if(o)return a.needsRepair&&await he(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>Yy(e,t,a)}),o;if(a.events.length>=Rl)throw new Error(`Native transaction event log ${t} exceeds ${Rl} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:i,...r?{operationId:r}:{}};return iN(s,s.sequence),await Fo.mkdir(n.directory,{recursive:!0}),await he(n.events,rN([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>Yy(e,t,a)}),s}async function nN(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=_h(t);let i=await hi(e,t.id);await Fo.mkdir(i.staged,{recursive:!0}),await Fo.mkdir(i.backups,{recursive:!0}),await ee(i.journal,t,{containedRoot:e.runtimeDir}),await Tt(e,t.id,"prepared")}async function yt(e,t,i={}){let r=await hi(e,t),n=await re({root:e.runtimeDir,file:r.journal,maxBytes:RI,label:`Native transaction journal ${t}`,hooks:i.hooks}),a=JSON.parse(tN.decode(n.bytes)),o=_h(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function Nr(e,t,i={}){return(await Th(e,t,i)).events}async function Cl(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=_h({...t,status:i});return await ee((await hi(e,t.id)).journal,r,{containedRoot:e.runtimeDir}),r}async function xh(e,t,i){try{return await re({root:j(e,t),file:t,maxBytes:Ah,label:i})}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Ih(e,t,i,r){let n=await xh(e,t,`${r} source`);if(!n)throw new Error(`${r} source does not exist`);let a=await xh(e,i,`${r} target`);await fi({root:j(e,i),directory:_t.dirname(i),label:`${r} target parent`}),await wr({sourceRoot:j(e,t),source:t,targetRoot:j(e,i),target:i,maxBytes:Ah,label:r,expectedHash:n.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function aN(e,t,i){let r=await xh(e,t,i);r&&await El({root:j(e,t),file:t,maxBytes:Ah,expectedHash:r.hash,expectedSize:r.size,label:i})}async function Xy(e,t){if(!t.backup)return;let i=await yr(e,t.target),r=await yr(e,t.backup);!await cn(i)||await cn(r)||await Ih(e,i,r,`Legacy Native transaction backup ${t.id}`)}async function DI(e,t){let i=await yr(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await Xy(e,t),await Ih(e,await yr(e,t.staged),i,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await Xy(e,t),await aN(e,i,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let r=await yr(e,t.source),[n,a]=await Promise.all([cn(r),cn(i)]);if(!n&&a){await(await wt({root:j(e,i),directory:i,label:`Legacy Native transaction move target ${t.id}`,maxEntries:xI})).verify();return}if(a)throw new Error(`Move target already exists: ${t.target}`);if(!n)throw new Error(`Move source does not exist: ${t.source}`);await Rh({root:j(e,r),source:r,target:i,label:`Legacy Native transaction move ${t.id}`})}async function oN(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=t.status==="prepared"?await Cl(e,t,"applying"):t,n=await Nr(e,t.id),a=new Set(n.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of r.operations)a.has(s.id)||(await Tt(e,r.id,"operation-started",s.id),await DI(e,s),await Tt(e,r.id,"operation-completed",s.id),o+=1,await i?.afterOperation?.(s,o));return r=await yt(e,r.id),r}async function LI(e,t){let i=await yr(e,t.target),r=t.backup?await yr(e,t.backup):null;if(t.type==="move"){if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let n=await yr(e,t.source);if(await cn(i)){if(await cn(n))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await Rh({root:j(e,i),source:i,target:n,label:`Legacy Native transaction rollback move ${t.id}`})}return}r&&await cn(r)?await Ih(e,r,i,`Legacy Native transaction rollback restore ${t.id}`):await aN(e,i,`Legacy Native transaction rollback remove ${t.id}`)}async function _l(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=await Nr(e,t.id);if(i.some(a=>a.type==="archive-finalization-started"||a.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let r=await Cl(e,t,"rolling-back");await Tt(e,r.id,"rollback-started");let n=new Set(i.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...r.operations].reverse())n.has(a.id)&&await LI(e,a);return await Tt(e,r.id,"rollback-completed"),r=await Cl(e,r,"rolled-back"),r}async function ta(e,t,i){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await Tt(e,t.id,i),i==="commit"?Cl(e,t,"committed"):t}async function BI(e,t,i){let r;try{r=await MI.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await yt(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of r)if(sn(n.name))try{let a=await Mo(e,n.name);if(!a||i?.kind===a.kind&&i.change===a.change)continue;if(zy(a))return!0}catch{return!0}return!1}async function VI(e,t){let i=Date.now()+5e3,r=FI.join(e.locksDir,"root-move.lock");for(;;)try{return await dr(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await $o(r);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=i)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function se(e,t,i,r){let n=await VI(e,t);try{if(await Wn(e.projectRoot),await BI(e,r?.allowedTransactionId,r?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await i()}finally{await fr(n)}}function sN(e){return Number.isSafeInteger(e)&&e>=1}async function cN(e){if(!sN(e.expectedRevision))throw new Error("Native expected revision must be a positive integer");if(e.next.revision!==e.expectedRevision+1)throw new Error("Native CAS next revision must increment the expected revision exactly once");let t=await e.read();if(!sN(t.revision))throw new Error("Native current revision must be a positive integer");let i=e.equals??((r,n)=>JSON.stringify(r)===JSON.stringify(n));if(t.revision===e.next.revision&&i(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}import{createHash as Ol}from"crypto";import{spawn as wN}from"node:child_process";import{promises as ce}from"fs";import V from"path";import{createHash as lN}from"crypto";import{createReadStream as qI}from"fs";async function Zt(e){let t=lN("sha256");for await(let i of qI(e))t.update(i);return t.digest("hex")}function L(e){return lN("sha256").update(e).digest("hex")}var Tl={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Lh=1e3,WI=8*1024*1024,zI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,JI=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),GI=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),UI=new Set(["schema","include","exclude","hash"]),KI=new Set(["provider","gitSelection","physicalSelection","projection"]),YI=new Set(["provider","selection"]),XI=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),QI=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),ZI=new Set(["schema","status","before","after"]),ej=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),tj=new Set(["path","hash","size","type","gitObjectId"]),ij=new Set(["path","size","type","reason"]),rj=new Set(["ref","hash","count"]),nj=new Set(["change-created","legacy-migration","explicit"]),aj=new Set(["file","directory","other"]),oj=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),Hl=/^[a-f0-9]{64}$/u,yN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,sj=new Set(["EACCES","EPERM"]),oa=64*1024,Hh=64*1024,cj=6e4,lj=1e3,uj=2,Mh={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},dj={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function NN(e){let t=e.deadlineMs??cj;if(!Number.isSafeInteger(t)||t<1)throw new Error("Native snapshot execution budget must be a positive integer");return{deadlineAt:Date.now()+t,gitProcess:e.gitProcess??{command:"git"}}}function ei(e){return Math.max(0,e.deadlineAt-Date.now())}function M(e){return ei(e)>=1}function jh(e){let t=e===void 0?new Error("Native snapshot deadline exceeded while waiting for Git"):new Error("Native snapshot deadline exceeded while waiting for Git",{cause:e});return Object.assign(t,{code:"GIT_SNAPSHOT_TIMEOUT"})}function na(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function fj(e){let t={...dj,...e};if(!Number.isSafeInteger(t.maxNodes)||t.maxNodes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxPathBytes)||t.maxPathBytes<1||t.maxPathBytes>t.maxBytes)throw new Error("Native physical selection limits must be positive bounded integers");return t}async function hj(e,t){if(t.terminateTree){await t.terminateTree(e);return}let i=e.pid;if(i===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,n=r&&V.win32.isAbsolute(r)?V.win32.resolve(r):"C:\\Windows",a=V.win32.join(n,"System32","taskkill.exe");if(!V.win32.isAbsolute(a))throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git taskkill path is not trusted"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"});let o=()=>new Promise(s=>{let c=!1,l=null,u=null,d=(f,h=!1)=>{c||(c=!0,u&&clearTimeout(u),h&&l?.kill("SIGKILL"),s(f))};try{l=wN(a,["/pid",String(i),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),lj),u.unref()}catch{d(!1)}});for(let s=0;s<uj;s+=1)if(await o()){e.kill("SIGKILL");return}throw e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy(),Object.assign(new Error("Native Git process-tree termination could not be confirmed on Windows"),{code:"GIT_SNAPSHOT_TERMINATION_UNCONFIRMED"})}try{process.kill(-i,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}function Fh(e,t,i,r){let n=ei(e);if(n<1)throw jh();let a=e.gitProcess,o=wN(a.command,[...a.argsPrefix??[],"-C",t,...i],{cwd:t,stdio:[r?"pipe":"ignore","pipe","pipe"],windowsHide:!0,detached:process.platform!=="win32"}),s=null,c=!1,l=null;o.once("error",h=>{s=h});let u=new Promise(h=>{o.once("close",h)}),d=setTimeout(()=>{c=!0,l=hj(o,a).then(()=>({error:null}),h=>({error:h}))},n);d.unref();let f=u.then(async h=>{if(clearTimeout(d),c){let v=await l;throw v?.error?jh(v.error):jh()}return{code:h,spawnError:s}});return{child:o,completion:f}}function bN(e){let t={...Mh,...e};if(!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecordBytes)||t.maxRecordBytes<1||t.maxRecordBytes>t.maxBytes)throw new Error("Native Git selection limits must be positive bounded integers");return t}async function Il(e,t,i,r=Hh){let{child:n,completion:a}=Fh(e,t,i,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",h=>{let v=Math.max(0,r-l);v>0&&o.push(Buffer.from(h).subarray(0,v)),l+=h.byteLength,l>r&&(u=!0)}),n.stderr.on("data",h=>{if(c>=oa)return;let v=oa-c,m=Buffer.from(h).subarray(0,v);s.push(m),c+=m.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${i.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function $h(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Wo(e,t,i,r){if(r.outputChunkBytes!==void 0&&(!Number.isSafeInteger(r.outputChunkBytes)||r.outputChunkBytes<1))throw new Error("Native Git output chunk size must be a positive integer");return new Promise((n,a)=>{let{child:o,completion:s}=Fh(e,t,i,r.stdin!==void 0),c=[],l=Ol("sha256"),u=[],d=0,f=0,h=0,v=0,m=Buffer.alloc(0),p=!1,b=!1,g=!1,y=E=>{let k=0;for(;k<E.byteLength;){let S=E.indexOf(0,k),R=S<0?E.byteLength:S,N=E.subarray(k,R);if(!p&&N.byteLength>0&&(m.byteLength+N.byteLength>r.maxRecordBytes?(m=Buffer.alloc(0),p=!0,b=!0):m=Buffer.concat([m,N])),S<0)break;v+=1,m.byteLength===0&&!p&&(g=!0);let w=m.byteLength+1;!p&&v<=r.maxRecords&&h+w<=r.maxBytes?(c.push(m),h+=w):b=!0,m=Buffer.alloc(0),p=!1,k=S+1}};o.stdout.on("data",E=>{l.update(E),f+=E.byteLength,f>r.maxBytes&&(b=!0);let k=r.outputChunkBytes;if(k===void 0){y(E);return}for(let S=0;S<E.byteLength;S+=k)y(E.subarray(S,Math.min(E.byteLength,S+k)))}),o.stderr.on("data",E=>{if(d>=oa)return;let k=oa-d,S=Buffer.from(E).subarray(0,k);u.push(S),d+=S.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:E,spawnError:k})=>{let S=r.acceptedExitCodes??[0];if(E!==null&&S.includes(E)&&k===null&&!g&&m.byteLength===0&&!p){n({records:c,digest:l.digest("hex"),overflow:b,recordCount:v,stdoutBytes:f});return}a(new Error(`git ${i.join(" ")} failed${k?`: ${k.message}`:g||m.byteLength>0||p?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),r.stdin&&o.stdin?.end(r.stdin)})}function jl(e){let t=e.toString("utf8");if(!Buffer.from(t,"utf8").equals(e))throw new Error("Native Git snapshot provider returned non-UTF-8 path data");return t}async function pj(e,t,i){if(i.length===0)return new Set;let r=await Wo(e,t,["check-ignore","--no-index","-z","--stdin"],{...Mh,maxRecords:Math.max(1,i.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${i.join("\0")}\0`,"utf8")});if(r.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(r.records.map(n=>{let a=jl(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function mj(e,t,i){let{child:r,completion:n}=Fh(e,t,i,!1),a=[],o=0,s=!1;r.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),r.stderr.on("data",u=>{if(o>=oa)return;let d=oa-o,f=Buffer.from(u).subarray(0,d);a.push(f),o+=f.byteLength});let{code:c,spawnError:l}=await n;if(c===0&&l===null)return s;throw new Error(`git ${i.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function aa(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||V.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||V.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function vj(e,t){return e.map(i=>{let r=aa(i);if(r===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return r})}async function gj(e){let t=V.resolve(e);for(;;){try{return await ce.lstat(V.join(t,".git")),!0}catch(r){if(r.code!=="ENOENT")throw r}let i=V.dirname(t);if(i===t)return!1;t=i}}async function kN(e,t,i,r={}){let n=V.resolve(t.projectRoot),a=V.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let h=V.relative(n,V.resolve(f)).replaceAll("\\","/"),v=aa(h);if(v===null)throw new Error("Native Git snapshot exclusion escaped the project root");return v}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...i,...r.outputChunkBytes===void 0?{}:{outputChunkBytes:r.outputChunkBytes}},l=await Wo(e,n,["ls-files","--stage","-z",...s],c);await r.afterStageBefore?.();let u=await Wo(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await r.afterCombined?.();let d=await Wo(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function SN(e){return{stageBefore:$h(e.stagedBefore),combined:$h(e.combined),stageAfter:$h(e.stagedAfter)}}async function EN(e,t,i=Mh,r={}){let n=V.resolve(t.projectRoot);if(!await gj(n))return null;let a;try{a=await Il(e,n,["rev-parse","--is-inside-work-tree"])}catch(g){throw na(g)?g:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:g})}if(a.toString("utf8").trim()!=="true")throw new Error("Native Git snapshot provider found .git metadata outside a working tree");let o;try{o=await kN(e,t,i,r)}catch(g){throw na(g)?g:new Error("Native Git snapshot provider failed after repository detection",{cause:g})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,h=g=>{for(let y of g){let E=jl(y),k=E.indexOf(" ");if(k<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let S=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(E.slice(0,k))?.groups;if(!S)throw new Error("Native Git snapshot provider returned a malformed staged header");let R=aa(E.slice(k+1));if(R===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(R),S.stage==="0"&&d.set(R,S.objectId),S.mode==="160000"&&S.stage==="0"&&f.add(R)}};h(s.records),h(l.records);let v=c.records.map(jl),m=vj(v,"combined"),p=new Set(m.filter(g=>!u.has(g))),b=new Set(m.filter((g,y)=>!u.has(g)&&v[y].endsWith("/")));for(let g of f)b.delete(g);return{tracked:u,trackedObjectIds:d,untracked:p,gitlinks:f,nestedRepositories:b,omissions:[],overflow:null,evidence:null,initialFence:SN(o)}}function kr(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function uN(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function wj(e,t){return!kr(e.stageBefore,e.stageAfter)||!kr(e.stageAfter,t.stageBefore)||!kr(e.combined,t.combined)||!kr(t.stageBefore,t.stageAfter)}async function PN(e,t,i,r,n){let a;try{a=await kN(e,t,i,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw na(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=r.initialFence,s=SN(a),c=uN(o)||uN(s),l=wj(o,s);c&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&r.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),r.evidence=c||l?{schema:"comet.native.git-selection.v1",status:c&&l?"overflow-and-changed":c?"overflow":"changed",...o,finalStageBefore:s.stageBefore,finalCombined:s.combined,finalStageAfter:s.stageAfter}:null,(o.combined.overflow||s.combined.overflow)&&(r.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:L(`comet.native.git-selection-overflow.v2
|
|
183
|
+
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}var yj=(1n<<256n)-1n;function Nj(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function dN(e){let t=V.resolve(e.paths.projectRoot),i=V.resolve(e.paths.nativeRoot),r=V.resolve(e.paths.runtimeDir),n=V.resolve(e.paths.configFile),a=V.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,h=!1,v=!1,m=!1,p=()=>ei(e.execution)>=1?!0:(h=!0,m=!0,!1),b=E=>{let k=Buffer.from(`${E.type}\0${E.path}`,"utf8"),S=Ol("sha256").update("comet.native.physical-selection-record.v1\0").update(k).digest();for(let R=0;R<c.length;R+=1)c[R]^=S[R];if(l=l+BigInt(`0x${S.toString("hex")}`)&yj,d+=1,f+=k.byteLength,Buffer.byteLength(E.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){h=!0,m=!0;return}o.push(E)},g=async E=>{if(m||!p())return;let k;try{k=await ce.opendir(E)}catch(P){if(!p())return;if(!Pe(P)&&!Ee(P)||E===t&&Pe(P))throw P;v||=Ee(P),h||=Pe(P),m=!0;return}if(!p()){try{await k.close()}catch(P){if(P.code!=="ERR_DIR_CLOSED")throw P}return}let S=!1,R;try{for(;!m&&p();){let P;try{P=await k.read()}catch(te){if(!p())break;if(!Pe(te)&&!Ee(te)||E===t&&Pe(te))throw te;v||=Ee(te),h||=Pe(te),m=!0;break}if(!p()||P===null)break;if(u+=1,u>e.limits.maxNodes){h=!0,m=!0;break}let F=V.join(E,P.name),$=kj(t,F);if(F===n||F===a||ti(i,F)||ti(r,F)||e.denylist.some(te=>ti(te,F))||ci($)!==null)continue;if(!p())break;let Fe;try{Fe=await ce.lstat(F)}catch(te){if(!p())break;if(!Pe(te)&&!Ee(te))throw te;if(v=!0,b({path:$,type:"other"}),s.push({path:$,size:null,type:"file",reason:Pe(te)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.($),m||!p())break;continue}if(!p())break;let ue=Nj(Fe);if(ue==="directory"){if(Rj(e.policy,$))continue;if(!p())break;let te;try{te=await ce.realpath(F)}catch(ai){if(!p())break;if(!Pe(ai)&&!Ee(ai))throw ai;if(v=!0,b({path:$,type:ue}),s.push({path:$,size:null,type:"directory",reason:Pe(ai)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.($),m||!p())break;continue}if(!p())break;if(!O(e.physicalProjectRoot,te)||ti(e.physicalNativeRoot,te))continue;if(b({path:$,type:ue}),await e.hooks?.afterNode?.($),!p()||(await g(F),m))break;continue}if(b({path:$,type:ue}),await e.hooks?.afterNode?.($),!p()||m)break}}catch(P){S=!0,R=P}let N;try{await k.close()}catch(P){N=P}let w=p();if(S)throw R;if(w&&N!==void 0&&N.code!=="ERR_DIR_CLOSED")throw N};await g(t),p(),h?(o.length=0,d=0,f=0):(o.sort((E,k)=>E.path.localeCompare(k.path,"en")),s.sort((E,k)=>E.path.localeCompare(k.path,"en")));let y=h?L(`comet.native.physical-selection-incomplete.v1
|
|
184
|
+
${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):L(`comet.native.physical-selection.v1
|
|
185
|
+
${JSON.stringify({visitedNodeCount:u,recordCount:d,encodedBytes:f,xor:c.toString("hex"),sum:l.toString(16).padStart(64,"0")})}`);return{records:o,omissions:s,evidence:{hash:y,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:h,unstable:v}}}function RN(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function bj(e,t){let i=e.overflow||t.overflow,r=e.unstable||t.unstable||!RN(e,t),n=[];return i&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),r&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:i||r?{schema:"comet.native.physical-selection.v1",status:i&&r?"overflow-and-changed":i?"overflow":"changed",before:e,after:t}:null}}function CN(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,i)=>t.localeCompare(i,"en"))}async function fN(e,t){let r=(await Il(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!yN.test(r))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return L(`gitlink:${r}`)}async function hN(e,t){let i=await fN(e,t),r=await mj(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await fN(e,t);if(n!==i)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:r}}function qo(e,t){if(ci(t)!==null)return!1;let i=V.resolve(e.projectRoot,...t.split("/"));return!ti(V.resolve(e.nativeRoot),i)&&!ti(V.resolve(e.runtimeDir),i)}function Bh(e,t={}){let i=Ii(e),r=t.maxRecordedPaths??20;if(!Number.isSafeInteger(r)||r<0)throw new Error("Native snapshot health maxRecordedPaths must be a non-negative integer");let n=i.omitted.slice(0,r).map(a=>a.path);return{complete:i.complete,omittedCount:i.omittedCount,recordedOmissionCount:i.omitted.length,overflowCount:i.omissionOverflow?.count??0,samplePaths:n,sampleTruncated:n.length<i.omittedCount}}function kj(e,t){return V.relative(e,t).split(V.sep).join("/")}function Sj(e,t){return t.map(i=>V.resolve(e,...i.split(/[\\/]/u)))}function ti(e,t){let i=V.resolve(e),r=V.resolve(t);return r===i||O(i,r)}function Pe(e){return sj.has(e.code??"")}function Ee(e){return e.code==="ENOENT"}function Vh(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
186
|
+
`)}function Ej(e,t){return L(`comet.native.snapshot-policy.v1
|
|
187
|
+
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Oh(e,t,i){let r=new Set(t),n=[...t];for(;n.length>0;){if(i&&!i())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!r.has(a+1)&&(r.add(a+1),n.push(a+1))}return r}function Pj(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function pN(e){let t=ol(e,"Native snapshot pattern"),i=[];for(let r=0;r<t.length;r+=1){let n=t[r];n==="*"&&t[r+1]==="*"?(r+=1,t[r+1]==="/"?(r+=1,i.push({kind:"globstar-slash"})):i.push({kind:"globstar"})):n==="*"?i.push({kind:"star"}):n==="?"?i.push({kind:"question"}):i.push({kind:"literal",value:n})}return(r,n)=>{let a=n?Pj(n):void 0;if(a&&!a())return!1;let o=Oh(i,new Set([0]),a);if(o===null)return!1;for(let s of r){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=i[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=Oh(i,c,a),o===null||o.size===0)return!1}return Oh(i,o,a)?.has(i.length)??!1}}function xN(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>ol(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),i=[...new Set(e.exclude.map(n=>ol(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let r=Ej(t,i);if("hash"in e&&e.hash!==r)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:i,hash:r},includeMatchers:t.map(pN),excludeMatchers:i.map(pN),excludedDirectoryPrefixes:i.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function Rj(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function mN(e,t,i){if(!e)return!0;let r=()=>M(i),n=!1;for(let a of e.includeMatchers){if(!r())return!1;if(a(t,r)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!r()||a(t,r))return!1;return!0}function zo(e,t,i){let r=JSON.stringify(i);return L(`${e}
|
|
188
188
|
${Buffer.byteLength(t)}:${t}
|
|
189
|
-
${Buffer.byteLength(r)}:${r}`)}function Oh(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function _l(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!Oh(i))return e.splice(t,1),i}return null}function yr(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return mt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function lj(e,t,i,r){if(!L(r))return{status:"budget-exhausted"};let n;try{n=await se.open(e,"r")}catch(c){if(!L(r))return{status:"budget-exhausted"};throw c}if(!L(r))return await n.close(),{status:"budget-exhausted"};let a=Tl("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!L(r))return{status:"budget-exhausted"};let c=await n.stat();if(!L(r))return{status:"budget-exhausted"};if(!c.isFile()||!yr(i,c))return{status:"changed"};for(;;){if(!L(r))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!L(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!L(r))return{status:"budget-exhausted"};let d=await n.stat();return L(r)?!d.isFile()||!yr(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function Tt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function It(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function ta(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function hi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function EN(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=V.posix.normalize(e);if(i!==e||V.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function uj(e,t){let i=Tt(e,`Native snapshot entry ${t}`);It(i,DI,`Native snapshot entry ${t}`);let r=EN(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!Il.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:r,hash:i.hash,size:hi(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!pN.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function dj(e,t){let i=Tt(e,`Native snapshot omission ${t}`);if(It(i,MI,`Native snapshot omission ${t}`),!BI.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!VI.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:EN(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:hi(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function fj(e){let t=Tt(e,"Native snapshot omission overflow");if(It(t,LI,"Native snapshot omission overflow"),typeof t.hash!="string"||!Il.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:ta(t.count,"Native snapshot omission overflow count")}}function ea(e,t){let i=Tt(e,t);if(It(i,$I,t),typeof i.hash!="string"||!Il.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let r=hi(i.recordCount,`${t} recordCount`),n=hi(i.storedRecordCount,`${t} storedRecordCount`),a=hi(i.stdoutBytes,`${t} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function dN(e){let t=Tt(e,"Native Git selection evidence");if(It(t,jI,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=ea(t.stageBefore,"Native Git selection stageBefore"),r=ea(t.combined,"Native Git selection combined"),n=ea(t.stageAfter,"Native Git selection stageAfter"),a=ea(t.finalStageBefore,"Native Git selection finalStageBefore"),o=ea(t.finalCombined,"Native Git selection finalCombined"),s=ea(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!Nr(i,n)||!Nr(n,a)||!Nr(r,o)||!Nr(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function fN(e,t){let i=Tt(e,t);if(It(i,HI,t),typeof i.hash!="string"||!Il.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let r=hi(i.visitedNodeCount,`${t} visitedNodeCount`),n=hi(i.recordCount,`${t} recordCount`),a=hi(i.storedRecordCount,`${t} storedRecordCount`),o=hi(i.encodedBytes,`${t} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function hj(e){let t=Tt(e,"Native physical selection evidence");if(It(t,OI,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=fN(t.before,"Native physical selection before"),r=fN(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!bN(i,r);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:r}}function Ti(e){let t=Tt(e,"Native content snapshot manifest");if(It(t,xI,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!FI.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let S=Tt(t.capture,"Native content snapshot capture");if(It(S,TI,"Native content snapshot capture"),S.provider!=="git"&&S.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=S.gitSelection===void 0?void 0:dN(S.gitSelection),N=S.physicalSelection===void 0?void 0:hj(S.physicalSelection),w=null;if(S.projection!==void 0){let P=Tt(S.projection,"Native content snapshot projection");if(It(P,II,"Native content snapshot projection"),P.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");w={provider:"git",...P.selection===void 0?{}:{selection:dN(P.selection)}}}if(S.provider==="git"){if(N||w)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(N&&w)throw new Error("Native physical-tree capture cannot combine selection and projection");i=w?{provider:"physical-tree",projection:w}:{provider:"physical-tree",...N?{physicalSelection:N}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=Tt(t.limits,"Native content snapshot limits");It(r,AI,"Native content snapshot limits");let n={maxFiles:ta(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:ta(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:ta(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:ta(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:ta(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let S=Tt(t.policy,"Native snapshot policy");if(It(S,_I,"Native snapshot policy"),S.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(S.include)||!Array.isArray(S.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=SN({include:S.include,exclude:S.exclude,hash:S.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(uj),s=t.omitted.map(dj),c=hi(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:fj(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(S=>S.size>n.maxFileBytes)||o.reduce((S,R)=>S+R.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(S=>S.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Hh||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(S=>S.reason==="git-enumeration-limit"),f=s.filter(S=>S.reason==="git-selection-changed");for(let S of[...d,...f])if(S.path!=="."||S.size!==null||S.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=i?.provider==="git"?i.gitSelection:i?.projection?.selection,v=h?.status==="overflow"||h?.status==="overflow-and-changed",m=h?.status==="changed"||h?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(m!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let p=s.filter(S=>S.reason==="physical-enumeration-limit"),b=s.filter(S=>S.reason==="physical-selection-changed");for(let S of[...p,...b])if(S.path!=="."||S.size!==null||S.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(p.length>1||b.length>1)throw new Error("Native physical selection omissions must not be duplicated");let g=i?.physicalSelection,y=g?.status==="overflow"||g?.status==="overflow-and-changed",E=g?.status==="changed"||g?.status==="overflow-and-changed";if(y!==(p.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(E!==(b.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let k={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Fh(k)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return k}async function jl(e,t,i={}){let r=Ti(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=V.resolve(e.projectRoot),a=mN(i),o=vN(i.gitSelectionLimits),s=await yN(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(kN(s).filter(N=>Bo(e,N))),l=[...s.gitlinks].filter(N=>c.has(N)),u=[...s.nestedRepositories].filter(N=>Bo(e,N)),d=(N,w)=>w.some(P=>N===P||N.startsWith(`${P}/`)),f=N=>d(N,l),h=N=>d(N,u),v=[...r.entries.map(N=>N.path),...r.omitted.flatMap(N=>N.type==="directory"?[N.path,`${N.path}/`]:[N.path])].filter(N=>!c.has(N)&&!f(N)&&!h(N)),m=await YI(a,n,v),p=r.entries.filter(N=>!f(N.path)&&!h(N.path)&&Bo(e,N.path)&&(c.has(N.path)||!m.has(N.path)));await NN(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let b=[...s.omissions];for(let N of l)b.push({path:N,size:null,type:"directory",reason:"legacy-gitlink-boundary"});p.sort((N,w)=>N.path.localeCompare(w.path,"en"));let g=r.omitted.filter(N=>f(N.path)||h(N.path)||!Bo(e,N.path)?!1:m.has(N.path)?c.has(N.path)||[...c].some(w=>w.startsWith(`${N.path}/`)):!0);for(let N of b)g.some(w=>w.path===N.path&&w.reason===N.reason)||g.push(N);g.sort((N,w)=>N.path.localeCompare(w.path,"en"));let y=r.omissionOverflow?.count??0,E=r.omissionOverflow?.hash??M("comet.native.snapshot-omission-overflow.v1");s.overflow&&(y+=s.overflow.count,E=qo(E,"git-selection",{source:"git-selection",...s.overflow}));let k=N=>{y+=1,E=qo(E,"omission",N)};for(;g.length>Hh;){let N=_l(g);if(N===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");k(N)}let S=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:g.length+y===0,entries:p,omitted:g,omittedCount:g.length+y,...y>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${E}`,hash:E,count:y}}:{}}),R=S();for(;Fh(R)>r.limits.maxManifestBytes;){let N=_l(g);if(N===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");k(N),R=S()}return Ti(R)}function PN(e,t){if(!CI.test(t))throw new Error(`Invalid Native change name: ${t}`);return V.join(H(e,t),"baseline-manifest.json")}async function $l(e,t={}){let i={maxFiles:t.limits?.maxFiles??Cl.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Cl.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Cl.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Cl.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=SN(t.policy),n=mN({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=vN(t.gitSelectionLimits),o=UI(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=V.resolve(e.projectRoot),c=await se.realpath(s),l=V.resolve(e.nativeRoot),u=await se.realpath(l),d=V.resolve(e.runtimeDir),f=V.resolve(e.configFile),h=V.join(s,".comet","current-change.json"),v=aj(s,t.denylist??[]),m=[],p=[],b=new Map,g=new Map,y=0,E=0,k=M("comet.native.snapshot-omission-overflow.v1"),S=0,R=!1,N=null,w=_=>{E+=1,k=qo(k,"omission",_)},P=_=>{if(y+=1,p.length<Hh){p.push(_);return}if(Oh(_)){let A=_l(p);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");w(A),p.push(_);return}w(_)},F=_=>{y+=_.count,E+=_.count,k=qo(k,"git-selection",{source:"git-selection",..._})},$=_=>{E+=1,k=qo(k,"manifest-entry",{reason:"manifest-size",entry:_})},Le=async(_,A)=>{m.push(_),S+=_.size,b.set(_.path,A),R||(R=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},le=(_,A)=>{let I=m.findIndex(ae=>ae.path===_);if(I<0)return;let[q]=m.splice(I,1);S-=q.size,b.delete(_),P(A)},ee=async(_,A,I,q)=>{if(!I.isFile()||I.isSymbolicLink()||!L(n))return;let ae;try{ae=await se.realpath(_)}catch(x){if(!L(n))return;if(!Se(x)&&!ke(x))throw x;P({path:A,size:I.size,type:"file",reason:ke(x)?"changed-during-read":"unreadable"});return}if(!L(n)||!O(c,ae)||ei(u,ae))return;if(m.length>=i.maxFiles){P({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){P({path:A,size:I.size,type:"file",reason:"file-size"});return}if(S+I.size>i.maxTotalBytes){P({path:A,size:I.size,type:"file",reason:"total-size"});return}let G,B,me;try{if(G=await lj(ae,I.size,I,n),G.status==="budget-exhausted"||!L(n))return;if(G.status==="changed"){P({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!L(n)||(me=await se.realpath(_),!L(n)))return;B=await se.lstat(_)}catch(x){if(!L(n))return;if(!Se(x)&&!ke(x))throw x;P({path:A,size:I.size,type:"file",reason:ke(x)?"changed-during-read":"unreadable"});return}if(L(n)){if(G.bytes!==I.size||me!==ae||!yr(I,G.finalStat)||!yr(G.finalStat,B)||!B.isFile()||B.isSymbolicLink()||B.size!==I.size||B.mtimeMs!==I.mtimeMs||B.ctimeMs!==I.ctimeMs){P({path:A,size:B.isFile()?B.size:null,type:B.isFile()?"file":"other",reason:"changed-during-read"});return}L(n)&&await Le({path:A,hash:G.hash,size:B.size,type:"file",...q===void 0?{}:{gitObjectId:q}},{kind:"file",target:_,realTarget:ae,stat:B})}},ni=async(_,A,I)=>{if(!L(n))return;let q,ae,G;try{if(q=await se.readlink(_,{encoding:"buffer"}),!L(n)||(G=await se.lstat(_),!L(n)))return;ae=await se.readlink(_,{encoding:"buffer"})}catch(x){if(!L(n))return;if(!Se(x)&&!ke(x))throw x;P({path:A,size:null,type:"other",reason:ke(x)?"changed-during-read":"unreadable"});return}if(!L(n))return;if(!G.isSymbolicLink()||!yr(I,G)||G.mtimeMs!==I.mtimeMs||G.ctimeMs!==I.ctimeMs||!q.equals(ae)){P({path:A,size:null,type:"other",reason:"changed-during-read"});return}let B=q.byteLength;if(m.length>=i.maxFiles){P({path:A,size:B,type:"other",reason:"file-count"});return}if(B>i.maxFileBytes){P({path:A,size:B,type:"other",reason:"file-size"});return}if(S+B>i.maxTotalBytes){P({path:A,size:B,type:"other",reason:"total-size"});return}let me=Tl("sha256").update("symlink\0").update(q).digest("hex");L(n)&&await Le({path:A,hash:me,size:B,type:"file"},{kind:"symlink",target:_,rawTarget:q,stat:G})},Bt=async()=>{for(let[_,A]of[...b]){if(!L(n))return;if(A.kind==="file"){let B,me;try{if(B=await se.realpath(A.target),!L(n))return;me=await se.lstat(A.target)}catch(x){if(!L(n))return;if(!Se(x)&&!ke(x))throw x;le(_,{path:_,size:null,type:"file",reason:Se(x)?"unreadable":"changed-during-read"});continue}if(!L(n))return;(B!==A.realTarget||!me.isFile()||me.isSymbolicLink()||!yr(A.stat,me)||me.size!==A.stat.size||me.mtimeMs!==A.stat.mtimeMs||me.ctimeMs!==A.stat.ctimeMs)&&le(_,{path:_,size:me.isFile()?me.size:null,type:me.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let B,me;try{if(B=await se.lstat(A.target),!L(n))return;me=await se.readlink(A.target,{encoding:"buffer"})}catch(x){if(!L(n))return;if(!Se(x)&&!ke(x))throw x;le(_,{path:_,size:null,type:"other",reason:Se(x)?"unreadable":"changed-during-read"});continue}if(!L(n))return;(!B.isSymbolicLink()||!yr(A.stat,B)||B.mtimeMs!==A.stat.mtimeMs||B.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(me))&&le(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,q;try{if(I=await se.realpath(A.target),!L(n))return;q=await se.lstat(A.target)}catch{if(!L(n))return;le(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!L(n))return;if(!(I===A.realTarget&&q.isDirectory()&&!q.isSymbolicLink()&&yr(A.stat,q)&&O(c,I)&&!ei(u,I))){le(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let G;try{if(!L(n))return;G=await cN(n,I)}catch(B){if(ia(B))throw B;le(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!L(n))return;G.dirty?le(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):G.hash!==A.hash&&le(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of g){if(!L(n))return;try{let I=await se.lstat(A);if(!L(n))return;P({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!L(n))return;if(ke(I))continue;if(!Se(I))throw I;P({path:_,size:null,type:"file",reason:"unreadable"})}}},ht=await yN(n,e,a,t.gitSelectionHooks);if(ht===null){let _=await oN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let q of _.records){if(q.type!=="file"&&q.type!=="symlink"||b.has(q.path))continue;if(Zt(n)<1)break;if(!uN(r,q.path,n))continue;if(Zt(n)<1)break;let ae=V.resolve(s,...q.path.split("/")),G;try{G=await se.lstat(ae)}catch(B){if(!L(n))break;if(!Se(B)&&!ke(B))throw B;P({path:q.path,size:null,type:"file",reason:ke(B)?"changed-during-read":"unreadable"});continue}if(Zt(n)<1)break;if(q.type==="symlink"&&G.isSymbolicLink()){if(await ni(ae,q.path,G),Zt(n)<1)break;continue}if(q.type!=="file"||!G.isFile()||G.isSymbolicLink()){P({path:q.path,size:G.isFile()?G.size:null,type:G.isDirectory()?"directory":G.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await ee(ae,q.path,G),Zt(n)<1)break}Zt(n)>=1&&await Bt();let A=await oN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),I=rj(_.evidence,A.evidence);N=I.evidence;for(let q of[..._.omissions,...A.omissions,...I.omissions])p.some(ae=>ae.path===q.path&&ae.reason===q.reason)||P(q)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let x=Ti(_);for(let ue of x.entries)ue.gitObjectId!==void 0&&A.set(ue.path,ue);I=A.size>0}let q=new Set,ae=!0;try{let x=await Vo(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(x.overflow)I=!1,ae=!1,A.clear();else for(let ue of x.records){let ve=Al(ue),Ke=ve.indexOf(" "),Fe=Ke<0?null:ra(ve.slice(Ke+1));if(Ke!==1||Fe===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ve[0]!=="H"&&q.add(Fe)}}catch(x){if(ia(x))throw x;I=!1,ae=!1,A.clear()}let G=new Set;try{let x=await xl(n,s,["ls-files","--modified","-z"],$h);for(let ue of x.toString("utf8").split("\0")){let ve=ra(ue);ve!==null&&G.add(ve)}}catch{I=!1,ae=!1,A.clear()}let B=new Set,me=new Set;for(let x of kN(ht)){if(b.has(x)||!Bo(e,x))continue;if(Zt(n)<1)break;if(!uN(r,x,n))continue;if(Zt(n)<1)break;let ue=V.resolve(s,...x.split("/"));if(ue===f||ue===h||ei(d,ue)||v.some(pt=>ei(pt,ue)))continue;if(ht.gitlinks.has(x)){if(m.length>=i.maxFiles){P({path:x,size:0,type:"file",reason:"file-count"});continue}let pt,Bs;try{[pt,Bs]=await Promise.all([se.realpath(ue),se.lstat(ue)])}catch{P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Bs.isSymbolicLink()||!Bs.isDirectory()||!O(c,pt)||ei(u,pt)){P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Sn=await cN(n,pt);if(Sn.dirty){P({path:x,size:null,type:"directory",reason:"gitlink-dirty"});continue}await Le({path:x,hash:Sn.hash,size:0,type:"file"},{kind:"gitlink",target:ue,realTarget:pt,stat:Bs,hash:Sn.hash})}catch(Sn){if(ia(Sn))throw Sn;P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ve;try{ve=await se.lstat(ue)}catch(pt){if(ke(pt)&&ht.tracked.has(x)){g.set(x,ue);continue}if(!Se(pt)&&!ke(pt))throw pt;P({path:x,size:null,type:"file",reason:ke(pt)?"changed-during-read":"unreadable"});continue}if(ve.isSymbolicLink()){await ni(ue,x,ve);continue}if(!ve.isFile()){ht.nestedRepositories.has(x)||P({path:x,size:null,type:"other",reason:"changed-during-read"});continue}let Ke=ht.trackedObjectIds.get(x),Fe=Ke?A.get(x):void 0;if(I&&Fe?.gitObjectId!==void 0&&Fe.gitObjectId===Ke&&!q.has(x)&&!G.has(x)){if(m.length>=i.maxFiles){P({path:x,size:Fe.size,type:"file",reason:"file-count"});continue}if(Fe.size>i.maxFileBytes){P({path:x,size:Fe.size,type:"file",reason:"file-size"});continue}if(S+Fe.size>i.maxTotalBytes){P({path:x,size:Fe.size,type:"file",reason:"total-size"});continue}m.push({...Fe}),S+=Fe.size,B.add(x);continue}let Mm=ae&&!q.has(x)&&!G.has(x)?Ke:void 0;await ee(ue,x,ve,Mm),Mm!==void 0&&me.add(x)}if(await Bt(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await NN(n,e,a,ht,t.gitSelectionHooks?.outputChunkBytes),B.size>0||I&&me.size>0){let x=await xl(n,s,["ls-files","--modified","-z"],$h),ue=new Set;for(let ve of x.toString("utf8").split("\0")){let Ke=ra(ve);Ke!==null&&ue.add(Ke)}for(let ve of B){if(!ue.has(ve))continue;let Ke=m.find(Fe=>Fe.path===ve);le(ve,{path:ve,size:Ke?.size??null,type:"file",reason:"changed-during-read"})}for(let ve of me){if(!ue.has(ve))continue;let Ke=m.find(Fe=>Fe.path===ve);Ke&&delete Ke.gitObjectId}}for(let x of ht.omissions)P(x);ht.overflow&&F(ht.overflow)}m.sort((_,A)=>_.path.localeCompare(A.path,"en")),p.sort((_,A)=>_.path.localeCompare(A.path,"en"));let UE=ht===null?{provider:"physical-tree",...N?{physicalSelection:N}:{}}:{provider:"git",...ht.evidence?{gitSelection:ht.evidence}:{}},Dm=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:UE,createdAt:(t.now??new Date).toISOString(),complete:y===0,limits:i,...r?{policy:r.manifest}:{},entries:m,omitted:p,omittedCount:y,...E>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:E}}:{}}),ad=Dm();for(;Fh(ad)>i.maxManifestBytes;){if(p.filter(A=>!Oh(A)).length>0){let A=Math.max(1,Math.ceil(p.length/4));for(let I=0;I<A;I+=1){let q=_l(p);if(q===null)break;w(q)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let I of m.splice(-A))y+=1,$(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");ad=Dm()}return ad}async function Bh(e,t,i={}){let n=(await we(e.projectRoot))?.native.snapshot??sh;return $l(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function Vh(e,t,i){let r=PN(e,t);await T(j(e,r),r),await Z(r,Ti(i))}async function aa(e,t){let i=PN(e,t),r=j(e,i);await T(r,i);try{let n=await yl({root:r,file:i,maxBytes:RI,label:"Native baseline snapshot manifest"});return Ti(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as jj}from"crypto";import $j from"path";var yt=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{createHash as Cj}from"node:crypto";import{constants as Hl,promises as et}from"node:fs";import Nt from"node:path";import{TextDecoder as xj}from"node:util";import Sj from"path";var yj=En(Yr(),1);var gq=4*1024*1024;var Nj=null;function bj(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function RN(e,t){return(...i)=>{let r=Nj;if(r===null)return t(...i);let n=bj(`async:${e}`,i),a=r.entries.get(n);if(a)return a.value;let o=t(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var kq=RN("hookWritePolicy",async e=>(await ih(e))?.hook??{allow_paths:[]});var CN=(e,t)=>{let i=e[t];return i==null?null:String(i)};function zo(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function Wo(e,t){let i=zo(e,t);if(Sj.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function Ej(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function xN(e){if(!e.run_id)return null;let t=zo(e,"run_id"),i=zo(e,"skill"),r=zo(e,"skill_version"),n=zo(e,"skill_hash"),a=Wo(e,"pending_ref"),o=Wo(e,"trajectory_ref"),s=Wo(e,"context_ref"),c=Wo(e,"artifacts_ref"),l=Wo(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<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:i,skillVersion:r,skillHash:n,orchestration:e.orchestration,currentStep:CN(e,"current_step"),iteration:u,pending:CN(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:Ej(e)}}var vW=256*1024;var Pj=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function Rj(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)},i=xN(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function Ol(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(r=>!Pj.has(r));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return Rj(t)}var ze={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function Go(e,t){let i=Nt.relative(e,t);return i===""||!Nt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${Nt.sep}`)}function _N(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Jo(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function Aj(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function br(e,t,i){let r=yt[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=Nt.resolve(e),a=Nt.resolve(n,...r.slice(8).split("/"));if(!Go(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function AN(e){let t=await et.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await et.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function qh(e,t){let i=Nt.resolve(e),r=Nt.resolve(t);if(!Go(i,r))throw new Error("Native Run path is outside its change");let n=[await AN(i)],a=i;for(let o of Nt.relative(i,r).split(Nt.sep).filter(Boolean)){a=Nt.join(a,o);let s;try{s=await AN(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Go(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function Dl(e){for(let t of e){let i=await et.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Aj(t,i)||await et.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function _j(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function sn(e,t,i,r,n){let a=await qh(e,Nt.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await et.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${r} must be a regular file`);if(o.size>i)throw new Error(`${r} exceeds ${i} bytes`);let s=_N(o),c=await et.realpath(t);if(!Go(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?Hl.O_RDONLY:Hl.O_RDONLY|Hl.O_NOFOLLOW|Hl.O_NONBLOCK,u;try{u=await et.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,h]=await Promise.all([u.stat(),et.lstat(t),et.realpath(t)]);if(await Dl(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||h!==c||!Jo(s,d)||!Jo(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await _j(u,i,r);await n?.beforeFinalCheck?.();let[m,p,b]=await Promise.all([u.stat(),et.lstat(t),et.realpath(t)]);if(await Dl(a),!p.isFile()||p.isSymbolicLink()||b!==c||!Jo(s,m)||!Jo(s,p))throw new Error(`${r} changed while reading`);let g;try{g=new xj("utf-8",{fatal:!0}).decode(v)}catch(y){throw new Error(`${r} is not valid UTF-8`,{cause:y})}return{text:g,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function Tj(e,t,i){let r=await qh(e,Nt.dirname(t));if(!r)return{exists:!1};let n;try{n=await et.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!n.isFile()||n.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await et.realpath(t);if(!Go(r[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await Dl(r),{exists:!0,identity:_N(n),realPath:a}}async function Ij(e,t,i,r){let n=await qh(e,Nt.dirname(t));if(!n){if(!i.exists)return;throw new Error(`${r} parent changed before commit`)}let a;try{a=await et.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${r} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!Jo(i.identity,a)||await et.realpath(t)!==i.realPath)throw new Error(`${r} changed before commit`);await Dl(n)}async function Ml(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await Tj(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await fe(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await Ij(e.changeDir,e.file,i,e.label)}});let r=await sn(e.changeDir,e.file,e.maxBytes,e.label);if(!r||r.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function TN(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function IN(e){return`${JSON.stringify(e,null,2)}
|
|
190
|
-
`}function
|
|
191
|
-
`;if(Buffer.byteLength(a,"utf8")>
|
|
192
|
-
`)])}catch(d){if(!
|
|
193
|
-
${t}`).digest("hex")}async function
|
|
189
|
+
${Buffer.byteLength(r)}:${r}`)}function Dh(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function $l(e){for(let t=e.length-1;t>=0;t-=1){let i=e[t];if(!Dh(i))return e.splice(t,1),i}return null}function br(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Cj(e,t,i,r){if(!M(r))return{status:"budget-exhausted"};let n;try{n=await ce.open(e,"r")}catch(c){if(!M(r))return{status:"budget-exhausted"};throw c}if(!M(r))return await n.close(),{status:"budget-exhausted"};let a=Ol("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!M(r))return{status:"budget-exhausted"};let c=await n.stat();if(!M(r))return{status:"budget-exhausted"};if(!c.isFile()||!br(i,c))return{status:"changed"};for(;;){if(!M(r))return{status:"budget-exhausted"};let l=t+1-s;if(l<1)return{status:"changed"};let u=await n.read(o,0,Math.min(o.length,l),null);if(!M(r))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!M(r))return{status:"budget-exhausted"};let d=await n.stat();return M(r)?!d.isFile()||!br(c,d)?{status:"changed"}:{status:"complete",hash:a.digest("hex"),bytes:s,finalStat:d}:{status:"budget-exhausted"}}if(s+u.bytesRead>t)return{status:"changed"};a.update(o.subarray(0,u.bytesRead)),s+=u.bytesRead}}finally{await n.close()}}function It(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function jt(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function ra(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function pi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function AN(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let i=V.posix.normalize(e);if(i!==e||V.posix.isAbsolute(e)||i===".."||i.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function xj(e,t){let i=It(e,`Native snapshot entry ${t}`);jt(i,tj,`Native snapshot entry ${t}`);let r=AN(i.path,`Native snapshot entry ${t} path`);if(typeof i.hash!="string"||!Hl.test(i.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(i.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:r,hash:i.hash,size:pi(i.size,`Native snapshot entry ${t} size`),type:"file"};if(i.gitObjectId!==void 0){if(typeof i.gitObjectId!="string"||!yN.test(i.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=i.gitObjectId}return n}function Aj(e,t){let i=It(e,`Native snapshot omission ${t}`);if(jt(i,ij,`Native snapshot omission ${t}`),!aj.has(i.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!oj.has(i.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:AN(i.path,`Native snapshot omission ${t} path`),size:i.size===null?null:pi(i.size,`Native snapshot omission ${t} size`),type:i.type,reason:i.reason}}function _j(e){let t=It(e,"Native snapshot omission overflow");if(jt(t,rj,"Native snapshot omission overflow"),typeof t.hash!="string"||!Hl.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let i=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==i)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:i,hash:t.hash,count:ra(t.count,"Native snapshot omission overflow count")}}function ia(e,t){let i=It(e,t);if(jt(i,QI,t),typeof i.hash!="string"||!Hl.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let r=pi(i.recordCount,`${t} recordCount`),n=pi(i.storedRecordCount,`${t} storedRecordCount`),a=pi(i.stdoutBytes,`${t} stdoutBytes`);if(n>r||!i.overflow&&n!==r)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,recordCount:r,storedRecordCount:n,stdoutBytes:a,overflow:i.overflow}}function vN(e){let t=It(e,"Native Git selection evidence");if(jt(t,XI,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let i=ia(t.stageBefore,"Native Git selection stageBefore"),r=ia(t.combined,"Native Git selection combined"),n=ia(t.stageAfter,"Native Git selection stageAfter"),a=ia(t.finalStageBefore,"Native Git selection finalStageBefore"),o=ia(t.finalCombined,"Native Git selection finalCombined"),s=ia(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[i,r,n,a,o,s].some(d=>d.overflow),l=!kr(i,n)||!kr(n,a)||!kr(r,o)||!kr(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:i,combined:r,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function gN(e,t){let i=It(e,t);if(jt(i,ej,t),typeof i.hash!="string"||!Hl.test(i.hash))throw new Error(`${t} hash is invalid`);if(typeof i.overflow!="boolean"||typeof i.unstable!="boolean")throw new Error(`${t} flags are invalid`);let r=pi(i.visitedNodeCount,`${t} visitedNodeCount`),n=pi(i.recordCount,`${t} recordCount`),a=pi(i.storedRecordCount,`${t} storedRecordCount`),o=pi(i.encodedBytes,`${t} encodedBytes`);if(a>n||!i.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:i.hash,visitedNodeCount:r,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:i.overflow,unstable:i.unstable}}function Tj(e){let t=It(e,"Native physical selection evidence");if(jt(t,ZI,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let i=gN(t.before,"Native physical selection before"),r=gN(t.after,"Native physical selection after"),n=i.overflow||r.overflow,a=i.unstable||r.unstable||!RN(i,r);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:i,after:r}}function Ii(e){let t=It(e,"Native content snapshot manifest");if(jt(t,JI,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!nj.has(t.origin))throw new Error("Native content snapshot origin is invalid");let i;if(t.capture!==void 0){let S=It(t.capture,"Native content snapshot capture");if(jt(S,KI,"Native content snapshot capture"),S.provider!=="git"&&S.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=S.gitSelection===void 0?void 0:vN(S.gitSelection),N=S.physicalSelection===void 0?void 0:Tj(S.physicalSelection),w=null;if(S.projection!==void 0){let P=It(S.projection,"Native content snapshot projection");if(jt(P,YI,"Native content snapshot projection"),P.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");w={provider:"git",...P.selection===void 0?{}:{selection:vN(P.selection)}}}if(S.provider==="git"){if(N||w)throw new Error("Native Git capture cannot include physical or projection evidence");i={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(N&&w)throw new Error("Native physical-tree capture cannot combine selection and projection");i=w?{provider:"physical-tree",projection:w}:{provider:"physical-tree",...N?{physicalSelection:N}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let r=It(t.limits,"Native content snapshot limits");jt(r,GI,"Native content snapshot limits");let n={maxFiles:ra(r.maxFiles,"Native snapshot maxFiles"),maxFileBytes:ra(r.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:ra(r.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:ra(r.maxManifestBytes,"Native snapshot maxManifestBytes"),...r.maxDurationMs===void 0?{}:{maxDurationMs:ra(r.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let S=It(t.policy,"Native snapshot policy");if(jt(S,UI,"Native snapshot policy"),S.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(S.include)||!Array.isArray(S.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=xN({include:S.include,exclude:S.exclude,hash:S.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(xj),s=t.omitted.map(Aj),c=pi(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:_j(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(S=>S.size>n.maxFileBytes)||o.reduce((S,R)=>S+R.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(S=>S.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Lh||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(S=>S.reason==="git-enumeration-limit"),f=s.filter(S=>S.reason==="git-selection-changed");for(let S of[...d,...f])if(S.path!=="."||S.size!==null||S.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=i?.provider==="git"?i.gitSelection:i?.projection?.selection,v=h?.status==="overflow"||h?.status==="overflow-and-changed",m=h?.status==="changed"||h?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(m!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let p=s.filter(S=>S.reason==="physical-enumeration-limit"),b=s.filter(S=>S.reason==="physical-selection-changed");for(let S of[...p,...b])if(S.path!=="."||S.size!==null||S.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(p.length>1||b.length>1)throw new Error("Native physical selection omissions must not be duplicated");let g=i?.physicalSelection,y=g?.status==="overflow"||g?.status==="overflow-and-changed",E=g?.status==="changed"||g?.status==="overflow-and-changed";if(y!==(p.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(E!==(b.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let k={schema:"comet.native.content-snapshot.v1",origin:t.origin,...i?{capture:i}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Vh(k)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return k}async function Dl(e,t,i={}){let r=Ii(t);if(r.capture?.provider==="git"||r.capture?.projection||r.capture?.physicalSelection)return r;let n=V.resolve(e.projectRoot),a=NN(i),o=bN(i.gitSelectionLimits),s=await EN(a,e,o,i.gitSelectionHooks);if(s===null)return r;let c=new Set(CN(s).filter(N=>qo(e,N))),l=[...s.gitlinks].filter(N=>c.has(N)),u=[...s.nestedRepositories].filter(N=>qo(e,N)),d=(N,w)=>w.some(P=>N===P||N.startsWith(`${P}/`)),f=N=>d(N,l),h=N=>d(N,u),v=[...r.entries.map(N=>N.path),...r.omitted.flatMap(N=>N.type==="directory"?[N.path,`${N.path}/`]:[N.path])].filter(N=>!c.has(N)&&!f(N)&&!h(N)),m=await pj(a,n,v),p=r.entries.filter(N=>!f(N.path)&&!h(N.path)&&qo(e,N.path)&&(c.has(N.path)||!m.has(N.path)));await PN(a,e,o,s,i.gitSelectionHooks?.outputChunkBytes);let b=[...s.omissions];for(let N of l)b.push({path:N,size:null,type:"directory",reason:"legacy-gitlink-boundary"});p.sort((N,w)=>N.path.localeCompare(w.path,"en"));let g=r.omitted.filter(N=>f(N.path)||h(N.path)||!qo(e,N.path)?!1:m.has(N.path)?c.has(N.path)||[...c].some(w=>w.startsWith(`${N.path}/`)):!0);for(let N of b)g.some(w=>w.path===N.path&&w.reason===N.reason)||g.push(N);g.sort((N,w)=>N.path.localeCompare(w.path,"en"));let y=r.omissionOverflow?.count??0,E=r.omissionOverflow?.hash??L("comet.native.snapshot-omission-overflow.v1");s.overflow&&(y+=s.overflow.count,E=zo(E,"git-selection",{source:"git-selection",...s.overflow}));let k=N=>{y+=1,E=zo(E,"omission",N)};for(;g.length>Lh;){let N=$l(g);if(N===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");k(N)}let S=()=>({...r,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:g.length+y===0,entries:p,omitted:g,omittedCount:g.length+y,...y>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${E}`,hash:E,count:y}}:{}}),R=S();for(;Vh(R)>r.limits.maxManifestBytes;){let N=$l(g);if(N===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");k(N),R=S()}return Ii(R)}function _N(e,t){if(!zI.test(t))throw new Error(`Invalid Native change name: ${t}`);return V.join(H(e,t),"baseline-manifest.json")}async function Ll(e,t={}){let i={maxFiles:t.limits?.maxFiles??Tl.maxFiles,maxFileBytes:t.limits?.maxFileBytes??Tl.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??Tl.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??Tl.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},r=xN(t.policy),n=NN({...t,deadlineMs:t.deadlineMs??i.maxDurationMs}),a=bN(t.gitSelectionLimits),o=fj(t.physicalSelectionLimits);if(i.maxFiles<1||i.maxFileBytes<1||i.maxTotalBytes<1||i.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=V.resolve(e.projectRoot),c=await ce.realpath(s),l=V.resolve(e.nativeRoot),u=await ce.realpath(l),d=V.resolve(e.runtimeDir),f=V.resolve(e.configFile),h=V.join(s,".comet","current-change.json"),v=Sj(s,t.denylist??[]),m=[],p=[],b=new Map,g=new Map,y=0,E=0,k=L("comet.native.snapshot-omission-overflow.v1"),S=0,R=!1,N=null,w=_=>{E+=1,k=zo(k,"omission",_)},P=_=>{if(y+=1,p.length<Lh){p.push(_);return}if(Dh(_)){let A=$l(p);if(A===null)throw new Error("Native snapshot has too many required selection-integrity omissions");w(A),p.push(_);return}w(_)},F=_=>{y+=_.count,E+=_.count,k=zo(k,"git-selection",{source:"git-selection",..._})},$=_=>{E+=1,k=zo(k,"manifest-entry",{reason:"manifest-size",entry:_})},Fe=async(_,A)=>{m.push(_),S+=_.size,b.set(_.path,A),R||(R=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(_.path))},ue=(_,A)=>{let I=m.findIndex(oe=>oe.path===_);if(I<0)return;let[q]=m.splice(I,1);S-=q.size,b.delete(_),P(A)},te=async(_,A,I,q)=>{if(!I.isFile()||I.isSymbolicLink()||!M(n))return;let oe;try{oe=await ce.realpath(_)}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;P({path:A,size:I.size,type:"file",reason:Ee(x)?"changed-during-read":"unreadable"});return}if(!M(n)||!O(c,oe)||ti(u,oe))return;if(m.length>=i.maxFiles){P({path:A,size:I.size,type:"file",reason:"file-count"});return}if(I.size>i.maxFileBytes){P({path:A,size:I.size,type:"file",reason:"file-size"});return}if(S+I.size>i.maxTotalBytes){P({path:A,size:I.size,type:"file",reason:"total-size"});return}let U,B,ve;try{if(U=await Cj(oe,I.size,I,n),U.status==="budget-exhausted"||!M(n))return;if(U.status==="changed"){P({path:A,size:null,type:"file",reason:"changed-during-read"});return}if(!M(n)||(ve=await ce.realpath(_),!M(n)))return;B=await ce.lstat(_)}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;P({path:A,size:I.size,type:"file",reason:Ee(x)?"changed-during-read":"unreadable"});return}if(M(n)){if(U.bytes!==I.size||ve!==oe||!br(I,U.finalStat)||!br(U.finalStat,B)||!B.isFile()||B.isSymbolicLink()||B.size!==I.size||B.mtimeMs!==I.mtimeMs||B.ctimeMs!==I.ctimeMs){P({path:A,size:B.isFile()?B.size:null,type:B.isFile()?"file":"other",reason:"changed-during-read"});return}M(n)&&await Fe({path:A,hash:U.hash,size:B.size,type:"file",...q===void 0?{}:{gitObjectId:q}},{kind:"file",target:_,realTarget:oe,stat:B})}},ai=async(_,A,I)=>{if(!M(n))return;let q,oe,U;try{if(q=await ce.readlink(_,{encoding:"buffer"}),!M(n)||(U=await ce.lstat(_),!M(n)))return;oe=await ce.readlink(_,{encoding:"buffer"})}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;P({path:A,size:null,type:"other",reason:Ee(x)?"changed-during-read":"unreadable"});return}if(!M(n))return;if(!U.isSymbolicLink()||!br(I,U)||U.mtimeMs!==I.mtimeMs||U.ctimeMs!==I.ctimeMs||!q.equals(oe)){P({path:A,size:null,type:"other",reason:"changed-during-read"});return}let B=q.byteLength;if(m.length>=i.maxFiles){P({path:A,size:B,type:"other",reason:"file-count"});return}if(B>i.maxFileBytes){P({path:A,size:B,type:"other",reason:"file-size"});return}if(S+B>i.maxTotalBytes){P({path:A,size:B,type:"other",reason:"total-size"});return}let ve=Ol("sha256").update("symlink\0").update(q).digest("hex");M(n)&&await Fe({path:A,hash:ve,size:B,type:"file"},{kind:"symlink",target:_,rawTarget:q,stat:U})},Vt=async()=>{for(let[_,A]of[...b]){if(!M(n))return;if(A.kind==="file"){let B,ve;try{if(B=await ce.realpath(A.target),!M(n))return;ve=await ce.lstat(A.target)}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;ue(_,{path:_,size:null,type:"file",reason:Pe(x)?"unreadable":"changed-during-read"});continue}if(!M(n))return;(B!==A.realTarget||!ve.isFile()||ve.isSymbolicLink()||!br(A.stat,ve)||ve.size!==A.stat.size||ve.mtimeMs!==A.stat.mtimeMs||ve.ctimeMs!==A.stat.ctimeMs)&&ue(_,{path:_,size:ve.isFile()?ve.size:null,type:ve.isFile()?"file":"other",reason:"changed-during-read"});continue}if(A.kind==="symlink"){let B,ve;try{if(B=await ce.lstat(A.target),!M(n))return;ve=await ce.readlink(A.target,{encoding:"buffer"})}catch(x){if(!M(n))return;if(!Pe(x)&&!Ee(x))throw x;ue(_,{path:_,size:null,type:"other",reason:Pe(x)?"unreadable":"changed-during-read"});continue}if(!M(n))return;(!B.isSymbolicLink()||!br(A.stat,B)||B.mtimeMs!==A.stat.mtimeMs||B.ctimeMs!==A.stat.ctimeMs||!A.rawTarget.equals(ve))&&ue(_,{path:_,size:null,type:"other",reason:"changed-during-read"});continue}let I,q;try{if(I=await ce.realpath(A.target),!M(n))return;q=await ce.lstat(A.target)}catch{if(!M(n))return;ue(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!M(n))return;if(!(I===A.realTarget&&q.isDirectory()&&!q.isSymbolicLink()&&br(A.stat,q)&&O(c,I)&&!ti(u,I))){ue(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"});continue}let U;try{if(!M(n))return;U=await hN(n,I)}catch(B){if(na(B))throw B;ue(_,{path:_,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!M(n))return;U.dirty?ue(_,{path:_,size:null,type:"directory",reason:"gitlink-dirty"}):U.hash!==A.hash&&ue(_,{path:_,size:null,type:"directory",reason:"gitlink-changed"})}for(let[_,A]of g){if(!M(n))return;try{let I=await ce.lstat(A);if(!M(n))return;P({path:_,size:I.isFile()?I.size:null,type:I.isFile()?"file":I.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(I){if(!M(n))return;if(Ee(I))continue;if(!Pe(I))throw I;P({path:_,size:null,type:"file",reason:"unreadable"})}}},pt=await EN(n,e,a,t.gitSelectionHooks);if(pt===null){let _=await dN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let q of _.records){if(q.type!=="file"&&q.type!=="symlink"||b.has(q.path))continue;if(ei(n)<1)break;if(!mN(r,q.path,n))continue;if(ei(n)<1)break;let oe=V.resolve(s,...q.path.split("/")),U;try{U=await ce.lstat(oe)}catch(B){if(!M(n))break;if(!Pe(B)&&!Ee(B))throw B;P({path:q.path,size:null,type:"file",reason:Ee(B)?"changed-during-read":"unreadable"});continue}if(ei(n)<1)break;if(q.type==="symlink"&&U.isSymbolicLink()){if(await ai(oe,q.path,U),ei(n)<1)break;continue}if(q.type!=="file"||!U.isFile()||U.isSymbolicLink()){P({path:q.path,size:U.isFile()?U.size:null,type:U.isDirectory()?"directory":U.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await te(oe,q.path,U),ei(n)<1)break}ei(n)>=1&&await Vt();let A=await dN({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:v,policy:r,limits:o}),I=bj(_.evidence,A.evidence);N=I.evidence;for(let q of[..._.omissions,...A.omissions,...I.omissions])p.some(oe=>oe.path===q.path&&oe.reason===q.reason)||P(q)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let _=t.incrementalBaseline,A=new Map,I=!1;if(_){let x=Ii(_);for(let de of x.entries)de.gitObjectId!==void 0&&A.set(de.path,de);I=A.size>0}let q=new Set,oe=!0;try{let x=await Wo(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(x.overflow)I=!1,oe=!1,A.clear();else for(let de of x.records){let ge=jl(de),Ye=ge.indexOf(" "),Be=Ye<0?null:aa(ge.slice(Ye+1));if(Ye!==1||Be===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");ge[0]!=="H"&&q.add(Be)}}catch(x){if(na(x))throw x;I=!1,oe=!1,A.clear()}let U=new Set;try{let x=await Il(n,s,["ls-files","--modified","-z"],Hh);for(let de of x.toString("utf8").split("\0")){let ge=aa(de);ge!==null&&U.add(ge)}}catch{I=!1,oe=!1,A.clear()}let B=new Set,ve=new Set;for(let x of CN(pt)){if(b.has(x)||!qo(e,x))continue;if(ei(n)<1)break;if(!mN(r,x,n))continue;if(ei(n)<1)break;let de=V.resolve(s,...x.split("/"));if(de===f||de===h||ti(d,de)||v.some(mt=>ti(mt,de)))continue;if(pt.gitlinks.has(x)){if(m.length>=i.maxFiles){P({path:x,size:0,type:"file",reason:"file-count"});continue}let mt,zs;try{[mt,zs]=await Promise.all([ce.realpath(de),ce.lstat(de)])}catch{P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(zs.isSymbolicLink()||!zs.isDirectory()||!O(c,mt)||ti(u,mt)){P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let Pn=await hN(n,mt);if(Pn.dirty){P({path:x,size:null,type:"directory",reason:"gitlink-dirty"});continue}await Fe({path:x,hash:Pn.hash,size:0,type:"file"},{kind:"gitlink",target:de,realTarget:mt,stat:zs,hash:Pn.hash})}catch(Pn){if(na(Pn))throw Pn;P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let ge;try{ge=await ce.lstat(de)}catch(mt){if(Ee(mt)&&pt.tracked.has(x)){g.set(x,de);continue}if(!Pe(mt)&&!Ee(mt))throw mt;P({path:x,size:null,type:"file",reason:Ee(mt)?"changed-during-read":"unreadable"});continue}if(ge.isSymbolicLink()){await ai(de,x,ge);continue}if(!ge.isFile()){pt.nestedRepositories.has(x)||P({path:x,size:null,type:"other",reason:"changed-during-read"});continue}let Ye=pt.trackedObjectIds.get(x),Be=Ye?A.get(x):void 0;if(I&&Be?.gitObjectId!==void 0&&Be.gitObjectId===Ye&&!q.has(x)&&!U.has(x)){if(m.length>=i.maxFiles){P({path:x,size:Be.size,type:"file",reason:"file-count"});continue}if(Be.size>i.maxFileBytes){P({path:x,size:Be.size,type:"file",reason:"file-size"});continue}if(S+Be.size>i.maxTotalBytes){P({path:x,size:Be.size,type:"file",reason:"total-size"});continue}m.push({...Be}),S+=Be.size,B.add(x);continue}let qm=oe&&!q.has(x)&&!U.has(x)?Ye:void 0;await te(de,x,ge,qm),qm!==void 0&&ve.add(x)}if(await Vt(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await PN(n,e,a,pt,t.gitSelectionHooks?.outputChunkBytes),B.size>0||I&&ve.size>0){let x=await Il(n,s,["ls-files","--modified","-z"],Hh),de=new Set;for(let ge of x.toString("utf8").split("\0")){let Ye=aa(ge);Ye!==null&&de.add(Ye)}for(let ge of B){if(!de.has(ge))continue;let Ye=m.find(Be=>Be.path===ge);ue(ge,{path:ge,size:Ye?.size??null,type:"file",reason:"changed-during-read"})}for(let ge of ve){if(!de.has(ge))continue;let Ye=m.find(Be=>Be.path===ge);Ye&&delete Ye.gitObjectId}}for(let x of pt.omissions)P(x);pt.overflow&&F(pt.overflow)}m.sort((_,A)=>_.path.localeCompare(A.path,"en")),p.sort((_,A)=>_.path.localeCompare(A.path,"en"));let fP=pt===null?{provider:"physical-tree",...N?{physicalSelection:N}:{}}:{provider:"git",...pt.evidence?{gitSelection:pt.evidence}:{}},Vm=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:fP,createdAt:(t.now??new Date).toISOString(),complete:y===0,limits:i,...r?{policy:r.manifest}:{},entries:m,omitted:p,omittedCount:y,...E>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${k}`,hash:k,count:E}}:{}}),sd=Vm();for(;Vh(sd)>i.maxManifestBytes;){if(p.filter(A=>!Dh(A)).length>0){let A=Math.max(1,Math.ceil(p.length/4));for(let I=0;I<A;I+=1){let q=$l(p);if(q===null)break;w(q)}}else if(m.length>0){let A=Math.max(1,Math.ceil(m.length/4));for(let I of m.splice(-A))y+=1,$(I)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");sd=Vm()}return sd}async function qh(e,t,i={}){let n=(await ye(e.projectRoot))?.native.snapshot??lh;return Ll(e,{...i,policy:t.policy,incrementalBaseline:t,limits:{maxFiles:n.max_files,maxFileBytes:n.max_total_bytes,maxTotalBytes:n.max_total_bytes,maxDurationMs:n.max_duration_ms},deadlineMs:n.max_duration_ms})}async function Wh(e,t,i){let r=_N(e,t);await T(j(e,r),r),await ee(r,Ii(i))}async function sa(e,t){let i=_N(e,t),r=j(e,i);await T(r,i);try{let n=await Sl({root:r,file:i,maxBytes:WI,label:"Native baseline snapshot manifest"});return Ii(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}import{createHash as Xj}from"crypto";import Qj from"path";var Nt=Object.freeze({stateRef:"runtime/run-state.json",pendingRef:"runtime/pending-action.json",trajectoryRef:"runtime/trajectory.jsonl",contextRef:"runtime/context.md",artifactsRef:"runtime/artifacts.json",checkpointRef:"runtime/checkpoints/latest.json",snapshotsRef:"runtime/skill-snapshots"});import{createHash as zj}from"node:crypto";import{constants as Fl,promises as tt}from"node:fs";import bt from"node:path";import{TextDecoder as Jj}from"node:util";import Bj from"path";var Dj=Rn(Qr(),1);var J1=4*1024*1024;var Lj=null;function Mj(e,t){let i=e;for(let r of t)i+="\0"+(typeof r=="string"?r:JSON.stringify(r));return i}function TN(e,t){return(...i)=>{let r=Lj;if(r===null)return t(...i);let n=Mj(`async:${e}`,i),a=r.entries.get(n);if(a)return a.value;let o=t(...i).catch(s=>{throw r.entries.delete(n),s});return r.entries.set(n,{value:o}),o}}var X1=TN("hookWritePolicy",async e=>(await nh(e))?.hook??{allow_paths:[]});var IN=(e,t)=>{let i=e[t];return i==null?null:String(i)};function Go(e,t){let i=e[t];if(typeof i!="string"||i.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return i}function Jo(e,t){let i=Go(e,t);if(Bj.isAbsolute(i)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(i)||i.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return i}function Vj(e){let t=e.run_retries??"{}",i;try{i=typeof t=="string"?JSON.parse(t):t}catch(r){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:r})}if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let r of Object.values(i))if(!Number.isInteger(r)||Number(r)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return i}function jN(e){if(!e.run_id)return null;let t=Go(e,"run_id"),i=Go(e,"skill"),r=Go(e,"skill_version"),n=Go(e,"skill_hash"),a=Jo(e,"pending_ref"),o=Jo(e,"trajectory_ref"),s=Jo(e,"context_ref"),c=Jo(e,"artifacts_ref"),l=Jo(e,"checkpoint_ref"),u=Number(e.iteration);if(!Number.isInteger(u)||u<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:i,skillVersion:r,skillHash:n,orchestration:e.orchestration,currentStep:IN(e,"current_step"),iteration:u,pending:IN(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:Vj(e)}}var zW=256*1024;var qj=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"]);function Wj(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)},i=jN(t);if(!i)throw new Error("Invalid Run state: runId must be a non-empty string");return i}function Ml(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,i=Object.keys(t).find(r=>!qj.has(r));if(i)throw new Error(`Invalid Run state: unknown field ${i}`);if(t.currentStep!==null&&(typeof t.currentStep!="string"||t.currentStep.length===0))throw new Error("Invalid Run state: currentStep must be a non-empty string or null");if(t.pending!==null&&(typeof t.pending!="string"||t.pending.length===0))throw new Error("Invalid Run state: pending must be a non-empty string or null");if(!t.retries||typeof t.retries!="object"||Array.isArray(t.retries))throw new Error("Invalid Run state: retries must be an object");return Wj(t)}var Je={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};function Ko(e,t){let i=bt.relative(e,t);return i===""||!bt.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${bt.sep}`)}function ON(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Uo(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function Gj(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Sr(e,t,i){let r=Nt[t];if(i!==void 0&&i!==r)throw new Error(`Native Run ${t} ref must be ${r}`);let n=bt.resolve(e),a=bt.resolve(n,...r.slice(8).split("/"));if(!Ko(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function $N(e){let t=await tt.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await tt.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function zh(e,t){let i=bt.resolve(e),r=bt.resolve(t);if(!Ko(i,r))throw new Error("Native Run path is outside its change");let n=[await $N(i)],a=i;for(let o of bt.relative(i,r).split(bt.sep).filter(Boolean)){a=bt.join(a,o);let s;try{s=await $N(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!Ko(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function Bl(e){for(let t of e){let i=await tt.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Gj(t,i)||await tt.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function Uj(e,t,i){let r=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${i} exceeds ${t} bytes`);r.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(r,n)}async function ln(e,t,i,r,n){let a=await zh(e,bt.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await tt.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${r} must be a regular file`);if(o.size>i)throw new Error(`${r} exceeds ${i} bytes`);let s=ON(o),c=await tt.realpath(t);if(!Ko(a[0].realPath,c))throw new Error(`${r} resolves outside its change`);let l=process.platform==="win32"?Fl.O_RDONLY:Fl.O_RDONLY|Fl.O_NOFOLLOW|Fl.O_NONBLOCK,u;try{u=await tt.open(t,l)}catch(d){throw new Error(`${r} changed while opening`,{cause:d})}try{let[d,f,h]=await Promise.all([u.stat(),tt.lstat(t),tt.realpath(t)]);if(await Bl(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||h!==c||!Uo(s,d)||!Uo(s,f))throw new Error(`${r} changed while opening`);await n?.afterOpen?.();let v=await Uj(u,i,r);await n?.beforeFinalCheck?.();let[m,p,b]=await Promise.all([u.stat(),tt.lstat(t),tt.realpath(t)]);if(await Bl(a),!p.isFile()||p.isSymbolicLink()||b!==c||!Uo(s,m)||!Uo(s,p))throw new Error(`${r} changed while reading`);let g;try{g=new Jj("utf-8",{fatal:!0}).decode(v)}catch(y){throw new Error(`${r} is not valid UTF-8`,{cause:y})}return{text:g,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function Kj(e,t,i){let r=await zh(e,bt.dirname(t));if(!r)return{exists:!1};let n;try{n=await tt.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!n.isFile()||n.isSymbolicLink())throw new Error(`${i} must be a regular file`);let a=await tt.realpath(t);if(!Ko(r[0].realPath,a))throw new Error(`${i} resolves outside its change`);return await Bl(r),{exists:!0,identity:ON(n),realPath:a}}async function Yj(e,t,i,r){let n=await zh(e,bt.dirname(t));if(!n){if(!i.exists)return;throw new Error(`${r} parent changed before commit`)}let a;try{a=await tt.lstat(t)}catch(o){if(o.code==="ENOENT"&&!i.exists)return;throw new Error(`${r} changed before commit`,{cause:o})}if(!i.exists||!a.isFile()||a.isSymbolicLink()||!Uo(i.identity,a)||await tt.realpath(t)!==i.realPath)throw new Error(`${r} changed before commit`);await Bl(n)}async function Vl(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let i=e.expected??await Kj(e.changeDir,e.file,e.label);if(i.exists&&i.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await he(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await Yj(e.changeDir,e.file,i,e.label)}});let r=await ln(e.changeDir,e.file,e.maxBytes,e.label);if(!r||r.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function HN(e,t){try{return JSON.parse(e)}catch(i){throw new Error(`${t} contains invalid JSON`,{cause:i})}}function DN(e){return`${JSON.stringify(e,null,2)}
|
|
190
|
+
`}function Er(e){return Ml(e)}async function $e(e,t){let i=Sr(e,"stateRef"),r=await ln(e,i,Je.runStateBytes,"Native Run state",t);return r?Ml(HN(r.text,"Native Run state")):null}async function un(e,t,i){let r=Ml(t);await Vl({changeDir:e,file:Sr(e,"stateRef"),content:DN(r),maxBytes:Je.runStateBytes,label:"Native Run state",hooks:i})}async function it(e,t,i){let r=Sr(e,"trajectoryRef",t),n=await ln(e,r,Je.trajectoryBytes,"Native Run trajectory",i);if(!n)return[];let a=n.text.split(/\r?\n/u).map((o,s)=>({line:o,number:s+1})).filter(({line:o})=>o.length>0);if(a.length>Je.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Je.trajectoryEvents} events`);return a.map(({line:o,number:s})=>{try{return JSON.parse(o)}catch(c){throw new Error(`Invalid Native Run trajectory event at line ${s}`,{cause:c})}})}async function LN(e,t,i){return(await ln(e,Sr(e,"trajectoryRef",t),Je.trajectoryBytes,"Native Run trajectory",i))?.text??null}async function MN(e,t,i,r,n){if(!/^[a-f0-9]{64}$/u.test(r))throw new Error("Native Run trajectory expected hash is invalid");let a=Sr(e,"trajectoryRef",t),o=await ln(e,a,Je.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(zj("sha256").update(o.text,"utf8").digest("hex")!==r)throw new Error("Native Run trajectory changed before repair");await Vl({changeDir:e,file:a,content:i,maxBytes:Je.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:n})}async function FN(e,t,i,r){let n=Sr(e,"trajectoryRef",t),a=`${JSON.stringify(i)}
|
|
191
|
+
`;if(Buffer.byteLength(a,"utf8")>Je.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${Je.trajectoryEventBytes} bytes`);let o=await ln(e,n,Je.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=Je.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${Je.trajectoryEvents} events`);await Vl({changeDir:e,file:n,content:`${o?.text??""}${a}`,maxBytes:Je.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:r})}async function ca(e,t,i){let r=await ln(e,Sr(e,"checkpointRef",t),Je.checkpointBytes,"Native Run checkpoint",i);return r?HN(r.text,"Native Run checkpoint"):null}async function BN(e,t,i,r){await Vl({changeDir:e,file:Sr(e,"checkpointRef",t),content:DN(i),maxBytes:Je.checkpointBytes,label:"Native Run checkpoint",hooks:r})}var Zj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ql=class extends Error{constructor(i){super(i.status==="repairable"?`Native trajectory has an incomplete final line at ${i.file}:${i.line}; run doctor --repair`:`Native trajectory is invalid at ${i.file}:${i.line}: ${i.message}`);this.inspection=i;this.name="NativeTrajectoryRepairRequiredError"}inspection;code="native-trajectory-tail-repair-required"};function Jh(e){return Xj("sha256").update(e).digest("hex")}function e$(e,t){if(!Zj.test(t))throw new Error(`Invalid Native change name: ${t}`);return Qj.join(H(e,t),"trajectory.jsonl")}function t$(e){let t=e.split(/\n/u),i=0;for(let r=0;r<t.length;r+=1){let n=t[r].endsWith("\r")?t[r].slice(0,-1):t[r];if(n.length!==0){i=r+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:r+1,message:a.message}}}}return{status:"valid",count:i}}function i$(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let i=/position (\d+)/iu.exec(e.message)?.[1];return i!==void 0&&Number(i)>=Math.max(0,t.length-1)}function r$(e,t){let i=t.lastIndexOf(10),r=t.subarray(0,i+1),n=t$(r.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(i===t.length-1)return{status:"clean",file:e};let a=t.subarray(i+1),o=a.toString("utf8"),s=n.count+1,c,l;try{JSON.parse(o.endsWith("\r")?o.slice(0,-1):o),c="missing-newline",l=Buffer.concat([t,Buffer.from(`
|
|
192
|
+
`)])}catch(d){if(!i$(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=r}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:Jh(t),targetHash:Jh(l),tailHash:Jh(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function VN(e,t){let i=e$(e,t);await T(j(e,i),i);let r=H(e,t),n=await LN(r,Nt.trajectoryRef);return n===null?{status:"clean",file:i}:r$(i,Buffer.from(n))}async function la(e,t){let i=await VN(e,t);return"inspection"in i?i.inspection:i}async function Wl(e,t){let i=await la(e,t);if(i.status!=="clean")throw new ql(i)}async function qN(e,t,i){return se(e,`repair trajectory tail for ${t}`,async()=>{let r=await VN(e,t);if(!("inspection"in r)){if(r.status==="clean")return null;throw new ql(r)}try{await MN(H(e,t),Nt.trajectoryRef,r.targetContent,r.inspection.originalHash,{beforeCommit:i?.beforeCommit})}catch(a){throw/changed (?:before|while)/iu.test(a.message)?new Error(`Native trajectory changed while preparing tail repair for ${t}; inspect it again before retrying`,{cause:a}):a}if((await la(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return r.inspection})}import{createHash as n$}from"node:crypto";import{promises as zl}from"node:fs";import ji from"node:path";var Yo=/^[a-f0-9]{64}$/u,WN=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,a$=16*1024,Uh=process.platform,o$=new Set(["workspace-root-changed","workspace-inspection-unavailable"]);function ua(e){return o$.has(e)}function GN(e,t){let i=ji.relative(e,t);return ji.isAbsolute(i)||i===".."||i.startsWith(`..${ji.sep}`)?null:i.replaceAll("\\","/")||"."}function UN(e){return Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127})}function KN(e,t){if(e.length===0||UN(e)||e.includes("\\")||ji.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let i=ji.posix.normalize(e);if(i!==e||i===".."||i.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Kh(e,t){return n$("sha256").update(`${e}
|
|
193
|
+
${t}`).digest("hex")}async function zN(e,t){let i=await zl.realpath(t),r=await zl.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Uh==="win32"?ji.normalize(i).toLowerCase():i;return Kh(e,`${n}
|
|
194
194
|
${r.dev}
|
|
195
195
|
${r.ino}
|
|
196
|
-
${r.birthtimeMs}`)}async function
|
|
196
|
+
${r.birthtimeMs}`)}async function JN(e,t){let i=await zl.realpath(t),r=await zl.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Uh==="win32"?ji.normalize(i).toLowerCase():i;return Kh(e,n)}function s$(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function Gh(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||UN(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function YN(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Gh(e.changeBranch,"Native workspace change branch"),Gh(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function c$(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,i=new Set(["provider","baseCommit","targetBranch","targetCommit"]),r=Object.keys(t).filter(n=>!i.has(n));if(r.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${r.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!WN.test(t.baseCommit)||typeof t.targetCommit!="string"||!WN.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Gh(t.targetBranch,"Native workspace Git target branch")}function Xo(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,i=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),r=Object.keys(t).filter(o=>!i.has(o));if(r.length>0)throw new Error(`Native workspace identity has unknown field(s): ${r.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Yo.test(String(t.projectRootId))||!Yo.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");s$(t.capturedAt),KN(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!Yo.test(String(t.projectRootPathId))||a&&!Yo.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Yo.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&c$(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(YN(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function da(e,t){return ji.join(H(e,t),"workspace.json")}function l$(e,t){let i=da(e,t),r=j(e,i),n=GN(r,i);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:r,ref:KN(n,"Native workspace file ref")}}async function XN(e,t){try{let i=l$(e,t),r=await Z({root:i.root,ref:i.ref,maxBytes:a$});return JSON.parse(r.text)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function QN(e,t){let i=fe(e.projectRoot),r={projectRoot:ji.resolve(e.projectRoot),currentBranch:i.currentBranch,isSecondaryWorktree:i.isSecondaryWorktree};try{let n=await kt(e,t);if(n===null)return{...r,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...r,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await fa({paths:e,identity:n});return{...r,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...r,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function Yh(e,t){let i=await XN(e,t);if(i===null)return!1;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native workspace identity must be an object");return i.schema==="comet.native.workspace.v1"?!0:(Xo(i),i.schema==="comet.native.workspace.v3"?!1:i.projectRootPathId===void 0||i.nativeRootPathId===void 0)}async function ZN(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=GN(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let i=fe(e.paths.projectRoot),r=i.isGitWorktree?xi(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??i.currentBranch,a=n==null?null:xi(e.paths.projectRoot,n),o=r!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:r,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([zN("comet.native.workspace-project-root.v2",e.paths.projectRoot),zN("comet.native.workspace-native-root.v2",e.paths.nativeRoot),JN("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),JN("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&YN(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:Kh("comet.native.workspace-session.v2",`${s}
|
|
197
197
|
${c}
|
|
198
|
-
${e.sessionId}`)}:{}},h=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return Ko(h),h}async function Vl(e){let t=await UN(e),i=la(e.paths,e.name),r=j(e.paths,i);return await T(r,i),await Z(i,t,{containedRoot:r}),t}async function bt(e,t){let i=await JN(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Ko(i),i)}async function KN(e){return await Uh(e.paths,e.name)?Vl(e):null}async function Yo(e){Ko(e.identity);let t=await UN({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),Jh==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function ua(e){if(Ko(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Yo(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=de(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function YN(e,t){let i=await bt(e,t);if(i===null)return null;let r=await ua({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var QN=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],Jj=new Set(QN),ZN=new Set([...QN,"minimum_runtime_version","revision"]),Gj=new Set([...ZN,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),Uj=new Set(["capability","operation","source","base_hash"]),Kj=new Set(["shape","build","verify","archive"]),Yj=new Set(["implicit","confirmed"]),Xj=new Set(["pending","pass","fail"]),_e="comet-state.yaml",Yh=/^[a-f0-9]{64}$/u,eb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Qj=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Xo=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},un=class extends Error{constructor(i,r){super(i!==ye||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},Qo=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Zo=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},da=class extends Error{constructor(i,r,n,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${r} omitted entr${r===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=r;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},u2=Ws("en");function ts(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function tb(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Wl(e){if(!eb.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Zj(e){if(!eb.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function ib(e,t){if(e.length===0||pi.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function e$(e,t){let i=ts(e,`spec_changes[${t}]`);if(tb(i,Uj,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(Zj(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let r=i.source,n=i.base_hash;if(r!==void 0&&typeof r!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof r=="string"&&ib(r,`Spec source for ${i.capability}`),i.operation==="create"){if(!r)throw new Error(`Create spec ${i.capability} requires source`);if(n!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!r)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof n!="string"||!Yh.test(n))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(r!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof n!="string"||!Yh.test(n))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof r=="string"?{source:r}:{},base_hash:n}}function t$(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function Xh(e,t){if(tb(e,t,_e),typeof e.name!="string")throw new Error("Native change name is required");if(Wl(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!Kj.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!Yj.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let i=e.spec_changes.map(e$),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof e.verification_result!="string"||!Xj.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&ib(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!t$(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function nn(e){let t=ts(e,_e);if(t.schema!==Ze)throw new Error(`Expected ${Ze}`);return{schema:Ze,...Xh(t,Jj)}}function es(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Kh(e,t,i){if(e===null)return null;let r=typeof e=="string"?Qj.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function i$(e){if(e==null)return null;if(typeof e!="string"||!Yh.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function r$(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function ui(e){let t=ts(e,_e);if(t.schema!==Ne)throw new Error(`Expected ${Ne}`);if(es(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Ne} minimum_runtime_version must be 2`);return{schema:Ne,minimum_runtime_version:2,revision:es(t.revision,"Native v2 revision"),...Xh(t,ZN)}}function ct(e){let t=ts(e,_e);if(t.schema!==ye){if(t.schema===Ze||t.schema===Ne){let o=t.schema===Ze?nn(t):ui(t);throw new Xo(o.name,o.schema)}throw new un(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=es(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new un(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=es(t.revision,"Native revision"),n=Xh(t,Gj),a=i$(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ye,minimum_runtime_version:3,revision:r,verification_protocol:r$(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Kh(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Kh(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Kh(t.partial_allowance,"Native partial_allowance","allowances")}}function rb(e){let t=ts(e,_e);if(t.schema===Ze){let n=nn(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ye}`}}if(t.schema===Ne){let n=ui(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ye}`}}if(t.schema!==ye){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new un(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=es(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new un(t.schema,i).message};let r=ct(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function ln(e){let t=ct(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function zl(e){let t=ui(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function re(e,t){Wl(t);let i=pi.join(e.changesDir,t);if(!O(e.changesDir,i))throw new Error("Native change path escaped");return i}async function fa(e,t){let i=H(e,t),r=pi.join(i,"schema-migration.json");await T(O(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await XN.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function ha(e,t){let i=H(e,t),r=pi.join(i,"checkpoint-journal.json");await T(O(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await XN.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Jl(e,t=pi.dirname(e)){let i=pi.relative(t,e).split(pi.sep).join("/"),r=await Q({root:t,ref:i,maxBytes:null,includeHash:!1}),n=(0,ql.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function mi(e,t){let i=pi.join(re(e,t),_e);await T(e.nativeRoot,i);let r=rb(await Jl(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await fa(e,t)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(r.status==="current"&&r.state&&await n$(e,r.state),r)}async function Gl(e,t){let i=pi.join(re(e,t),_e);await T(e.nativeRoot,i);let r=rb(await Jl(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function n$(e,t){if(await aa(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function Oe(e,t){let i=await mi(e,t);if(i.status==="migration-required")throw new Xo(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new un(i.schema,i.minimumRuntimeVersion);return await YN(e,t),i.state}async function nb(e,t,i){let r={...t,schema:ye,minimum_runtime_version:3,revision:i+1},n=await rN({expectedRevision:i,next:r,read:async()=>{let a=ct(await Jl(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>fe(e,(0,ql.stringify)(ln(a))),equals:(a,o)=>JSON.stringify(ln(a))===JSON.stringify(ln(o)),conflict:a=>new Qo(t.name,i,a)});return Object.assign(t,n),n}async function Ul(e,t,i,r){if(await Vn(e.projectRoot),await fa(e,t.name))throw new Xo(t.name,t.schema);if(!r?.allowPendingCheckpointRecovery&&await ha(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await Oe(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Fl(e,t.name);let a=pi.join(re(e,t.name),_e);return await T(e.nativeRoot,a),nb(a,t,i)}async function ab(e,t){return nb(e,t,t.revision)}async function ob(e){return ct(await Jl(e))}var cb=["outcome","scope","nonGoals","acceptanceExamples"],a$=[...cb,"constraints","decisions","openQuestions","verificationExpectations"],o$=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],lb={maxFileBytes:bo};function ub(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
|
|
199
|
-
`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),t}async function s$(e,t){let i=sb.resolve(e,...t.split(/[\\/]/u));if(!O(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await Qh.realpath(e),n=await Qh.realpath(i);if(!O(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await Qh.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function is(e){return{valid:e.length===0,findings:e}}async function Zh(e,t){let i=[],r;try{r=(await Q({root:e,ref:t,maxBytes:lb.maxFileBytes})).text}catch(o){return is([{code:"brief-missing",message:o.message,path:t}])}let n=new Map;for(let[o,s]of ub(r))n.set(qs(o)??o,s);for(let o of a$)n.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of cb)(n.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=n.get("openQuestions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),is(i)}async function ep(e,t){let i=[],r;try{r=(await Q({root:e,ref:t,maxBytes:lb.maxFileBytes})).text}catch(a){return is([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of ub(r))n.set(Um(a)??a,o);for(let a of o$)n.has(a)?(n.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return is(i)}function Kl(e,t){return sb.join(e.specsDir,t,"spec.md")}async function db(e,t){let i=[],r=re(e,t.name);for(let n of t.spec_changes){let a=Kl(e,n.capability),o=null;try{await T(e.nativeRoot,a),o=await Qt(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await s$(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return is(i)}import{promises as hH}from"node:fs";import Uk from"node:path";import fb from"node:path";var c$="comet.native.archive-preflight.v1",l$="comet.native.archive-preflight.v1",u$="comet.native.archive-operation.v1",d$=/^[a-f0-9]{64}$/u,hb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,f$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Yl(e,t){return e<t?-1:e>t?1:0}function h$(e,t){if(typeof e!="string"||!d$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ji(e,t){return e===null?null:h$(e,t)}function p$(e,t){let i=fb.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||fb.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function m$(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function v$(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function g$(e,t){if(!hb.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=ji(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=ji(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=ji(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function w$(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:ji(e.contractHash,"Native archive contract hash"),acceptanceHash:ji(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:ji(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:ji(e.reportHash,"Native archive report hash"),envelopeHash:ji(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:ji(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function y$(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!f$.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(Yl);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function N$(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(Yl)}function pb(e){if(!hb.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(g$).sort((l,u)=>Yl(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:D(u$,l)})),r=w$(e.evidence),n=v$(e.workspace),a=[...new Set([...y$(e.findingCodes??[]),...N$({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(Yl),o=m$(e.revision),s=p$(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:r,workspace:n,findingCodes:a};return{schema:c$,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:D(l$,c)}}import{createHash as b$}from"node:crypto";import mb from"node:path";var k$="comet.native.conflict-radar.v1",lt=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512}),S$="comet.native.conflict-radar.v1",E$="comet.native.conflict-radar-signals.v1",P$=/^[a-f0-9]{64}$/u,wb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,R$=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),C$=new Set(["capability","operation","baseHash"]),x$=new Set(["path","kind"]);function pa(e,t){return e<t?-1:e>t?1:0}function tp(e){return Buffer.byteLength(e,"utf8")}function ip(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let r=e,n=Object.keys(r).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function rp(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(tp(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function A$(e,t){let i=rp(e,t,lt.maxArtifactPathBytes),r=mb.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||mb.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function yb(e,t){if(typeof e!="string"||!P$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function _$(e,t){let i=ip(e,C$,t),r=rp(i.capability,`${t} capability`,lt.maxCapabilityBytes);if(!wb.test(r))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=i.baseHash===null?null:yb(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function T$(e,t){let i=ip(e,x$,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:A$(i.path,`${t} path`),kind:i.kind}}function I$(e,t){let i=ip(e,R$,`Conflict radar change ${t}`),r=rp(i.name,`Conflict radar change ${t} name`,lt.maxNameBytes);if(!wb.test(r))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${r} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${r} specs must be an array`);if(i.specs.length>lt.maxSpecsPerChange)throw new Error(`Conflict radar change ${r} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${r} declared artifacts must be an array`);if(i.declaredArtifacts.length>lt.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>_$(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>pa(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${r} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>T$(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>pa(c.path,l.path)||pa(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${r} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:yb(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function j$(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>lt.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(I$).sort((n,a)=>pa(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>lt.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>lt.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function $$(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function O$(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),r=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function H$(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function D$(e,t){let i=[],r=b$("sha256").update(`${E$}
|
|
200
|
-
[`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(
|
|
201
|
-
`,"utf8")}function
|
|
202
|
-
${
|
|
203
|
-
`),e.omissionOverflow&&
|
|
204
|
-
`);let i=0;lp(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){Sr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)ss(o,n.path)&&(a+=1,Sr(t,"change-attribution",o));Sr(t,"change-end",{attributionCount:a}),a===0&&Sr(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&Sr(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function Db(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=Z$(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let R=new Set(i.externalDrift.paths),N=new Set(o.changePaths),w=i.externalDrift.paths.filter(P=>!N.has(P)||n.some(F=>ss(F,P)));if(w.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${w.slice(0,8).join(", ")}`);if(R.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=D(rs,e),c=D(rs,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[R,N]of[["baseline",e],["current",t]])for(let w of N.omitted){if(l.length>=q$)break;l.push($i({kind:"snapshot-omission",source:R,path:w.path,evidence:{reason:w.reason,size:w.size,type:w.type}},`${R} snapshot omitted ${w.path}: ${w.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...Sb("baseline",e),...Sb("current",t),...o.totalChanges===0&&a===null?[$i({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],h=()=>{if(i.gitChangedPaths===void 0)return;let R=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(N=>R.has(N)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(N=>!R.has(N))}},v=R=>{let N=o.candidates.slice(0,R.detailedChangeCount),w=N.filter(Bt=>Bt.attributedTo.length===0&&!u.has(Bt.path)),P=o.totalChanges-N.length,F=o.totalUnattributed-w.length,$=d-R.detailedOmissionCount,Le=F+$,le=[...w.map(Bt=>$i({kind:"unattributed-change",source:"implementation-scope",path:Bt.path,evidence:{after:Bt.after,before:Bt.before,changeKind:Bt.kind}},`Changed path is not covered by a declared artifact: ${Bt.path}`)),...l.slice(0,R.detailedOmissionCount),...f,...Le>0?[Hb(R.overflowHash,{changes:P,unattributed:F,unresolved:Le})]:[]],ee=X$(le),ni=R.includeGitAdvisory?h():void 0;return{schema:np,contractHash:r,baselineProjectionRef:ap(s),baselineProjectionHash:s,currentProjectionRef:ap(c),currentProjectionHash:c,complete:ee.length===0,declaredArtifacts:n,changes:N,unattributed:w,unresolvedScopes:ee,noCodeReason:a,...ni?{gitAdvisory:ni}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},m=o.candidates.length,p=l.length,b=i.gitChangedPaths!==void 0,g="0".repeat(64);for(;;){let R=v({detailedChangeCount:m,detailedOmissionCount:p,includeGitAdvisory:b,overflowHash:g});if(as({...R,scopeHash:g})<=fn)break;if(b){b=!1;continue}if(p>0){p-=Math.max(1,Math.ceil(p/4));continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let E=o.totalChanges>m||d>p?tO({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:m,detailedOmissionCount:p}):g,k=v({detailedChangeCount:m,detailedOmissionCount:p,includeGitAdvisory:b,overflowHash:E}),S={...k,scopeHash:D(_b,k)};if(as(S)>fn)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return S}function dp(e){let t=op(e.baseline),i=op(e.current),r=Ob(e);return{authority:r,baseline:t,current:i,scope:Db(t,i,r)}}var iO=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function vi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function gi(e,t,i,r){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function dn(e,t){if(typeof e!="string"||!cp.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Pb(e,t,i){let r=ap(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function va(e,t){let i=vi(e,"Native snapshot projection");if(gi(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==Ab)throw new Error("Native snapshot projection schema is invalid");let r=Ti({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),n=op(r);if(D(rs,i)!==D(rs,n))throw new Error("Native snapshot projection is not canonical");let a=D(rs,n);if(t!==void 0&&dn(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function fp(e,t){let i=vi(e,`Declared artifact ${t}`);if(gi(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Er(i.path,`Declared artifact ${t} path`),kind:i.kind}}function Rb(e,t){if(e===null)return null;let i=vi(e,t);return gi(i,["hash","size"],[],t),{hash:dn(i.hash,`${t} hash`),size:ma(i.size,`${t} size`)}}function Cb(e,t){let i=vi(e,`Implementation change ${t}`);if(gi(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let r=i.attributedTo.map(fp),n=os(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Rb(i.before,`Implementation change ${t} before`),o=Rb(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:Er(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function rO(e,t){let i=vi(e,`Unresolved scope ${t}`);gi(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let r=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!r.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?Tb(i.path,`Unresolved scope ${t} path`):Er(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function ns(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((n,a)=>Er(n,`${t} ${a}`)),r=[...new Set(i)].sort(Je);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function Mb(e){let t=vi(e,"Native implementation external drift");if(gi(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=ns(t.paths,"Native external drift paths");return $b({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function ga(e){let t=vi(e,"Native implementation scope"),i=[...iO].filter(w=>w!=="gitAdvisory"&&w!=="externalDrift");if(gi(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==np)throw new Error("Native implementation scope schema is invalid");let r=dn(t.contractHash,"Implementation scope contractHash"),n=dn(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=Pb(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=dn(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=Pb(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(fp);if(JSON.stringify(c)!==JSON.stringify(os(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Cb),u=[...l].sort((w,P)=>Je(w.path,P.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(P=>!d.has(`${P.kind}:${P.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(P=>ss(P,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Cb),h=t.externalDrift===void 0?void 0:Mb(t.externalDrift),v=new Set(h?.paths??[]),m=l.filter(w=>w.attributedTo.length===0&&!v.has(w.path));if(JSON.stringify(f)!==JSON.stringify(m))throw new Error("Implementation scope unattributed changes are inconsistent");let p=t.unresolvedScopes.map(rO),b=p.filter(w=>w.kind==="scope-detail-overflow");if(b.length>1)throw new Error("Implementation scope has multiple detail overflow records");let g=b[0]===void 0?null:eO(b[0]);if(g&&(g.changes+g.unresolved===0||g.unattributed>g.changes||g.unattributed>g.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let y=t.noCodeReason,E=[...m.map(w=>$i({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(g?.changes??0)===0&&y===null?[$i({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],k=p.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(p)!==JSON.stringify([...p].sort(sp))||new Set(p.map(w=>w.id)).size!==p.length||JSON.stringify(k)!==JSON.stringify(E.sort(sp))||t.complete!==(p.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let S;if(t.gitAdvisory!==void 0){let w=vi(t.gitAdvisory,"Implementation scope Git advisory");if(gi(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let P=ns(w.changedPaths,"Git changed paths"),F=ns(w.pathsPresentInSnapshotChanges,"Git present paths"),$=ns(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),Le=[...F,...$].sort(Je);if(JSON.stringify(Le)!==JSON.stringify(P)||$.some(le=>l.some(ee=>ee.path===le)))throw new Error("Implementation scope Git advisory partition is invalid");S={advisoryOnly:!0,changedPaths:P,pathsPresentInSnapshotChanges:F,pathsAbsentFromSnapshotChanges:$}}let R={schema:np,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:p,noCodeReason:y,...S?{gitAdvisory:S}:{},...h?{externalDrift:h}:{}},N=dn(t.scopeHash,"Implementation scope scopeHash");if(D(_b,R)!==N)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:N}}function nO(e){let t=vi(e,"Native implementation scope authority");if(gi(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(fp);if(JSON.stringify(i)!==JSON.stringify(os(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let r;t.gitChangedPaths!==void 0&&(r=ns(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:Mb(t.externalDrift),a=Ob({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function cs(e){let t=vi(e,"Native implementation scope bundle");gi(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=nO(t.authority),r=va(t.baseline),n=va(t.current),a=ga(t.scope),o=Db(r,n,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:r,current:n,scope:o}}function Lb(e){let t=ga(e.scope);return cs({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}import Fb from"node:path";var aO=/\b(Bearer|Basic)\s+[^\s"']+/giu,oO=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,sO=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,cO=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,lO=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,uO=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,dO=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function jt(e){return e.replace(aO,"$1 [REDACTED]").replace(oO,"[REDACTED PRIVATE KEY]").replace(sO,"$1[REDACTED]@").replace(cO,"[REDACTED TOKEN]").replace(lO,'$1"[REDACTED]"').replace(uO,"$1$2$1$3$4[REDACTED]$4").replace(dO,"$1$2[REDACTED]")}var Vb=/^[a-f0-9]{64}$/u;var fO="comet.native.acceptance-trace.v2",hO="comet.native.partial-allowance.v1",pO="comet.native.verification-evidence.v2";function Oi(e,t){if(!Vb.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function qb(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Wb(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function hp(e,t,i=2e3){let r=jt(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function ls(e,t){let i=Fb.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||Fb.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function mO(e,t,i){let r=ls(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=si(r),a=r.toLowerCase(),o=i?ls(i,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${r}`);return r}function pp(e){let t=ls(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function wa(e,t){return e<t?-1:e>t?1:0}function Xl(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ql(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function zb(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function Bb(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let r=`runtime/evidence/${t}/${i}.json`;if(e!==r)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function vO(e){let t=Xl(e,"Native acceptance trace");if(Ql(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!Vb.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let i=ls(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=Xl(o,`Native acceptance trace entry ${s}`);if(Ql(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>pp(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(wa))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:ls(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:hp(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>wa(o.acceptanceId,s.acceptanceId)))||new Set(r.map(o=>o.acceptanceId)).size!==r.length||t.total!==r.length||t.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==r.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:r},a=Oi(t.traceHash,"Native acceptance trace hash");if(D(fO,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function Zl(e){let t=Xl(e,"Native partial allowance");if(Ql(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(wa))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:Wb(t.change),scopeHash:Oi(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:hp(t.reason,"Partial allowance reason"),confirmedSummary:hp(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:qb(t.sourceRevision),confirmedAt:zb(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let r=Oi(t.allowanceHash,"Native partial allowance hash");if(D(hO,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function us(e){let t=Xl(e,"Native verification evidence");if(Ql(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=Oi(t.implementationScopeHash,"Native verification implementation scope hash"),r=vO(t.acceptanceTrace),n=Oi(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(r.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:Oi(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>pp(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(wa)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(wa);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>pp(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(wa)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:Wb(t.change),sourceRevision:qb(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Oi(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:Bb(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:mO(t.reportRef,"Native verification report ref"),reportHash:Oi(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:Bb(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:zb(t.createdAt,"Native verification timestamp")},d=Oi(t.envelopeHash,"Native verification envelope hash");if(D(pO,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import Jb from"node:path";var Gb="comet.native.check-receipt.v1",gO="comet.native.check-receipt.v1",ya="scoped-text-safety",mp=1,ut=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),wO=/^[a-f0-9]{64}$/u,yO=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,NO="comet.native.checker-policy.v1",bO="comet.native.check-input.v1",kO=2048,Ub=D(NO,{policy:ya,version:mp,limits:ut,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),SO=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),Kb=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],Xb=["contract-before-does-not-match-scope","implementation-before-does-not-match-scope","contract-changed-during-check","implementation-changed-during-check","contract-after-does-not-match-scope","implementation-after-does-not-match-scope"],EO=new Set(Xb);function Pr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Rr(e,t,i,r=[]){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function Hi(e,t){if(typeof e!="string"||!wO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function kt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Qb(e,t){let i=kt(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function Yb(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function PO(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>kO||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=Jb.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Jb.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function RO(e){let t=Pr(e,"Native check receipt checker");Rr(t,["policy","version","hash","limits"],"Native check receipt checker");let i=Pr(t.limits,"Native check receipt limits");if(Rr(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==ya||t.version!==mp||t.hash!==Ub||i.maxFiles!==ut.maxFiles||i.maxFileBytes!==ut.maxFileBytes||i.maxTotalBytes!==ut.maxTotalBytes||i.maxIssues!==ut.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:ya,version:mp,hash:Ub,limits:{...ut}}}function CO(e){let t=Pr(e,"Native check receipt contract");return Rr(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Hi(t.expectedHash,"Native check expected contract hash"),beforeHash:Hi(t.beforeHash,"Native check before contract hash"),afterHash:Hi(t.afterHash,"Native check after contract hash")}}function xO(e){let t=Pr(e,"Native check receipt implementation");return Rr(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Hi(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Hi(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Hi(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Hi(t.afterSnapshotHash,"Native check after snapshot hash")}}function AO(e,t){let i=Pr(e,`Native check batch ${t}`);Rr(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:kt(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:kt(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:kt(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:kt(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:kt(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:kt(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>ut.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>ut.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function _O(e){let t=Pr(e,"Native check receipt counts");Rr(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:kt(t.filesSelected,"Native check filesSelected"),filesScanned:kt(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:kt(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:kt(t.bytesScanned,"Native check bytesScanned"),issueCount:kt(t.issueCount,"Native check issueCount"),recordedIssueCount:kt(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(AO):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>ut.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>ut.maxFiles||i.bytesScanned>ut.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function TO(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||Kb.indexOf(e.kind)-Kb.indexOf(t.kind)}function IO(e){if(!Array.isArray(e)||e.length>ut.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=Pr(r,`Native check issue ${n}`);if(Rr(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!SO.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:PO(a.path,`Native check issue ${n} path`),line:Qb(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(TO);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function jO(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!EO.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=Xb.filter(r=>t.includes(r));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function $O(e){return D(bO,e)}function eu(e){let t=Pr(e,"Native check receipt");if(Rr(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Gb)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!yO.test(t.change))throw new Error("Native check receipt change name is invalid");let i=Qb(t.sourceRevision,"Native check source revision"),r=RO(t.checker),n=CO(t.contract),a=xO(t.implementation),o=$O({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Hi(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=Yb(t.startedAt,"Native check receipt startedAt"),c=Yb(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=_O(t.counts),u=IO(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=jO(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>ut.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>ut.maxFiles&&!u.some(m=>m.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let h={schema:Gb,change:t.change,sourceRevision:i,checker:r,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},v=Hi(t.receiptHash,"Native check receipt content hash");if(D(gO,h)!==v)throw new Error("Native check receipt content hash mismatch");return{...h,receiptHash:v}}var gp="comet.native.verification-receipt.v3",OO=gp,HO="comet.native.declared-artifacts.v1",DO=/^[a-f0-9]{64}$/u,MO=/^acceptance-[a-f0-9]{64}$/u,LO=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,FO=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,BO=4096,VO=256,qO=1024;function Na(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function Cr(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function Di(e,t){if(typeof e!="string"||!DO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ti(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=jt(e).trim();if(!i||i.length>BO||i!==e.trim())throw new Error(`${t} is invalid`);return i}function vp(e,t){let i=ti(e,t),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function ds(e,t,i=ti,r=!1,n=VO){if(!Array.isArray(e)||e.length>n||!r&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function WO(e,t){if(typeof e!="string"||!MO.test(e))throw new Error(`${t} is invalid`);return e}function zO(e){let t=Na(e,"Native verification receipt bindings");if(Cr(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!LO.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:Di(t.contractHash,"Native verification receipt contract hash"),scopeHash:Di(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Di(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Di(t.artifactHash,"Native verification receipt artifact hash")}}function JO(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=FO.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function GO(e,t,i,r){let n=Na(t,`Native ${e} evidence`);if(e==="automated-check"){if(Cr(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=vp(n.startedAt,"Native automated-check start time"),o=vp(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(i==="passed"&&n.exitCode!==0||i==="failed"&&n.exitCode===0||i==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=Na(n.worktree,"Native automated-check worktree");if(Cr(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=Na(n.afterFence,"Native automated-check after fence");if(Cr(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:ti(n.executable,"Native automated-check executable"),args:ds(n.args,"Native automated-check arguments",ti,!0),cwd:ti(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:ti(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Di(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Di(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Di(n.outputHash,"Native automated-check output hash"),outputSummary:ti(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){Cr(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=JO(n.checkReceiptRef);if(Di(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:ds(n.subjects,"Native static inspection subjects",ti,r==="required-check"),rule:ti(n.rule,"Native static inspection rule"),resultSummary:ti(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return Cr(n,["steps","observations"],"Native manual-evidence evidence"),{steps:ds(n.steps,"Native manual evidence steps"),observations:ds(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function UO(e){let t=Na(e,"Native verification receipt");if(Cr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let i=t.kind,r=t.role,n=t.status,a=ti(t.actor,"Native verification receipt actor"),o=ds(t.acceptanceIds,"Native receipt acceptance IDs",WO,r==="required-check",qO).sort();if(r==="required-check"&&o.length!==0||r==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(r==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:gp,kind:i,role:r,status:n,bindings:zO(t.bindings),acceptanceIds:o,actor:a,issuedAt:vp(t.issuedAt,"Native verification receipt issue time"),evidence:GO(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==ya||s.actor!==`native-runtime:${ya}`))throw new Error("Native required check policy identity is invalid");return s}function tu(e){let t=Na(e,"Native verification receipt");if(Cr(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==gp)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=UO(r),a=Di(t.receiptHash,"Native verification receipt hash");if(D(OO,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function wp(e){return D(HO,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var ik=/^[a-f0-9]{64}$/u,xr=fn,tz=3*xr;function yp(e,t){let i=wi.relative(e,t);return i===""||!wi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${wi.sep}`)}function YO(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function iu(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return mt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Zb(e){let t=await ii.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await ii.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function XO(e,t){let i=wi.resolve(e),r=wi.resolve(t);if(!yp(i,r))throw new Error("Native evidence path is outside its change");let n=[await Zb(i)],a=i;for(let o of wi.relative(i,r).split(wi.sep).filter(Boolean)){a=wi.join(a,o);let s=await Zb(a);if(!yp(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function ek(e){for(let t of e){let i=await ii.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!YO(t,i)||await ii.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function QO(e,t,i={}){let r=await XO(t,wi.dirname(e));await i.afterParentChainCaptured?.();let n=await ii.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await ii.realpath(e);if(!yp(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await ii.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),ii.lstat(e),ii.realpath(e)]);if(await ek(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!iu(s,n)||!iu(s,c))throw new Error("Native evidence document changed while opening");if(s.size>xr)throw new Error(`Native evidence document exceeds ${xr} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let p=xr+1-d,b=await o.read(f,0,Math.min(f.length,p),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,d>xr)throw new Error(`Native evidence document exceeds ${xr} bytes`);u.push(Buffer.from(f.subarray(0,b.bytesRead)))}await i.beforeFinalCheck?.();let[h,v,m]=await Promise.all([o.stat(),ii.lstat(e),ii.realpath(e)]);if(await ek(r),!v.isFile()||v.isSymbolicLink()||m!==a||!iu(s,h)||!iu(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function ka(e,t){if(!ik.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function rk(e){return ka("reports",e)}async function ZO(e,t,i,r,n){if(!ik.test(i))throw new Error("Native report evidence hash is invalid");let a=await hn({paths:e,name:t,kind:"reports",hash:i,hooks:r,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||KO("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function ba(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function e0(e,t,i,r,n){let a=ka(i,r);return n?wi.join(n,...a.split("/")):sr(H(e,t),a)}async function hn(e){let t=e0(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??j(e.paths,t);return await T(i,t),QO(t,i,e.hooks)}function tk(e,t){return va(e,t)}function t0(e,t){let i=ga(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function i0(e,t,i){let r=Zl(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function r0(e,t,i){let r=us(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function n0(e,t,i,r=!1,n){let a=await ru(e,t,i.implementationScopeRef,void 0,n);if(r&&await ZO(e,t,i.reportHash,void 0,n),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await nk(e,t,i.partialAllowanceRef,void 0,n);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function fs(e,t,i,r,n){let a=ba(i,"scopes"),o=t0(await hn({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=ba(o.baselineProjectionRef,"snapshots"),c=ba(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([hn({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>tk(d,s)),hn({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>tk(d,c))]);return Lb({baseline:l,current:u,scope:o})}async function ru(e,t,i,r,n){return(await fs(e,t,i,r,n)).scope}async function nk(e,t,i,r,n){let a=ba(i,"allowances");return i0(await hn({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function hs(e,t,i,r,n){let a=ba(i,"receipts"),o=tu(await hn({paths:e,name:t,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function Sa(e,t,i,r,n){let a=ba(i,"verifications"),o=r0(await hn({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await n0(e,t,o,!1,n),o}var a0=4096;async function o0(e,t=lt.maxChanges){try{let i=await gt({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function ak(e,t){let i=await Oe(e,t),[r,n]=await Promise.all([i.implementation_scope?ru(e,t,i.implementation_scope):null,bt(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:r?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function nu(e,t,i={}){let n=(await o0(e,a0)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await ak(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await ak(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=Nb([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{promises as S0}from"fs";import E0 from"path";import{isDeepStrictEqual as ou}from"util";var Ea={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var s0=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function c0(e,t){return e<t?-1:e>t?1:0}function l0(e,t,i,r){if(!Array.isArray(e)||e.length>i||!r&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!s0.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(c0)}function Np(e=[]){return l0(e,"Native repair failed check IDs",Ea.maxFailedCheckIds,!0)}function ok(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function u0(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:ok(e.failedAcceptanceIds,t.failedAcceptanceIds)&&ok(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function bp(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(u0(r,a))break;i+=1,r=a}return i}function kp(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var sk="repairStagnation",St={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},f0=/^[a-f0-9]{64}$/u;var h0=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),p0=["data","runId","sequence","timestamp","type"],ck=["disposition","overrideSummaryHash","signatureHash"],m0=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],lk=12;function Ep(e,t){return e<t?-1:e>t?1:0}function uk(e,t,i){let r=Object.keys(e).sort(Ep);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function au(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function ps(e,t){if(typeof e!="string"||!f0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function v0(e){if(!Array.isArray(e)||e.length>Ea.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(Ep)}function dk(e){if(typeof e!="string"||e.length===0||e.length>St.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Sp(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>St.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>St.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>St.maxTextCharacters&&(!n||e.length>St.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>St.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${r} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>St.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>Sp(s,t+1,i,`${r}[${c}]`));return}let a=au(e,r),o=Object.keys(a);if(o.length>St.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>St.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>St.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Sp(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function g0(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function w0(e,t,i){let r=au(e,`Native repair trajectory event ${t+1}`);if(uk(r,p0,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(g0(r.timestamp),typeof r.type!="string"||!h0.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(dk(r.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Sp(r.data,0,n,"Native trajectory event data"),au(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function Pp(e){let t=au(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Ep),r=i.length===ck.length&&i.every((l,u)=>l===ck[u]);r||uk(t,m0,"Native repair trajectory projection");let n=ps(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:ps(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(r)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=ps(t.contractHash,"Native repair trajectory contract hash"),s=v0(t.failedAcceptanceIds),c=Np(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function y0(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function N0(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??lk;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=bp({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<Ea.warningAtConsecutiveFailures?"continue":a<Ea.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function b0(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??lk;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||r.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function fk(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>St.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=dk(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],r=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=w0(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>St.maxTotalDataNodes||c>St.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,h=Object.hasOwn(f,"repairScopeHash")?ps(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?ps(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,sk)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(h!==null&&n!==null&&h!==n||h===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=h,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=Pp(f[sk]);if(y0(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(i.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&h!==null&&n!==null&&h!==n&&(i.length=0,o=0),h!==null&&(n=h),N0(v,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(r?.contractHash===null&&h!==null&&n!==null&&h!==n)throw new Error("Native repair override cannot cross implementation scope progress");b0(v,i,r);let m=i.at(-1);if(!m||m.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:m.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>Ea.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function hk(e){return fk(e).history}function pk(e){let t=fk(e).latestProjection;return t?{...t}:null}var yi={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},ms=M("comet-native-runtime:v3:scope-reopen"),k0=[{skillVersion:"3",skillHash:M("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:M("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:M("comet-native-runtime:v1")}];function mk(e){return e.skillVersion===yi.definition.metadata.version&&e.skillHash===ms||k0.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var Rp={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function Ar(e){let i={sequence:(await tt(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await ON(e.changeDir,e.run.trajectoryRef,i),i}async function pn(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:M(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await HN(e.changeDir,e.run.checkpointRef,t),t}function vk(e){return M(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var Ek=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],P0=new Set(Ek),Pk=new Set([...Ek,"minimum_runtime_version","revision"]),R0=new Set([...Pk,"operation"]),C0=512*1024,Cp=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),x0=new Set([...Cp,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),vs=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Ge(e,t){return E0.join(H(e,t),"transition.json")}function A0(e){return`transition-${e}`}async function _0(e,t,i){let r=A0(t);return lr(e,r,i)}async function mn(e,t,i,r){let n=await _0(e,t,i);try{return await r()}finally{await ur(n)}}function cu(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Ap(e,t){let i=Object.keys(e).find(r=>!t.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function su(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ni(e,t){return ou(e,t)}function xp(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,r=Object.keys(i),n=r.find(u=>!x0.has(u)),a=[...Cp].find(u=>!Object.hasOwn(i,u)),o=Cp.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0)+(Object.hasOwn(i,"returnToBuild")?1:0);if(n||a||r.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(i.returnToBuild!==void 0&&typeof i.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(kp(i.summary,"Native transition journal event summary"),jt(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(kp(i.noCodeReason,"Native transition journal event no-code reason"),jt(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?Pp(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...i.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function T0(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,r=Object.keys(i),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(r.length===n.size&&r.every(a=>n.has(a))&&i.reason==="spec-rebase")return xp({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return xp(e,t)}function _p(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let r=i?T0(e.eventData,e.evidenceHash):xp(e.eventData,e.evidenceHash),n=kr(e.nextRun),a=e.previousRun===null?null:kr(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function gk(e,t,i=!1){if(e.skill!==yi.definition.metadata.name||(i?!mk(e):e.skillVersion!==yi.definition.metadata.version||e.skillHash!==ms)||e.orchestration!==yi.definition.orchestration.mode||e.pendingRef!==yt.pendingRef||e.trajectoryRef!==yt.trajectoryRef||e.contextRef!==yt.contextRef||e.artifactsRef!==yt.artifactsRef||e.checkpointRef!==yt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function wk(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function yk(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function Tp(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(gk(o,"next Run",r||a!==null),yk(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(gk(a,"previous Run",!0),yk(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!ou(wk(a),wk(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function I0(e,t,i){return M(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Rk(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Nk(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function Ip(e,t,i,r,n=!1){let a=i.eventData,o=Nk(e),s=Nk(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(r==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&ou(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(r==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&ou(e.spec_changes,t.spec_changes),l=vk({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(r==="spec-rebase"){let c=I0(e.name,a.summary,t.spec_changes),l=M(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&i.evidenceHash!==c||n&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function jp(e,t){let i=cu(e);if(Ap(i,R0),i.schema!==fr)throw new Error(`Expected Native transition schema ${fr}`);let r=su(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(r>3)throw new Error(`Native transition requires runtime protocol ${r}; current protocol is ${3}`);if(r!==3)throw new Error(`Native transition ${fr} minimum_runtime_version must be ${3}`);let n=su(i.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat"&&i.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=_p(i,t),o=ct(i.previousState),s=ct(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(Ip(o,s,a,i.operation),Tp(o,s,a,!1,i.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:fr,minimum_runtime_version:3,revision:n,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function j0(e,t){let i=cu(e);if(Ap(i,P0),i.schema!==rn)throw new Error(`Expected Native transition schema ${rn}`);let r=_p(i,t,!0),n=nn(i.previousState),a=nn(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return Ip(n,a,r,Rk(n,a,r.eventData),!0),Tp(n,a,r,!0),{schema:rn,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function $p(e,t){let i=cu(e);if(Ap(i,Pk),i.schema!==_i)throw new Error(`Expected Native transition schema ${_i}`);if(su(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${_i} minimum_runtime_version must be 2`);let n=su(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=_p(i,t,!0),o=ui(i.previousState),s=ui(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(Ip(o,s,a,Rk(o,s,a.eventData),!0),Tp(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:_i,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function $0(e,t){let i=cu(e);if(i.schema===fr)return{status:"current",journal:jp(i,t)};if(i.schema===rn)return{status:"migration-required",journal:j0(i,t)};if(i.schema===_i)return{status:"migration-required",journal:$p(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function Op(e,t){let i=Ge(e,t),r=j(e,i);await T(r,i);try{let n=await ie({root:r,file:i,maxBytes:C0,label:`Native transition journal ${t}`});return $0(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Mi(e,t){let i=await Op(e,t);if(!i)return null;if(i.status==="migration-required")throw new vs(t);return i.journal}function bk(e,t){if(Ni(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(Ni(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function kk(e,t){if(Ni(e,t.nextState))return"next";if(Ni(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function O0(e){let{journal:t}=e;return Ck({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function Ck(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function Sk(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),r=i.filter(({event:a})=>a.type==="run_started"),n=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==r.length+n.length||r.length>(t.previousRun===null?1:0)||n.length>1||t.previousRun===null&&n.length===1&&(r.length!==1||r[0].index>=n[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...r,...n]){let o=O0({sequence:a.index+1,journal:t,type:a.event.type});if(!Ni(Ck(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:r[0]?.event??null,transitioned:n[0]?.event??null}}async function lu(e,t,i){if(await fa(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Fl(e,t);let r=await Mi(e,t);if(!r)return null;let n=H(e,t),a=Sk(await tt(n,r.nextRun.trajectoryRef),r),[o,s]=await Promise.all([je(n),Oe(e,t)]),c=bk(o,r),l=kk(s,r);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${r.change}; recovery journal was preserved`);if(c==="previous"&&(await cn(n,r.nextRun),await i?.afterRunStateWritten?.(r)),!Ni(await je(n),r.nextRun))throw new Error(`Native transition Run content changed while continuing ${r.change}; recovery journal was preserved`);if(l==="previous"){let p=await Ul(e,r.nextState,r.previousState.revision);if(!Ni(p,r.nextState))throw new Error(`Native transition change write diverged for ${r.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(r)}if(!Ni(await Oe(e,t),r.nextState))throw new Error(`Native transition change content changed while continuing ${r.change}; recovery journal was preserved`);let u=await Mi(e,t);if(!u||!Ni(u,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was preserved`);let d=Sk(await tt(n,r.nextRun.trajectoryRef),r);r.previousRun===null&&(d.started||await Ar({changeDir:n,run:r.nextRun,type:"run_started",data:{runtime:"comet-native",phase:r.previousState.phase,transitionId:r.id},now:new Date(r.createdAt)}));let f=d.transitioned;f||(f=await Ar({changeDir:n,run:r.nextRun,type:"state_transitioned",data:{...r.eventData,transitionId:r.id},now:new Date(r.createdAt)})),await pn({changeDir:n,run:r.nextRun,trajectoryOffset:f.sequence,evidenceHash:r.evidenceHash,now:new Date(r.createdAt)});let[h,v]=await Promise.all([je(n),Oe(e,t)]);bk(h,{...r,previousRun:r.nextRun}),kk(v,{...r,previousState:r.nextState});let m=await Mi(e,t);if(!m||!Ni(m,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was not removed`);return await S0.rm(Ge(e,t),{force:!0}),r.nextState}async function xk(e,t,i){return oe(e,`continue transition ${t}`,()=>mn(e,t,`continue transition ${t}`,()=>lu(e,t,i)))}import Ak from"node:path";var H0="comet.native.contract.v1",D0="comet.native.acceptance-set.v1",_k=/^[a-f0-9]{64}$/u,gs={maxAcceptanceCriteria:Oo.maxCriteria};function Tk(e,t){let i=Ak.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||Ak.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function Ik(e){return D("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
|
|
205
|
-
`))}function M0(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(_k))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(_k))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=Tk(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Ik(e.markdown)},markdown:e.markdown}}function L0(e,t){return jk(e.id,t.id)}function jk(e,t){return e<t?-1:e>t?1:0}function $k(e){let t=Tk(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(M0).sort((d,f)=>jk(d.snapshot.capability,f.snapshot.capability)),r=i.map(({snapshot:d})=>d.capability);if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=sl(e.briefMarkdown,t,gs.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...cl(f,d.source,gs.maxAcceptanceCriteria-a.length)),a.push(...Ey(f,d.source,gs.maxAcceptanceCriteria-a.length)));if(a.sort(L0),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>gs.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${gs.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:Ik(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=D(D0,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:D(H0,u)}}var uu={maxSpecs:64,maxFileBytes:bo,maxTotalBytes:4*1024*1024};async function Pa(e){if(e.specChanges.length>uu.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await Q({root:e.changeDir,ref:e.briefRef,maxBytes:uu.maxFileBytes}),i=t.size,r=[];for(let n of e.specChanges){if(n.operation==="remove"){r.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await Q({root:e.changeDir,ref:n.source,maxBytes:uu.maxFileBytes});if(i+=a.size,i>uu.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");r.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:$k({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import{execFile as nH}from"node:child_process";import{promisify as aH}from"node:util";var rJ=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");import{promises as J0}from"fs";import Ra from"path";var Tr={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},Ca=/^[a-f0-9]{64}$/u;function du(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function fu(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function _r(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function Ok(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Hp(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function F0(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||Ra.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=Ra.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function Dp(e,t){return Ra.join(H(e,t),"checkpoints","progress.json")}function Ir(e,t){return Ra.join(H(e,t),"checkpoint-journal.json")}function Mp(e,t,i){if(!Ca.test(i))throw new Error("Native checkpoint manifest hash is invalid");return Ra.join(H(e,t),"checkpoints","manifests",`${i}.json`)}function B0(e){if(!Ca.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Lp(e,t,i){let r=await ie({root:e,file:t,maxBytes:Tr.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function V0(e,t){let i=du(e,`checkpoint manifest artifact ${t}`);fu(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=F0(_r(i.path,`checkpoint artifact ${t} path`,4096)),n=si(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!Ca.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:Hp(i.size,`checkpoint artifact ${t} size`)}}function hu(e,t){let i=du(e,"Native checkpoint manifest");if(fu(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>Tr.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(V0),n=[...r].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(r.map(o=>o.path)).size!==r.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Hp(i.totalBytes,"checkpoint manifest totalBytes");if(r.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>Tr.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:r,totalBytes:a}}function Fp(e){return M(JSON.stringify(hu(e,e.change)))}function Bp(e,t){let i=du(e,"Native progress checkpoint");if(fu(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let r=i.phase;if(r!=="shape"&&r!=="build"&&r!=="verify"&&r!=="archive")throw new Error("Native checkpoint phase is invalid");let n=Ok(i.previousRevision,"Native checkpoint previousRevision"),a=Ok(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=_r(i.manifestHash,"Native checkpoint manifestHash",64);if(!Ca.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=B0(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=_r(i.inputHash,"Native checkpoint inputHash",64);if(!Ca.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=_r(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Hp(i.artifactCount,"Native checkpoint artifactCount");if(u>Tr.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=_r(i.summary,"Native checkpoint summary"),f=_r(i.nextAction,"Native checkpoint nextAction");if(jt(d)!==d||jt(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:_r(i.id,"Native checkpoint id",128),change:t,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function q0(e,t){let i=du(e,"Native checkpoint journal");if(fu(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let r=ct(i.previousState),n=ct(i.nextState),a=Bp(i.checkpoint,t),o=hu(i.manifest,t),s=_r(i.inputHash,"Native checkpoint journal inputHash",64),c=M(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Ca.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(r.name!==t||n.name!==t||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==Fp(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:r,nextState:n,checkpoint:a,manifest:o}}async function W0(e,t,i){let r=Ra.resolve(e.projectRoot,...t.split("/"));if(!O(e.projectRoot,r)||O(e.nativeRoot,r)||O(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=Gf(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await ie({root:e.projectRoot,file:r,maxBytes:Tr.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function z0(e,t){let i=Dp(e,t),r=j(e,i);await T(r,i);try{return Bp(await Lp(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Vp(e,t,i){let r=Mp(e,t,i),n=j(e,r);await T(n,r);let a=await Lp(n,r,"Native checkpoint manifest"),o=hu(a,t);if(qp(e,o),Fp(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function jr(e,t){let i=Ir(e,t),r=j(e,i);await T(r,i);try{let n=q0(await Lp(r,i,"Native checkpoint journal"),t);return qp(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Hk(e,t,i,r){let n=hu(i,t);qp(e,n);let a=Fp(n),o=Mp(e,t,a),s=j(e,o);await T(s,o);try{let c=await Vp(e,t,a);if(JSON.stringify(c)!==JSON.stringify(n))throw new Error("Native checkpoint manifest hash collision")}catch(c){if(c.code!=="ENOENT")throw c}return await Z(o,n,{containedRoot:s,beforeCommit:r?.beforeCommit}),a}function qp(e,t){for(let i of t.artifacts){let r=Gf(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function Dk(e,t){let i=Bp(t,t.change),r=await Vp(e,i.change,i.manifestHash),n=M(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:r.artifacts}));if(i.inputHash!==n||i.artifactCount!==r.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=Dp(e,t.change),o=j(e,a);await T(o,a),await Z(a,i,{containedRoot:o})}async function Mk(e){let t;try{t=await z0(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:Dp(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await Vp(e.paths,e.name,t.manifestHash);let a=M(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await W0(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:Mp(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}async function Lk(e,t,i){let r=await jr(e,t);if(!r)return null;if(await Hk(e,r.change,r.manifest)!==r.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Ul(e,r.nextState,r.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(r),await Dk(e,r.checkpoint),await i?.afterProgressWritten?.(r),await J0.rm(Ir(e,t),{force:!0}),r}async function Fk(e,t,i){return oe(e,`continue checkpoint ${t}`,()=>mn(e,t,`continue checkpoint ${t}`,async()=>(await lu(e,t),Lk(e,t,i))))}import{constants as Wp,promises as $t}from"node:fs";import xa from"node:path";var G0=/^[a-f0-9]{64}$/u,U0=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,ws=512*1024;function K0(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function pu(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return mt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Y0(e,t){let i=xa.resolve(e),r=xa.resolve(t);if(!O(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",...xa.relative(i,r).split(xa.sep).filter(Boolean)]){o&&(a=xa.join(a,o));let s=await $t.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await $t.realpath(a);if(n.length>0&&!O(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function Bk(e){for(let t of e){let i=await $t.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!K0(t,i)||await $t.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function X0(e){if(!G0.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function Q0(e){let t=U0.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function Z0(e,t,i){return sr(H(e,t),X0(i))}async function eH(e,t,i){let r=await Y0(i,xa.dirname(e)),n=await $t.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>ws)throw new Error(`Native check receipt exceeds ${ws} bytes`);let[a,o]=await Promise.all([$t.realpath(t),$t.realpath(e)]);if(!O(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Wp.O_RDONLY|Wp.O_NOFOLLOW|Wp.O_NONBLOCK,c=await $t.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),$t.lstat(e),$t.realpath(e)]);if(await Bk(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!pu(n,l)||!pu(l,u))throw new Error("Native check receipt changed while opening");let f=[],h=0,v=Buffer.allocUnsafe(16*1024);for(;;){let g=ws+1-h,y=await c.read(v,0,Math.min(v.length,g),null);if(y.bytesRead===0)break;if(h+=y.bytesRead,h>ws)throw new Error(`Native check receipt exceeds ${ws} bytes`);f.push(Buffer.from(v.subarray(0,y.bytesRead)))}let[m,p,b]=await Promise.all([c.stat(),$t.lstat(e),$t.realpath(e)]);if(await Bk(r),!p.isFile()||p.isSymbolicLink()||b!==o||!O(a,b)||!pu(l,m)||!pu(l,p))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,h).toString("utf8"))}finally{await c.close()}}async function Vk(e,t,i){let r=Q0(i),n=H(e,t),a=Z0(e,t,r),o=j(e,a);await T(o,a);let s=eu(await eH(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var ys=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var QJ=64*1024;var ZJ=3600*1e3;var eG=aH(nH);var oH=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function qk(e,t){let i=[];for(let r of oH){let n=e.bindings[r],a=t[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function Wk(e){if(e.receipt.kind!=="static-inspection")return null;let t=await Vk(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var $r=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function sH(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function cH(e){let t=sH(e.bundle.baseline),i=await Bh(e.paths,t,{origin:"explicit",now:e.now});return dp({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function Jk(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await fs(e.paths,e.state.name,e.state.implementation_scope),i=await Pa({changeDir:re(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await cH({paths:e.paths,bundle:t,now:e.now}),n=[];return i.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),r!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function Gk(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await Jk(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function lH(e){let t=await Q({root:re(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Ry(t.text)}}function uH(e){let{receipt:t,implementationScope:i}=e,r=[],n=up({baseline:i.baseline,current:i.current,declaredArtifacts:i.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function dH(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:wp(e.implementationScope.scope.declaredArtifacts)}}async function zk(e){let t=await hs(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=qk(t,e.expectedBindings);if(i.push(...r.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new $r([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await Wk({paths:e.paths,state:e.state,receipt:t});if(n){let a=uH({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function fH(e){let t=dH({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await zk({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof $r)return i.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let r of e.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await zk({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof $r)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(r.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new $r(i)}function zp(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function mu(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:zp(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([Jk(e),Sa(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:zp(e.state.verification_result,"stale"),envelope:null};let r=await lH({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await fH({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:zp(e.state.verification_result,"invalid"),envelope:null}}}function pH(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function Kk(e){try{return await hH.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function mH(e,t){try{return(await Q({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function vH(e,t,i){let r=Kl(e,i.capability);if(!O(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=Uk.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await mH(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await Q({root:re(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function gH(e,t){return Kk(Ge(e,t))}async function vu(e){let t=e.now??new Date,i=await Oe(e.paths,e.name),r=await bt(e.paths,e.name),n=await we(e.paths.projectRoot),a=pH(i.name,t),o=Uk.resolve(e.paths.nativeRoot,...a.split("/"));if(!O(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,h]=await Promise.all([Promise.all(i.spec_changes.map(v=>vH(e.paths,i.name,v))),mu({paths:e.paths,state:i,now:t}),nu(e.paths,i.name),fa(e.paths,i.name),ha(e.paths,i.name),gH(e.paths,i.name),Kk(o)]);return pb({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:h,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}import{promises as Jp}from"node:fs";import Li from"node:path";var wH="comet.native.archive-tree.v1",yH={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function Qk(e){let t={...yH,...e};for(let[i,r]of Object.entries(t))if(!Number.isSafeInteger(r)||r<=0)throw new Error(`Native Archive content limit ${i} must be a positive safe integer`);return t}function Yk(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,i)=>t.name.localeCompare(i.name)))}function Xk(e,t,i,r){if(i.entryCount+=1,i.entryCount>r.maxEntries)throw new Error(`Native Archive content exceeds ${r.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>r.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${r.maxRefBytes} bytes: ${t.ref}`);let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(i.manifestBytes+=n+(e.length===0?0:1),i.manifestBytes+2>r.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${r.maxManifestBytes} bytes`);e.push(t)}async function Zk(e,t,i,r,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await gt({root:e,directory:t,label:`Native Archive content directory ${Li.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=Yk(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=Li.join(t,u.name),f=Li.relative(e,d).replaceAll("\\","/"),h=await Jp.lstat(d);if(u.isSymbolicLink()||h.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${f}`);if(u.isDirectory()&&h.isDirectory()){Xk(i,{ref:f,kind:"directory"},r,n),await Zk(e,d,i,r,n,a+1);continue}if(!u.isFile()||!h.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let v=await ie({root:e,file:d,maxBytes:n.maxFileBytes,label:`Native Archive content file ${f}`});if(r.totalBytes+=v.size,r.totalBytes>n.maxTotalBytes)throw new Error(`Native Archive content exceeds ${n.maxTotalBytes} total file bytes`);Xk(i,{ref:f,kind:"file",hash:v.hash,size:v.size},r,n),await o.verify()}await o.verify();let l=await gt({root:e,directory:t,label:`Native Archive content directory ${Li.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(Yk(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${Li.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function eS(e,t={}){let i=Qk(t);e=Li.resolve(e);let r=await Jp.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await Zk(e,e,n,{entryCount:0,totalBytes:0,manifestBytes:0},i,0);let o=JSON.stringify(n);if(Buffer.byteLength(o,"utf8")>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);return M(`${wH}\0${o}`)}async function ri(e,t={}){let i=Qk(t);e=Li.resolve(e);let r;try{r=await Jp.lstat(e)}catch(n){if(n.code==="ENOENT")return null;throw n}if(r.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(r.isFile())return{kind:"file",hash:(await ie({root:Li.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${Li.basename(e)}`})).hash};if(r.isDirectory())return{kind:"directory",hash:await eS(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as it}from"node:fs";import Ce from"node:path";var Up=16*1024*1024,NH=256*1024,bH=16*1024,Ns="comet.native.archive-cas.v1";function kH(e,t){let i="runtime/",r=t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=r?t.slice(i.length):t,o=Ce.resolve(n,...a.split("/"));if(!O(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function He(e,t){let i=kH(e,t);return T(j(e,i),i)}function Or(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function Aa(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function dt(e){let t=await ri(e.target);if(!Or(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${Aa(t)}`);return t}async function Kp(e,t){let i=await fi(e,t),r=await ie({root:e.runtimeDir,file:i.journal,maxBytes:NH,label:`Native Archive transaction journal ${t}`}),n=El(JSON.parse(r.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function gu(e,t,i){let r=El({...t,status:i}),n=await fi(e,r.id);return await Z(n.journal,r,{containedRoot:e.runtimeDir}),r}function wu(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function tS(e){return{...wu(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Hr(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function SH(e,t){return Hr(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function te(e){try{return await it.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function bi(e){let t=await it.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=tS(t),r=await ie({root:j(e.paths,e.file),file:e.file,maxBytes:Up,label:e.label}),n=await it.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!SH(i,tS(n))||r.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:wu(n),size:r.size}}function EH(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${i} record must be an object`);let n=e;if(Object.keys(n).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${i} record has an invalid shape`);let o=n.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${i} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${i} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${i} identity ${c} is invalid`);if(n.schema!==Ns||n.operationId!==t.id||n.role!==i||n.hash!==r)throw new Error(`Archive CAS ${t.id} ${i} record is not transaction-bound`);return{schema:Ns,operationId:t.id,role:i,hash:r,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function ki(e,t,i,r){let n=await fi(e,t.id),a=Ce.join(n.backups,".cas"),o=`.${Ce.basename(r)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:Ce.join(a,`${i.id}.original.json`),postRecord:Ce.join(a,`${i.id}.post.json`),candidate:Ce.join(a,`${i.id}.candidate`),originalQuarantine:Ce.join(Ce.dirname(r),`${o}.original`),rollbackQuarantine:Ce.join(Ce.dirname(r),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>T(j(e,c),c))),s}async function Ot(e){if(!await te(e.file))return null;let t=await ie({root:e.paths.runtimeDir,file:e.file,maxBytes:bH,label:`Archive CAS ${e.operation.id} ${e.role} record`});return EH(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function yu(e){let t=await Ot(e);if(t){if(!Hr(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await di({root:e.paths.runtimeDir,directory:Ce.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:Ns,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await Z(e.file,i,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let r=await Ot(e);if(!r||!Hr(r.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return r}async function Ee(e){let t=await bi({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!Hr(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function PH(e){let t=await bi({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await yu({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Ee({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function RH(e){if(!await te(e.quarantine)||await te(e.target))return;let t=await Xt({root:j(e.paths,e.target),directory:Ce.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await it.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[i,r]=await Promise.all([it.lstat(e.quarantine),it.lstat(e.target)]);if(!Hr(wu(i),wu(r)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await it.unlink(e.quarantine),await t.verify()}async function aS(e){if(await te(e.quarantine)){await Ee({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await Xt({root:j(e.paths,e.target),directory:Ce.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Ee({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await Ee({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await it.rename(e.target,e.quarantine),await t.verify(),await Ee({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await RH(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:i})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function vn(e){if(!await te(e.file))return;await Ee(e);let t=await Xt({root:j(e.paths,e.file),directory:Ce.dirname(e.file),label:e.label});await t.verify(),await Ee(e),await it.unlink(e.file),await t.verify()}async function iS(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let r=await He(e,t.target),n=await He(e,t.backup),a=await ri(n);if(a!==null){if(!Or(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await dt({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await vr({sourceRoot:j(e,r),source:r,targetRoot:j(e,n),target:n,maxBytes:Up,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await dt({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function oS(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let i=await ki(e.paths,e.journal,e.operation,e.target),r=await Ot({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await te(i.originalQuarantine)){if(!r)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Ee({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:r,label:`Archive apply quarantine ${e.operation.target}`}),await iS(e.paths,e.operation,e.hooks),{record:r,quarantine:i.originalQuarantine}}if(!await te(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return r??=await PH({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Ee({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive apply target ${e.operation.target}`}),await iS(e.paths,e.operation,e.hooks),await aS({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:i.originalQuarantine,record:r,hooks:e.hooks}),{record:r,quarantine:i.originalQuarantine}}async function rS(e){let t=await ki(e.paths,e.journal,e.operation,e.target);return await te(t.candidate)?(await bi({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await di({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await vr({sourceRoot:j(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:Up,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function CH(e){let t=e.operation.stagedHash,i=await ki(e.paths,e.journal,e.operation,e.target),r=await Ot({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(r&&await te(e.target))return await Ee({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive write target ${e.operation.target}`}),await te(i.candidate)&&await vn({paths:e.paths,file:i.candidate,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r;if(await te(e.target)){let c=await rS(e),l=await bi({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await bi({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Hr(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return r=await yu({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await vn({paths:e.paths,file:c,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}let n=await rS(e),a=await bi({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await di({root:j(e.paths,e.target),directory:Ce.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await Xt({root:j(e.paths,e.target),directory:Ce.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Ee({paths:e.paths,file:n,operation:e.operation,record:{schema:Ns,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await it.link(n,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await bi({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Hr(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return r=await yu({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await vn({paths:e.paths,file:n,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}async function xH(e,t,i,r){let n=await He(e,i.target),a=await He(e,i.staged);if(await dt({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await ki(e,t,i,n);(!await Ot({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await te(n))&&await oS({paths:e,journal:t,operation:i,target:n,hooks:r})}else{let o=await ri(n);if(o!==null&&!Or(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${Aa(o)}`)}await CH({paths:e,journal:t,operation:i,staged:a,target:n,hooks:r}),await dt({target:n,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function AH(e,t,i,r){let n=await He(e,i.target);await oS({paths:e,journal:t,operation:i,target:n,hooks:r}),await dt({target:n,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function _H(e,t){let i=await He(e,t.source),r=await He(e,t.target),[n,a]=await Promise.all([ri(i),ri(r)]);if(!(n===null&&Or(a,t.expectedSourceHash,"directory"))){if(!Or(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${Aa(n)}, target=${Aa(a)}`);await it.mkdir(Ce.dirname(r),{recursive:!0}),await it.rename(i,r),await dt({target:r,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function TH(e,t,i,r){return i.type==="write"?xH(e,t,i,r):i.type==="remove"?AH(e,t,i,r):_H(e,i)}function IH(e){let t=0,i=!1,r=[];for(let n of e.events){if(n.type!=="operation-started"&&n.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||n.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(n.type==="operation-started"){i=!0;continue}if(!i)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);r.push(a.id),t+=1,i=!1}return r}async function jH(e,t,i,r){let n=await He(e,i.target);if(i.type==="write"){let a=await He(e,i.staged);await dt({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await ki(e,t,i,n),s=await Ot({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!s)throw new Error(`Completed Archive target ${i.target} has no CAS identity`);if(await Ee({paths:e,file:n,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await dt({target:await He(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await Ot({paths:e,file:o.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${i.target} has no original CAS identity`);if(await te(o.originalQuarantine))await Ee({paths:e,file:o.originalQuarantine,operation:i,record:c,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`)}return}if(i.type==="remove"){await dt({target:n,expectedHash:null,label:`Completed Archive target ${i.target}`}),await dt({target:await He(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await ki(e,t,i,n),o=await Ot({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${i.target} has no original CAS identity`);if(await te(a.originalQuarantine))await Ee({paths:e,file:a.originalQuarantine,operation:i,record:o,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`);return}r||(await dt({target:await He(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await dt({target:n,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function sS(e,t,i){let r=t.status==="prepared"?await gu(e,t,"applying"):t;if(r.status!=="applying")throw new Error(`Native Archive transaction ${r.id} cannot apply from ${r.status}`);let n=await wr(e,r.id),a=IH({journal:r,events:n}),o=new Set(a),s=n.some(l=>l.type==="archive-finalization-started");for(let l of r.operations.slice(0,a.length))await jH(e,r,l,s);let c=o.size;for(let l of r.operations)o.has(l.id)||(l.id==="archive-change"&&await i?.beforeArchiveChangeMove?.(l),await _t(e,r.id,"operation-started",l.id),await TH(e,r,l,i),await _t(e,r.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return r=await Kp(e,r.id),r}async function $H(e){try{return await Ee(e),!0}catch{return!1}}async function OH(e){await Ee({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await Xt({root:j(e.paths,e.target),directory:Ce.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Ee({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await it.link(e.quarantine,e.target)}catch(i){throw i.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:i}):i}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await Ee({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function Gp(e){if(e.operation.type!=="write")return;let t=await ki(e.paths,e.journal,e.operation,e.target);if(!await te(t.candidate))return;let i=await bi({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await vn({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:Ns,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function HH(e,t,i,r){let n=await He(e,i.target),a=await ki(e,t,i,n),o=i.expectedTargetHash,s=o===null?null:await Ot({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await Ot({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await te(a.candidate)&&await te(n)){let l=await bi({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await bi({paths:e,file:n,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});Hr(l.identity,u.identity)&&(c=await yu({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await te(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await Ee({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await te(n)&&!(s!==null&&await $H({paths:e,file:n,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await ri(n);if(Or(u,o)){await Gp({paths:e,journal:t,operation:i,target:n});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await aS({paths:e,operation:i,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:r})}if(o===null){if(await te(n))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await te(n)){if(!s||!await te(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await OH({paths:e,operation:i,target:n,quarantine:a.originalQuarantine,record:s,hooks:r})}s&&await te(a.originalQuarantine)&&await vn({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await te(a.rollbackQuarantine)&&await vn({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await Gp({paths:e,journal:t,operation:i,target:n}),await dt({target:n,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function DH(e,t){let i=await He(e,t.source),r=await He(e,t.target),[n,a]=await Promise.all([ri(i),ri(r)]);if(!(Or(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!Or(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${Aa(n)}, target=${Aa(a)}`);await it.mkdir(Ce.dirname(i),{recursive:!0}),await it.rename(r,i)}}async function cS(e,t,i){let r=await wr(e,t.id);if(r.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await gu(e,t,"rolling-back");await _t(e,n.id,"rollback-started");let a=new Set(r.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...n.operations].reverse())a.has(o.id)&&(o.type==="move"?await DH(e,o):await HH(e,n,o,i));return await _t(e,n.id,"rollback-completed"),n=await gu(e,n,"rolled-back"),n}async function nS(e,t,i){let r=await He(e,i.target);if(i.type==="write"){let n=await ki(e,t,i,r),a=await Ot({paths:e,file:n.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!a)throw new Error(`Archive commit target ${i.target} has no CAS identity`);await Ee({paths:e,file:r,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await dt({target:r,expectedHash:null,label:`Archive commit target ${i.target}`})}async function MH(e,t){for(let i of t.operations){if(i.type==="move")continue;let r=await He(e,i.target),n=await ki(e,t,i,r);if(await te(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await nS(e,t,i),i.expectedTargetHash!==null){let a=await Ot({paths:e,file:n.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${i.target} has no original CAS identity`);await te(n.originalQuarantine)&&await vn({paths:e,file:n.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await Gp({paths:e,journal:t,operation:i,target:r})}for(let i of t.operations)i.type!=="move"&&await nS(e,t,i)}async function Nu(e,t,i){return i==="commit"&&await MH(e,t),await _t(e,t.id,i),i==="commit"?gu(e,t,"committed"):t}var UG=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});import{promises as LH}from"fs";import FH from"path";var Yp="comet.selection.v2",BH=16*1024;function bu(e){return FH.join(e,".comet","current-change.json")}function VH(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function lS(e){return e===null||typeof e=="string"}function qH(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!VH(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&&!lS(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Yp,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Yp)throw new Error(`current change selection schema must be ${Yp}`);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(!lS(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 Xp(e){let t;try{let r=bu(e),{bytes:n}=await Qr(r,BH,{label:"current change selection"});t=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...qH(t)}}async function uS(e){await LH.rm(bu(e),{force:!0})}async function dS(e,t,i){let r=await Xp(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await uS(e),!0)}import{promises as Cs}from"node:fs";import Fr from"node:path";var nm=En(Yr(),1);import{promises as AS}from"node:fs";import Ht from"node:path";import{execFileSync as WH}from"node:child_process";var zH=3e4,JH=8*1024*1024,Qp=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function GH(e,t){try{return WH("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:zH,maxBuffer:JH,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new Qp(e,t,r)}}function xe(e,t){return GH(e,t).trim()}function bs(e){return xe(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}import De from"node:path";import{promises as Eu}from"node:fs";import ku from"node:path";function fS(...e){if(e.length===0)return ku.resolve();if(ku.win32.isAbsolute(e[0])){let t=ku.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return ku.resolve(...e)}var Su=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var em="comet.native.supervisor.v2",UH=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function KH(e,t){let i=De.relative(De.resolve(e),De.resolve(t));return i===""||!De.isAbsolute(i)&&!i.startsWith(`..${De.sep}`)}function YH(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function XH(e,t,i){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(i))throw new Error("Native Supervisor parent and child names are invalid");return fS(e,".worktrees",`${t}-${i}`)}function vS(e,t){return De.join(qe(e,t),"supervisor")}function gS(e,t){return De.join(vS(e,t),"state.json")}function wS(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==em)throw new Error(`Native Supervisor state schema must be ${em}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(typeof a!="string"||a.length===0)throw new Error(`Native Supervisor integration field ${n} is invalid`);if(ks(t.integration.targetCommit,"Native Supervisor target commit"),ks(t.integration.headCommit,"Native Supervisor integration head commit"),!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let i=new Set,r=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(i.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(i.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&ks(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if(ks(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),r.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(r.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function Dr(e,t){try{let i=await Eu.readFile(gS(e,t),"utf8"),r=JSON.parse(i);return wS(r),r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function _a(e,t){wS(t),await Eu.mkdir(e.changesRuntimeDir,{recursive:!0}),await Z(gS(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function ks(e,t){if(!UH.test(e))throw new Error(`${t} must be a Git commit`)}function tm(e){return structuredClone(e)}function yS(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function NS(e){ks(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:r})=>r)),i=e.contract.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.depends_on],status:r.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null}));for(let r of i)for(let n of r.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${r.name} depends on unknown child ${n}`);return{schema:em,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:i,history:[],finalVerification:{status:"pending",summary:null}}}async function im(e){let t=YH(e.parent),i=Ci(e.paths.projectRoot,t);if(!i)return null;let r=Ci(e.paths.projectRoot,e.targetBranch);if(!r)return null;let n=zt(e.paths.projectRoot).map(o=>De.resolve(o)).find(o=>de(o).currentBranch===t);if(!n)return null;let a=NS({parent:e.parent,targetBranch:e.targetBranch,targetCommit:r,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(i!==r){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=i}return yS(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function bS(e){if(!bs(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=xe(e.integration.worktree,["rev-parse","--show-toplevel"]);if(De.resolve(t)!==De.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let i=xe(e.integration.worktree,["branch","--show-current"]);if(i!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${i||"(detached)"}`);return xe(e.integration.worktree,["rev-parse","HEAD"])}async function QH(e){let t=Ci(e.paths.projectRoot,e.state.integration.targetBranch);if(!t||t===e.state.integration.targetCommit)return null;let i=e.state;if(bS(i)!==i.integration.headCommit)throw new Error("Native Supervisor integration head changed before target refresh");try{xe(i.integration.worktree,["merge","--no-edit",i.integration.targetBranch])}catch(o){throw new Error(`Native Supervisor target drift requires conflict resolution in ${i.integration.worktree}`,{cause:o})}let n=xe(i.integration.worktree,["rev-parse","HEAD"]),a=tm(i);return a.integration.headCommit=n,a.finalVerification={status:"pending",summary:null},yS(a,{kind:"target-refreshed",child:null,runId:null,summary:`Target ${i.integration.targetBranch} was refreshed before delivery`}),a.stateVersion+=1,await _a(e.paths,a),a}async function Ss(e){let i=await Dr(e.paths,e.state.parent)??e.state;if(i.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before delivery; reload status first");if(i.finalVerification.status!=="passed")throw new Error("Native Supervisor delivery requires a passed final verification");if(!i.children.every(({status:v})=>v==="integrated"||v==="archived"))throw new Error("Native Supervisor delivery requires every child to be integrated");let n=zt(e.paths.projectRoot).map(v=>De.resolve(v)).find(v=>de(v).currentBranch===i.integration.targetBranch);if(!n)throw new Error(`Native Supervisor target branch worktree is unavailable: ${i.integration.targetBranch}`);if(!bs(n))throw new Error(`Native Supervisor target worktree is not clean: ${n}`);let a=xe(n,["rev-parse","HEAD"]);if((()=>{try{return xe(n,["merge-base","--is-ancestor",i.integration.headCommit,a]),!0}catch{return!1}})()){let v=await pS({paths:e.paths,state:i,targetCommit:a});if(await mS({paths:e.paths,plan:v}),i.children.every(({status:p})=>p==="archived"))return await Zp(e.paths,i.parent),{state:i,targetRoot:n,targetCommit:a};let m=tm(i);for(let p of m.children)p.status="archived";return m.stateVersion+=1,await _a(e.paths,m),await Zp(e.paths,i.parent),{state:m,targetRoot:n,targetCommit:a}}let c=bS(i);if(c!==i.integration.headCommit)throw new Error("Native Supervisor integration head changed after final verification");let l=Ci(e.paths.projectRoot,i.integration.targetBranch),u=(()=>{if(!l)return!1;try{return xe(i.integration.worktree,["merge-base","--is-ancestor",l,c]),!0}catch{return!1}})();if(l!==c&&!u&&l!==i.integration.targetCommit&&await QH({paths:e.paths,state:i}))throw new Error("Native Supervisor target changed; parent integration checks must be rerun before delivery");let d=await pS({paths:e.paths,state:i,targetCommit:c});l!==c&&xe(n,["merge","--ff-only",i.integration.branch]);let f=xe(n,["rev-parse","HEAD"]);if(f!==c)throw new Error("Native Supervisor target did not receive the verified integration head");let h=tm(i);for(let v of h.children)v.status="archived";return await mS({paths:e.paths,plan:d}),h.stateVersion+=1,await _a(e.paths,h),await Zp(e.paths,i.parent),{state:h,targetRoot:n,targetCommit:f}}function kS(e,t){return De.join(vS(e,t),"cleanup.json")}function hS(e){let t=zt(e.paths.projectRoot).map(s=>De.resolve(s)),i=De.resolve(process.cwd()),r=[{root:e.state.integration.worktree,branch:e.state.integration.branch},...e.state.children.map(({name:s})=>({root:XH(e.paths.projectRoot,e.state.parent,s),branch:`comet/supervisor/${e.state.parent}/${s}`}))].map(s=>({...s,root:De.resolve(s.root)})),n=e.targetCommit,a=[e.state.integration.branch,...e.state.children.map(({name:s})=>`comet/supervisor/${e.state.parent}/${s}`)],o=r.flatMap(s=>{let c=t.find(l=>l===s.root);return c?[{...s,root:c}]:[]});for(let s of o){if(KH(s.root,i))throw new Error(`Native Supervisor cannot clean the current worktree: ${s.root}`);if(!bs(s.root))throw new Error(`Native Supervisor cleanup requires a clean worktree: ${s.root}`);let c=de(s.root).currentBranch;if(!c)throw new Error(`Native Supervisor worktree is detached: ${s.root}`);if(c!==s.branch)throw new Error(`Native Supervisor cleanup found unexpected branch ${c} for ${s.root}; expected ${s.branch}`);try{xe(e.paths.projectRoot,["merge-base","--is-ancestor",c,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${c}`)}}for(let s of a)if(No(e.paths.projectRoot,s))try{xe(e.paths.projectRoot,["merge-base","--is-ancestor",s,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${s}`)}return{parent:e.state.parent,targetCommit:e.targetCommit,worktrees:o.map(({root:s})=>s),expectedBranches:Object.fromEntries(o.map(({root:s,branch:c})=>[s,c])),branches:a}}async function pS(e){let t=kS(e.paths,e.state.parent);try{let r=JSON.parse(await Eu.readFile(t,"utf8"));if(r.parent===e.state.parent&&r.targetCommit===e.targetCommit&&Array.isArray(r.worktrees)&&r.expectedBranches&&typeof r.expectedBranches=="object"&&Array.isArray(r.branches)){let n=hS(e);return{parent:r.parent,targetCommit:r.targetCommit,worktrees:[...new Set([...r.worktrees,...n.worktrees])],expectedBranches:{...r.expectedBranches,...n.expectedBranches},branches:[...new Set([...r.branches,...n.branches])]}}}catch(r){if(r.code!=="ENOENT")throw r}let i=hS(e);return await Z(t,i,{containedRoot:e.paths.changesRuntimeDir}),i}async function mS(e){for(let t of e.plan.worktrees){if(!zt(e.paths.projectRoot).map(a=>De.resolve(a)).includes(De.resolve(t)))continue;let r=e.plan.expectedBranches[t];if(!r)throw new Error(`Native Supervisor cleanup has no expected branch for ${t}`);let n=de(t).currentBranch;if(n!==r)throw new Error(`Native Supervisor cleanup found unexpected branch ${n??"(detached)"} for ${t}; expected ${r}`);xe(e.paths.projectRoot,["worktree","remove",t])}for(let t of e.plan.branches)No(e.paths.projectRoot,t)&&xe(e.paths.projectRoot,["branch","-d",t])}async function Zp(e,t){await Eu.rm(kS(e,t),{force:!0})}function SS(e){let t=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:[],status:i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:i.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:i})=>i==="ready").map(({name:i})=>i),allDone:t.every(({status:i})=>i==="integrated"||i==="archived")}}var ES="children.yaml",Pu="comet.native.children.v1",Ta="comet.native.children.v2",ZH=Ta,eD=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,PS=new Set(["schema","children"]),tD=new Set(["schema","acceptance_index","children"]),iD=new Set(["name","depends_on","covers"]),rD=new Set(["name","summary","depends_on"]),nD=new Set(["name","depends_on","covers"]);function Cu(e,t,i=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${i}`);return e}function Ru(e,t,i){let r=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(r.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...r.length>0?[`unexpected ${r.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${i} fields are invalid: ${a.join("; ")}`)}}function RS(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((i,r)=>i.localeCompare(r,"en"))}function rm(e,t){let i=Ht.normalize(Ht.resolve(e)),r=Ht.normalize(Ht.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function aD(e){let t=new Map(e.map(a=>[a.name,a])),i=new Set,r=new Set,n=a=>{if(!r.has(a)){if(i.has(a))throw new Error(`Native children dependency cycle includes ${a}`);i.add(a);for(let o of t.get(a).depends_on)n(o);i.delete(a),r.add(a)}};for(let a of e)n(a.name)}function CS(e,t,i=t){let r=new Set(t);for(let o of e){let s=o.covers.filter(c=>!r.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function am(e){let t=new Set(e.acceptance.filter(({source:i})=>i===e.brief).map(({id:i})=>i));if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let i=[...e.history].reverse().find(({outcome:r})=>r==="fail");for(let r of i?.unresolved_ids??[])t.add(r)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...t]}}function oD(e){let t=Cu(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),i={};for(let[r,n]of Object.entries(t)){let a=Cu(n,`Native children acceptance_index.${r}`);if(Ru(a,new Set(["source","text"]),`Native children acceptance_index.${r}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${r}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${r}.text must be a non-empty string`);i[r]={source:a.source,text:a.text}}return i}function sD(e,t,i){let r=i.requiredAcceptanceIds??t??[],n=Object.keys(e),a=r.filter(c=>!(c in e)),o=n.filter(c=>!r.includes(c));if(a.length>0||o.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${a.join(", ")||"none"}; extra ${o.join(", ")||"none"}`);let s=new Map((i.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of r){let l=s.get(c);if(!l)continue;let u=e[c];if(u.source!==l.source||u.text!==l.text){let d=["source","text"].filter(f=>u[f]!==l[f]);throw new Error(`Native children acceptance_index.${c} does not match the acceptance catalog: copy ${d.join(", ")} exactly from the current acceptance catalog`)}}}function cD(e,t,i={}){let r=(0,nm.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${r.errors[0].message}`);let n=Cu(r.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Pu&&a!==Ta)throw Ru(n,PS,"Native children contract"),new Error(`Native children schema must be ${Pu} or ${Ta}`);let o=a===Pu?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Ru(n,o==="indexed-v2"?tD:PS,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((d,f)=>{let h=Cu(d,`Native child ${f}`);if(Ru(h,o==="indexed-v2"?nD:o==="summary-v2"?rD:iD,`Native ${s} child fields (child ${f})`),typeof h.name!="string"||!eD.test(h.name))throw new Error(`Native child ${f} name is invalid`);let v=o==="summary-v2";if(v){if(typeof h.summary!="string"||h.summary.trim().length===0)throw new Error(`Native child ${h.name} summary must be a non-empty string`);if(h.summary.length>2e3)throw new Error(`Native child ${h.name} summary exceeds 2000 characters`)}return{name:h.name,summary:v?h.summary:null,depends_on:RS(h.depends_on,`Native child ${h.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?RS(h.covers,`Native child ${h.name} covers`):[]}}),l=c.map(({name:d})=>d);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let d of c){let f=d.depends_on.filter(h=>!u.has(h));if(f.length>0)throw new Error(`Native child ${d.name} depends on unknown child: ${f.join(", ")}`)}if(aD(c),a===ZH){if(o==="indexed-v2"){let d=oD(n.acceptance_index);sD(d,t,i);let f=Object.keys(d);return CS(c,f,f),{schema:Ta,acceptance_index:d,children:c}}return{schema:Ta,children:c}}return t&&CS(c,t),{schema:Pu,children:c}}async function om(e){let t=Ht.join(e.changeDir,ES);try{await AS.lstat(t)}catch(r){if(r.code==="ENOENT")return null;throw r}let i=await Q({root:e.changeDir,ref:ES});return{contract:cD(i.text,e.acceptanceIds,e.validation),size:i.size}}function lD(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let i=e.slice(t.index+t[0].length);return i.split(/^#\s+/mu,1)[0]??i}function uD(e){let t=lD(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let i=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),r=t.match(/\bChild\s+\d+\b/giu);return Math.max(i?.length??0,r?.length??0)>=2}async function _S(e){try{let t=await Q({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return uD(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function sm(e){return D("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}async function dD(e){let t=zt(e.projectRoot);t.some(r=>rm(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>Ht.resolve(n)))]){let n=await we(r);n&&i.push({projectRoot:r,paths:await Ve(r,n.native.artifact_root),parent:rm(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function fD(e,t){let i=Ht.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Qe(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function hD(e,t){let i;try{i=await AS.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Ht.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Qe(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function pD(e,t,i){let r=Ht.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${Ht.sep}`))return null;let n=r.split(Ht.sep).join("/");try{let a=(0,nm.parseDocument)(xe(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:st(a.toJS({mapAsMap:!1}))}catch{return null}}function mD(e,t,i){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==i||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${i??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function xS(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Es(e){let t=Ht.join(e.paths.changesDir,e.state.name),i=await _S(t),r=await om({changeDir:t,validation:am(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:p})=>p)}:{}});if(!r)return e.state.children_contract_hash?{...i?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:i?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let n=sm({acceptance:e.state.acceptance,children:r.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n;if(r.contract.schema===Ta){let p=await Dr(e.paths,e.state.name);if(!p){let y=e.state.workspace.target_branch??e.state.workspace.change_branch;if(y){let E=await im({paths:e.paths,parent:e.state.name,targetBranch:y,contract:r.contract});E&&(p=E,await _a(e.paths,E))}}if(p){let y=SS(p);return e.state.children_contract_hash!==n?{...y,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(E=>({...E,message:"Supervisor child plan changed; Shape confirmation is required"}))}:{...y,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let b=new Map(r.contract.children.map(y=>[y.name,y])),g=r.contract.children.map(y=>({name:y.name,summary:y.summary,dependsOn:[...y.depends_on],covers:[],status:o&&y.depends_on.every(E=>r.contract.children.filter(({name:k})=>k!==y.name).every(({name:k})=>k!==E))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let y of g){if(y.status!=="ready")continue;b.get(y.name).depends_on.length>0&&(y.status="pending")}return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:g,readyChildren:g.filter(({status:y})=>y==="ready").map(({name:y})=>y),allDone:!1}}let s=await dD(e.paths),c=new Set(r.contract.children.map(({name:p})=>p)),l=new Map,u=new Map;for(let p of s){let b=p.parent&&a?`refs/heads/${a}`:"HEAD";for(let g of await hD(p,c)){let y={...g,source:p,committedState:pD(p,g.file,b)};l.set(g.state.name,[...l.get(g.state.name)??[],y])}for(let g of c){let y=await fD(p,g);y&&u.set(g,[...u.get(g)??[],{source:p,state:y}])}}let d=new Map;for(let p of r.contract.children){let b=(l.get(p.name)??[]).find(({source:E,committedState:k})=>E.parent&&k?.name===p.name&&xS(k,a));if(b){d.set(p.name,{kind:"done",phase:b.state.phase,projectRoot:b.source.projectRoot,message:null});continue}let g=l.get(p.name)?.[0];if(g){d.set(p.name,{kind:"blocked",phase:g.state.phase,projectRoot:g.source.projectRoot,message:`Native child ${p.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let y=u.get(p.name)??[];y.length>1?d.set(p.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${p.name} has multiple active workspace owners`}):y[0]&&d.set(p.name,mD(y[0].state,y[0].source,a))}let f=new Map(r.contract.children.map(p=>[p.name,p])),h=new Map,v=p=>{let b=h.get(p);if(b)return b;let g=f.get(p),E=g.depends_on.map(v).every(({status:P})=>P==="done"),k=d.get(p),S=k?.kind==="active"&&E?g.depends_on.filter(P=>!(l.get(P)??[]).some(({source:F,committedState:$})=>rm(F.projectRoot,k.projectRoot)&&$?.name===P&&xS($,a))):[],R,N=k?.message??null;k?.kind==="done"?(R=E?"done":"blocked",E||(N=`Native child ${p} was merged before its dependencies`)):k?.kind==="active"?(R=E&&S.length===0?"active":"blocked",E?S.length>0&&(N=`Native child ${p} does not include merged dependencies: ${S.join(", ")}`):N=`Native child ${p} started before its dependencies merged`):k?.kind==="blocked"?R="blocked":(R=o&&E?"ready":"pending",o||(N="Parent Shape confirmation is required"));let w={name:p,summary:g.summary,dependsOn:[...g.depends_on],covers:[...g.covers],status:R,phase:k?.phase??null,projectRoot:k?.projectRoot??null,message:N};return h.set(p,w),w},m=r.contract.children.map(({name:p})=>v(p));return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:m,readyChildren:m.filter(({status:p})=>p==="ready").map(({name:p})=>p),allDone:m.every(({status:p})=>p==="done")}}var Ps="skill-coordinated";function gD(e){return e.state_version+1}function wD(e){return e.map(t=>({...t,result:"pending",reason:null}))}function yD(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:dr(e.summary),completed_at:e.completedAt}}function cm(e){let t=st(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let i=(e.now??new Date).toISOString(),r=Un(t,yD({state:t,outcome:"recovery",summary:e.reason,completedAt:i})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?wD(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return st({...r,phase:"build",status:"active",state_version:gD(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:a,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,next_action:"submit-builder-candidate"}})}import{promises as IS}from"node:fs";import Rs from"node:path";function xu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Au(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Si(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function TS(e,t){return e===null?null:Si(e,t)}function Tu(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function ND(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function bD(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function _u(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function lm(e,t){if(e===null)return null;let i=Si(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function um(e,t){let i=Si(e,t);if(!Rs.isAbsolute(i))throw new Error(`${t} must be absolute`);return Rs.resolve(i)}function kD(e,t){let i=`Native local checks[${t}]`,r=xu(e,i);if(Au(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,u)=>Si(l,`${i}.argv[${u}]`,!0)),a=_u(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=lm(r.startedAt,`${i}.startedAt`),s=lm(r.completedAt,`${i}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${i} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${i} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${i} completed check requires startedAt and completedAt`);let c=Tu(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Si(r.id,`${i}.id`),name:Si(r.name,`${i}.name`),operationId:Si(r.operationId,`${i}.operationId`),status:a,repeatable:bD(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:Tu(r.executionCount,`${i}.executionCount`),argv:n,cwd:um(r.cwd,`${i}.cwd`),exitCode:ND(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Si(r.log,`${i}.log`)}}function dm(e){let t="Native local execution state",i=xu(e,t);if(Au(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Ho)throw new Error(`Native local execution schema must be ${Ho}`);let r=xu(i.workspace,"Native local workspace");Au(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=xu(i.execution,"Native local execution");Au(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=lm(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Si(o.operationId,"Native local execution.operationId"),stage:_u(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:_u(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:TS(o.executionId,"Native local execution.executionId"),status:_u(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:Tu(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(i.checks))throw new Error("Native local checks must be an array");let a=i.checks.map(kD);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:Ho,change:Si(i.change,"Native local change"),basedOnStateVersion:Tu(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:um(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:um(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:TS(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function gn(e){return dm({schema:Ho,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:Rs.resolve(e.projectRoot),worktreeRoot:Rs.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Iu(e){let t;try{t=await IS.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return dm(i)}async function Mr(e,t,i={}){let r=dm(t);await IS.mkdir(Rs.dirname(e),{recursive:!0}),await Z(e,r,i)}import{promises as SD}from"node:fs";function Lr(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
206
|
-
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function
|
|
207
|
-
`),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(d=>{let f=d.argv_display.map(
|
|
208
|
-
`),s=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(d=>`- **${d.owner}**: ${
|
|
209
|
-
`),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(d=>`- ${
|
|
210
|
-
`),l=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(d=>`| ${d.goal_cycle} | ${d.iteration} | ${d.attempt} | ${d.outcome} | ${d.unresolved_ids.join(", ")||"—"} | ${
|
|
198
|
+
${e.sessionId}`)}:{}},h=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return Xo(h),h}async function Jl(e){let t=await ZN(e),i=da(e.paths,e.name),r=j(e.paths,i);return await T(r,i),await ee(i,t,{containedRoot:r}),t}async function kt(e,t){let i=await XN(e,t);return i===null||i&&typeof i=="object"&&!Array.isArray(i)&&i.schema==="comet.native.workspace.v1"?null:(Xo(i),i)}async function eb(e){return await Yh(e.paths,e.name)?Jl(e):null}async function Qo(e){Xo(e.identity);let t=await ZN({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),i=[],r=[];return t.nativeRootRef!==e.identity.nativeRootRef&&i.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&i.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&i.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&i.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&i.push("native-root-legacy-identity")),Uh==="win32"&&i.length>0&&i.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?r.push("workspace-inspection-unavailable"):i.length>0&&r.push("workspace-root-changed"),{state:r.length===0?"aligned":r.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:r,driftComponents:i}}async function fa(e){if(Xo(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await Qo(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let i=fe(e.paths.projectRoot);return e.identity.changeBranch===null?i.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:i.isGitWorktree?i.currentBranch!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${i.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!i.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function tb(e,t){let i=await kt(e,t);if(i===null)return null;let r=await fa({paths:e,identity:i});if(r.state==="drifted")throw new Error(`${r.code}: ${r.message}`);return i}var rb=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],u$=new Set(rb),nb=new Set([...rb,"minimum_runtime_version","revision"]),d$=new Set([...nb,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),f$=new Set(["capability","operation","source","base_hash"]),h$=new Set(["shape","build","verify","archive"]),p$=new Set(["implicit","confirmed"]),m$=new Set(["pending","pass","fail"]),Te="comet-state.yaml",Qh=/^[a-f0-9]{64}$/u,ab=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,v$=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Zo=class extends Error{constructor(i,r){super(`Native change ${i} uses ${r}; run comet native doctor ${i} --repair before mutating it`);this.change=i;this.schema=r;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},fn=class extends Error{constructor(i,r){super(i!==Ne||r===null?`Unsupported Native change schema ${i} for runtime protocol ${3}`:`Native change ${i} requires runtime protocol ${r}; current protocol is ${3}`);this.schema=i;this.minimumRuntimeVersion=r;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},es=class extends Error{constructor(i,r,n){super(`Native change ${i} revision conflict: expected ${r}, actual ${n}`);this.change=i;this.expectedRevision=r;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},ts=class extends Error{constructor(i,r){super(`Native working directory already contains active change${r.length===1?"":"s"} ${r.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=i;this.activeChanges=r;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},ha=class extends Error{constructor(i,r,n,a,o,s=null,c=null){super(`Native change ${i} baseline is incomplete (${r} omitted entr${r===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=i;this.omittedCount=r;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},M2=Us("en");function rs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function ob(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Ul(e){if(!ab.test(e))throw new Error(`Invalid Native change name: ${e}`)}function g$(e){if(!ab.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function sb(e,t){if(e.length===0||mi.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function w$(e,t){let i=rs(e,`spec_changes[${t}]`);if(ob(i,f$,`spec_changes[${t}]`),typeof i.capability!="string")throw new Error("spec change capability is required");if(g$(i.capability),i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`Invalid spec operation for ${i.capability}`);let r=i.source,n=i.base_hash;if(r!==void 0&&typeof r!="string")throw new Error(`Spec source for ${i.capability} must be a string`);if(typeof r=="string"&&sb(r,`Spec source for ${i.capability}`),i.operation==="create"){if(!r)throw new Error(`Create spec ${i.capability} requires source`);if(n!==null)throw new Error(`Create spec ${i.capability} requires null base_hash`)}else if(i.operation==="replace"){if(!r)throw new Error(`Replace spec ${i.capability} requires source`);if(typeof n!="string"||!Qh.test(n))throw new Error(`Replace spec ${i.capability} requires a SHA-256 base_hash`)}else{if(r!==void 0)throw new Error(`Remove spec ${i.capability} forbids source`);if(typeof n!="string"||!Qh.test(n))throw new Error(`Remove spec ${i.capability} requires a SHA-256 base_hash`)}return{capability:i.capability,operation:i.operation,...typeof r=="string"?{source:r}:{},base_hash:n}}function y$(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function Zh(e,t){if(ob(e,t,Te),typeof e.name!="string")throw new Error("Native change name is required");if(Ul(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!h$.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!p$.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let i=e.spec_changes.map(w$),r=i.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(r.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(r)].join(", ")}`);if(typeof e.verification_result!="string"||!m$.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&sb(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!y$(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:i,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function on(e){let t=rs(e,Te);if(t.schema!==et)throw new Error(`Expected ${et}`);return{schema:et,...Zh(t,u$)}}function is(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Xh(e,t,i){if(e===null)return null;let r=typeof e=="string"?v$.exec(e):null;if(!r||r[1]!==i)throw new Error(`${t} must be null or runtime/evidence/${i}/<sha256>.json relative to the Native change`);return e}function N$(e){if(e==null)return null;if(typeof e!="string"||!Qh.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function b$(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function di(e){let t=rs(e,Te);if(t.schema!==be)throw new Error(`Expected ${be}`);if(is(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${be} minimum_runtime_version must be 2`);return{schema:be,minimum_runtime_version:2,revision:is(t.revision,"Native v2 revision"),...Zh(t,nb)}}function lt(e){let t=rs(e,Te);if(t.schema!==Ne){if(t.schema===et||t.schema===be){let o=t.schema===et?on(t):di(t);throw new Zo(o.name,o.schema)}throw new fn(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let i=is(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)throw new fn(t.schema,i);if(i!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let r=is(t.revision,"Native revision"),n=Zh(t,d$),a=N$(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ne,minimum_runtime_version:3,revision:r,verification_protocol:b$(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Xh(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Xh(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Xh(t.partial_allowance,"Native partial_allowance","allowances")}}function cb(e){let t=rs(e,Te);if(t.schema===et){let n=on(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ne}`}}if(t.schema===be){let n=di(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ne}`}}if(t.schema!==Ne){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new fn(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let i=is(t.minimum_runtime_version,"Native minimum_runtime_version");if(i>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:i,state:null,message:new fn(t.schema,i).message};let r=lt(t);return{status:"current",schema:r.schema,minimumRuntimeVersion:r.minimum_runtime_version,state:r}}function dn(e){let t=lt(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,verification_protocol:t.verification_protocol,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,approved_contract_hash:t.approved_contract_hash??null,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,implementation_scope:t.implementation_scope,verification_evidence:t.verification_evidence,partial_allowance:t.partial_allowance,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function Kl(e){let t=di(e);return{schema:t.schema,minimum_runtime_version:t.minimum_runtime_version,revision:t.revision,name:t.name,language:t.language,phase:t.phase,brief:t.brief,approval:t.approval,spec_changes:t.spec_changes.map(i=>({capability:i.capability,operation:i.operation,...i.source?{source:i.source}:{},base_hash:i.base_hash})),verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function ne(e,t){Ul(t);let i=mi.join(e.changesDir,t);if(!O(e.changesDir,i))throw new Error("Native change path escaped");return i}async function pa(e,t){let i=H(e,t),r=mi.join(i,"schema-migration.json");await T(O(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await ib.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function ma(e,t){let i=H(e,t),r=mi.join(i,"checkpoint-journal.json");await T(O(e.runtimeDir,r)?e.runtimeDir:e.nativeRoot,r);try{return await ib.lstat(r),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Yl(e,t=mi.dirname(e)){let i=mi.relative(t,e).split(mi.sep).join("/"),r=await Z({root:t,ref:i,maxBytes:null,includeHash:!1}),n=(0,Gl.parseDocument)(r.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function vi(e,t){let i=mi.join(ne(e,t),Te);await T(e.nativeRoot,i);let r=cb(await Yl(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await pa(e,t)?{status:"migration-required",schema:r.schema,minimumRuntimeVersion:r.minimumRuntimeVersion,state:r.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(r.status==="current"&&r.state&&await k$(e,r.state),r)}async function Xl(e,t){let i=mi.join(ne(e,t),Te);await T(e.nativeRoot,i);let r=cb(await Yl(i,e.nativeRoot));if(r.state&&r.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return r}async function k$(e,t){if(await sa(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function He(e,t){let i=await vi(e,t);if(i.status==="migration-required")throw new Zo(t,i.schema);if(i.status==="runtime-incompatible"||!i.state)throw new fn(i.schema,i.minimumRuntimeVersion);return await tb(e,t),i.state}async function lb(e,t,i){let r={...t,schema:Ne,minimum_runtime_version:3,revision:i+1},n=await cN({expectedRevision:i,next:r,read:async()=>{let a=lt(await Yl(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>he(e,(0,Gl.stringify)(dn(a))),equals:(a,o)=>JSON.stringify(dn(a))===JSON.stringify(dn(o)),conflict:a=>new es(t.name,i,a)});return Object.assign(t,n),n}async function Ql(e,t,i,r){if(await Wn(e.projectRoot),await pa(e,t.name))throw new Zo(t.name,t.schema);if(!r?.allowPendingCheckpointRecovery&&await ma(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await He(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Wl(e,t.name);let a=mi.join(ne(e,t.name),Te);return await T(e.nativeRoot,a),lb(a,t,i)}async function ub(e,t){return lb(e,t,t.revision)}async function db(e){return lt(await Yl(e))}var hb=["outcome","scope","nonGoals","acceptanceExamples"],S$=[...hb,"constraints","decisions","openQuestions","verificationExpectations"],E$=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],pb={maxFileBytes:So};function mb(e){let t=new Map,i=null,r=[],n=()=>{i!==null&&t.set(i,r.join(`
|
|
199
|
+
`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),i=o[1].trim(),r=[]):i!==null&&r.push(a)}return n(),t}async function P$(e,t){let i=fb.resolve(e,...t.split(/[\\/]/u));if(!O(e,i))throw new Error(`Artifact escapes Native change: ${t}`);let r=await ep.realpath(e),n=await ep.realpath(i);if(!O(r,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await ep.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function ns(e){return{valid:e.length===0,findings:e}}async function tp(e,t){let i=[],r;try{r=(await Z({root:e,ref:t,maxBytes:pb.maxFileBytes})).text}catch(o){return ns([{code:"brief-missing",message:o.message,path:t}])}let n=new Map;for(let[o,s]of mb(r))n.set(Gs(o)??o,s);for(let o of S$)n.has(o)||i.push({code:"brief-section-missing",message:`Missing brief section: ${o}`,path:t});for(let o of hb)(n.get(o)??"").length===0&&i.push({code:"brief-section-empty",message:`Brief section is empty: ${o}`,path:t});let a=n.get("openQuestions")??"";return/^\s*-\s*\[blocking\]/imu.test(a)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),ns(i)}async function ip(e,t){let i=[],r;try{r=(await Z({root:e,ref:t,maxBytes:pb.maxFileBytes})).text}catch(a){return ns([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of mb(r))n.set(Zm(a)??a,o);for(let a of E$)n.has(a)?(n.get(a)??"").length===0&&i.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):i.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return ns(i)}function Zl(e,t){return fb.join(e.specsDir,t,"spec.md")}async function vb(e,t){let i=[],r=ne(e,t.name);for(let n of t.spec_changes){let a=Zl(e,n.capability),o=null;try{await T(e.nativeRoot,a),o=await Zt(a)}catch(s){if(s.code!=="ENOENT"){i.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&i.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&i.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&i.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await P$(r,n.source)}catch(s){i.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return ns(i)}import{promises as TH}from"node:fs";import Zk from"node:path";import gb from"node:path";var R$="comet.native.archive-preflight.v1",C$="comet.native.archive-preflight.v1",x$="comet.native.archive-operation.v1",A$=/^[a-f0-9]{64}$/u,wb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function eu(e,t){return e<t?-1:e>t?1:0}function T$(e,t){if(typeof e!="string"||!A$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function $i(e,t){return e===null?null:T$(e,t)}function I$(e,t){let i=gb.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||gb.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function j$(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function $$(e){if(e==null)return null;if(e.schema!=="comet.native.workspace.v3")throw new Error("Native archive workspace schema is invalid");if(e.isolation!=="current"&&e.isolation!=="branch"&&e.isolation!=="worktree")throw new Error("Native archive workspace isolation is invalid");for(let[t,i]of[["change",e.changeBranch],["target",e.targetBranch]])if(i!==null&&(i.length===0||i.trim()!==i||Array.from(i).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})))throw new Error(`Native archive workspace ${t} branch is invalid`);if(e.finish!==null&&e.finish!=="merge"&&e.finish!=="push"&&e.finish!=="pull-request"&&e.finish!=="keep")throw new Error("Native archive workspace finish is invalid");if((e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null||e.finish===null))throw new Error("Native isolated archive workspace requires branches and a finish action");if(e.isolation==="current"&&e.finish!==null)throw new Error("Native current archive workspace cannot have a finish action");return{...e}}function O$(e,t){if(!wb.test(e.capability))throw new Error(`Native archive spec ${t} capability is invalid`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Native archive spec ${e.capability} operation is invalid`);let i=$i(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),r=$i(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=$i(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&i!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&i===null)throw new Error(`Native archive ${e.operation} ${e.capability} requires a base hash`);if(e.operation==="remove"!=(n===null))throw new Error(`Native archive ${e.operation} ${e.capability} proposed hash is invalid`);return{capability:e.capability,operation:e.operation,expectedBaseHash:i,actualBaseHash:r,proposedHash:n}}function H$(e){if(e.result!=="pending"&&e.result!=="pass"&&e.result!=="fail")throw new Error("Native archive verification result is invalid");if(!["missing","invalid","stale","complete","partial"].includes(e.freshness))throw new Error("Native archive verification freshness is invalid");if(!Number.isSafeInteger(e.skippedAcceptanceCount)||e.skippedAcceptanceCount<0)throw new Error("Native archive skipped acceptance count is invalid");let t={result:e.result,freshness:e.freshness,contractHash:$i(e.contractHash,"Native archive contract hash"),acceptanceHash:$i(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:$i(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:$i(e.reportHash,"Native archive report hash"),envelopeHash:$i(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:$i(e.partialAllowanceHash,"Native archive partial allowance hash"),skippedAcceptanceCount:e.skippedAcceptanceCount};if((e.freshness==="complete"||e.freshness==="partial")&&[t.contractHash,t.acceptanceHash,t.implementationScopeHash,t.reportHash,t.envelopeHash].some(i=>i===null))throw new Error("Fresh Native archive evidence requires every bound content hash");if(e.freshness==="partial"&&t.partialAllowanceHash===null||e.freshness==="complete"&&t.partialAllowanceHash!==null)throw new Error("Native archive partial evidence allowance state is invalid");return t}function D$(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(r=>{if(typeof r!="string"||!_$.test(r))throw new Error(`Native archive preflight finding code is invalid: ${String(r)}`);return r}),i=[...new Set(t)].sort(eu);if(i.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return i}function L$(e){let t=[];e.phase!=="archive"&&t.push("archive-phase-required"),e.archived&&t.push("change-already-archived"),e.pendingJournal&&t.push("pending-journal"),e.targetExists&&t.push("archive-target-exists"),e.evidence.result!=="pass"&&t.push("verification-not-passed"),e.evidence.freshness==="missing"&&t.push("verification-evidence-missing"),e.evidence.freshness==="invalid"&&t.push("verification-evidence-invalid"),e.evidence.freshness==="stale"&&t.push("verification-evidence-stale"),e.evidence.skippedAcceptanceCount>0&&t.push("verification-acceptance-skipped");for(let i of e.specs)i.actualBaseHash!==i.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(eu)}function yb(e){if(!wb.test(e.change))throw new Error("Native archive change name is invalid");if(typeof e.stateSchema!="string"||e.stateSchema.length===0)throw new Error("Native archive state schema is invalid");if(!Array.isArray(e.specs)||e.specs.length>64)throw new Error("Native archive preflight exceeds its spec budget");let t=e.specs.map(O$).sort((l,u)=>eu(l.capability,u.capability));if(new Set(t.map(l=>l.capability)).size!==t.length)throw new Error("Native archive preflight contains duplicate capabilities");let i=t.map(l=>({...l,operationHash:D(x$,l)})),r=H$(e.evidence),n=$$(e.workspace),a=[...new Set([...D$(e.findingCodes??[]),...L$({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:r})])].sort(eu),o=j$(e.revision),s=I$(e.targetRef,"Native archive target");if(e.archiveConfirmation!=="automatic"&&e.archiveConfirmation!=="required")throw new Error("Native archive confirmation must be automatic or required");let c={stateSchema:e.stateSchema,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetRef:s,targetExists:e.targetExists,operations:i,evidence:r,workspace:n,findingCodes:a};return{schema:R$,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:r.freshness,operationCount:i.length,operations:i,workspace:n,findingCodes:a,preflightHash:D(C$,c)}}import{createHash as M$}from"node:crypto";import Nb from"node:path";var F$="comet.native.conflict-radar.v1",ut=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512}),B$="comet.native.conflict-radar.v1",V$="comet.native.conflict-radar-signals.v1",q$=/^[a-f0-9]{64}$/u,Sb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,W$=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),z$=new Set(["capability","operation","baseHash"]),J$=new Set(["path","kind"]);function va(e,t){return e<t?-1:e>t?1:0}function rp(e){return Buffer.byteLength(e,"utf8")}function np(e,t,i){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${i} must be an object`);let r=e,n=Object.keys(r).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);return r}function ap(e,t,i){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(rp(e)>i)throw new Error(`${t} exceeds its byte budget`);return e}function G$(e,t){let i=ap(e,t,ut.maxArtifactPathBytes),r=Nb.posix.normalize(i);if(i.includes("\\")||Array.from(i).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(i)||Nb.posix.isAbsolute(r)||i.split("/").includes("..")||r!==i||r==="."||i.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return i}function Eb(e,t){if(typeof e!="string"||!q$.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function U$(e,t){let i=np(e,z$,t),r=ap(i.capability,`${t} capability`,ut.maxCapabilityBytes);if(!Sb.test(r))throw new Error(`${t} capability is invalid`);if(i.operation!=="create"&&i.operation!=="replace"&&i.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=i.baseHash===null?null:Eb(i.baseHash,`${t} canonical base hash`);if(i.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(i.operation!=="create"&&n===null)throw new Error(`${t} ${i.operation} operation requires a canonical base hash`);return{capability:r,operation:i.operation,baseHash:n}}function K$(e,t){let i=np(e,J$,t);if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:G$(i.path,`${t} path`),kind:i.kind}}function Y$(e,t){let i=np(e,W$,`Conflict radar change ${t}`),r=ap(i.name,`Conflict radar change ${t} name`,ut.maxNameBytes);if(!Sb.test(r))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(i.revision)||i.revision<1)throw new Error(`Conflict radar change ${r} revision must be a positive safe integer`);if(!Array.isArray(i.specs))throw new Error(`Conflict radar change ${r} specs must be an array`);if(i.specs.length>ut.maxSpecsPerChange)throw new Error(`Conflict radar change ${r} exceeds the spec budget`);if(!Array.isArray(i.declaredArtifacts))throw new Error(`Conflict radar change ${r} declared artifacts must be an array`);if(i.declaredArtifacts.length>ut.maxArtifactsPerChange)throw new Error(`Conflict radar change ${r} exceeds the declared artifact budget`);let n=i.specs.map((c,l)=>U$(c,`Conflict radar change ${r} spec ${l}`)).sort((c,l)=>va(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${r} has duplicate capabilities`);let a=i.declaredArtifacts.map((c,l)=>K$(c,`Conflict radar change ${r} artifact ${l}`)).sort((c,l)=>va(c.path,l.path)||va(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${r} has duplicate or conflicting artifact paths`);let s=i.workspaceIdentityHash===void 0||i.workspaceIdentityHash===null?null:Eb(i.workspaceIdentityHash,`Conflict radar change ${r} workspace identity hash`);return{name:r,revision:i.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function X$(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>ut.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(Y$).sort((n,a)=>va(n.name,a.name));if(new Set(t.map(n=>n.name)).size!==t.length)throw new Error("Native conflict radar contains duplicate change names");if(t.reduce((n,a)=>n+a.specs.length,0)>ut.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>ut.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function Q$(e,t){let i=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||i?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function Z$(e,t){let i=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),r=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!i&&!r&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function eO(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function tO(e,t){let i=[],r=M$("sha256").update(`${V$}
|
|
200
|
+
[`),n=0,a=!1,o=l=>{n>0&&r.update(","),r.update(Oo(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),i.length<ut.maxSignalsPerRelationship&&i.push(l)},s=new Map(t.specs.map(l=>[l.capability,l]));for(let l of e.specs){let u=s.get(l.capability);u&&o(Q$(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=Z$(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return r.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:eO(e,t),signalCount:n,signalHash:r.digest("hex"),signals:i,signalsTruncated:i.length!==n}}function bb(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function iO(e,t){return bb(e.classification)-bb(t.classification)||va(e.left,t.left)||va(e.right,t.right)}function kb(e,t,i,r){let n={definiteConflict:t.filter(({classification:a})=>a==="definite-conflict").length,possibleOverlap:t.filter(({classification:a})=>a==="possible-overlap").length,disjoint:t.filter(({classification:a})=>a==="disjoint").length};return{schema:F$,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:i,relationshipsTruncated:i.length!==t.length,omittedRelationshipCount:t.length-i.length,radarHash:r}}function Pb(e){let t=X$(e),i=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)i.push(tO(t[s],t[c]));i.sort(iO);let r=i.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=D(B$,{changes:t,relationships:r}),a=i.slice(0,ut.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=kb(t,i,a,n);for(;a.length>0&&rp(JSON.stringify(o))>ut.maxSerializedBytes;)a=a.slice(0,-1),o=kb(t,i,a,n);if(rp(JSON.stringify(o))>ut.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}import{createHash as h0}from"node:crypto";import{promises as ri}from"node:fs";import yi from"node:path";import{createHash as jb}from"node:crypto";import Rb from"path";var op="comet.native.implementation-scope.v2",$b="comet.native.content-snapshot-projection.v1",as="comet.native.content-snapshot-projection.v1",Ob="comet.native.implementation-scope.v2",rO="comet.native.unresolved-scope-id.v1",nO="comet.native.scope-detail-overflow.v1",aO="comet.native.snapshot-projection-overflow.v2",up=/^[a-f0-9]{64}$/u,pn=1024*1024,oO=128,sO=128;function Ge(e,t){return e<t?-1:e>t?1:0}function sp(e){if(!up.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function cO(e,t){return e===t?0:e===null?-1:t===null?1:Ge(e,t)}function Rr(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a normalized project-relative path`);let i=Rb.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Rb.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function Hb(e,t){return e==="."?e:Rr(e,t)}function ga(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function lO(e,t){if(e.type!=="file")throw new Error(`${t} must describe a file`);if(typeof e.hash!="string"||e.hash.length===0)throw new Error(`${t} hash must be non-empty`);return{path:Rr(e.path,`${t} path`),hash:e.hash,size:ga(e.size,`${t} size`),type:"file"}}function uO(e,t){return{path:Hb(e.path,`${t} path`),size:e.size===null?null:ga(e.size,`${t} size`),type:e.type,reason:e.reason}}function dO(e,t){return Ge(e.path,t.path)||Ge(e.hash,t.hash)||e.size-t.size}function fO(e,t){return Ge(e.path,t.path)||Ge(e.reason,t.reason)||Ge(e.type,t.type)||(e.size??-1)-(t.size??-1)}function ss(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
201
|
+
`,"utf8")}function Pr(e,t,i){let r=`${t}
|
|
202
|
+
${Oo(i)}`;e.update(`${Buffer.byteLength(r,"utf8")}:`),e.update(r)}function hO(e){if(ss(e)<=pn)return e;let t=[...e.entries],i=[...e.omitted],r=e.omittedCount,n=e.omissionOverflow?.count??0,a=jb("sha256");a.update(`${aO}
|
|
203
|
+
`),e.omissionOverflow&&Pr(a,"existing-overflow",e.omissionOverflow);let o=(f,h)=>{h||(r+=1),n+=1,Pr(a,"omission",f)},s=f=>{r+=1,n+=1,Pr(a,"entry",f)},c=()=>{for(let f=i.length-1;f>=0;f-=1){let h=i[f];if(!(h.reason==="git-enumeration-limit"||h.reason==="git-selection-changed"||h.reason==="physical-enumeration-limit"||h.reason==="physical-selection-changed"))return i.splice(f,1),h}return null},l=()=>({...e,complete:r===0,entries:t,omitted:i,omittedCount:r,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;ss(u)>pn;){if(i.filter(h=>h.reason!=="git-enumeration-limit"&&h.reason!=="git-selection-changed"&&h.reason!=="physical-enumeration-limit"&&h.reason!=="physical-selection-changed").length>0){let h=Math.max(1,Math.ceil(i.length/4));for(let v=0;v<h;v+=1){let m=c();if(m===null)break;o(m,!0)}}else if(t.length>0){let h=Math.max(1,Math.ceil(t.length/4));for(let v of t.splice(-h))s(v)}else throw new Error("Native snapshot projection metadata exceeds its evidence byte budget");u=l()}let d=a.digest("hex");return{...u,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${d}`,hash:d,count:n}}}function cp(e){let t=Ii(e),i=t.entries.map((n,a)=>lO(n,`Snapshot entry ${a}`));if(i.sort(dO),new Set(i.map(n=>n.path)).size!==i.length)throw new Error("Snapshot entries must not contain duplicate paths");let r=t.omitted.map((n,a)=>uO(n,`Snapshot omission ${a}`));return r.sort(fO),hO({schema:$b,origin:t.origin,...t.capture?{capture:t.capture}:{},complete:t.complete,limits:{maxFiles:t.limits.maxFiles,maxFileBytes:t.limits.maxFileBytes,maxTotalBytes:t.limits.maxTotalBytes,maxManifestBytes:t.limits.maxManifestBytes,...t.limits.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},...t.policy?{policy:t.policy}:{},entries:i,omitted:r,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function cs(e){let t=new Map;for(let[i,r]of e.entries()){if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${i} kind is invalid`);let n={path:Rr(r.path,`Declared artifact ${i} path`),kind:r.kind},a=t.get(n.path);if(a&&a.kind!==n.kind)throw new Error(`Declared artifact path has conflicting kinds: ${n.path}`);t.set(n.path,n)}return[...t.values()].sort((i,r)=>Ge(i.path,r.path)||Ge(i.kind,r.kind))}function ls(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function Cb(e){return e?{hash:e.hash,size:e.size}:null}function dp(e,t,i){let r=0,n=0;for(;r<e.entries.length||n<t.entries.length;){let a=e.entries[r],o=t.entries[n],s=a===void 0?1:o===void 0?-1:Ge(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(r+=1),s>=0&&(n+=1),c&&l&&c.hash===l.hash&&c.size===l.size||c&&!l&&!t.complete)continue;let u=c?.path??l?.path;u!==void 0&&i({path:u,kind:c?l?"modified":"removed":"added",before:Cb(c),after:Cb(l)})}}function Db(e,t){return{...e,attributedTo:t.filter(i=>ls(i,e.path))}}function fp(e){let t=cs(e.declaredArtifacts),i=[];return dp(e.baseline,e.current,r=>{i.push(Db(r,t))}),i}function Oi(e,t){return{id:`scope:${D(rO,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function pO(e,t){let i=t.omitted.map(r=>Oi({kind:"snapshot-omission",source:e,path:r.path,evidence:{reason:r.reason,size:r.size,type:r.type}},`${e} snapshot omitted ${r.path}: ${r.reason}`));return t.complete||i.push(Oi({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&i.push(Oi({kind:"snapshot-omission-overflow",source:e,path:null,evidence:{count:t.omissionOverflow.count,hash:t.omissionOverflow.hash,ref:t.omissionOverflow.ref}},`${e} snapshot has ${t.omissionOverflow.count} unlisted omissions`)),i}function xb(e,t){return pO(e,{...t,omitted:[]}).filter(i=>i.kind!=="snapshot-omission")}function lp(e,t){return Ge(e.kind,t.kind)||Ge(e.source,t.source)||cO(e.path,t.path)||Ge(e.id,t.id)}function mO(e){return[...new Map(e.map(i=>[i.id,i])).values()].sort(lp)}function Lb(e){return[...new Set(e.map((t,i)=>Rr(t,`Git path ${i}`)))].sort(Ge)}function Ab(e,t){if(typeof e!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(e))throw new Error(`${t} must be a Git commit object id`);return e}function vO(e,t){if(typeof e!="string"||e.length===0||e.trim()!==e||e.includes("\\")||e.includes("\0")||e.startsWith("-"))throw new Error(`${t} must be a valid Git branch name`);return e}function Mb(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=Lb(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:Ab(e.baseCommit,"Native external drift base commit"),targetBranch:vO(e.targetBranch,"Native external drift target branch"),targetCommit:Ab(e.targetCommit,"Native external drift target commit"),paths:t}}function Fb(e){if(typeof e.contractHash!="string"||!up.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:cs(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:Lb(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:Mb(e.externalDrift)}}}function gO(e,t,i,r,n){let a=[],o=r===void 0?null:new Set(r),s=[],c=[],l=0,u=!1,d=0,f=0;return dp(e,t,h=>{let v=i.some(m=>ls(m,h.path));if(d+=1,c.push(h.path),!v&&!n?.has(h.path)&&(f+=1),o?.has(h.path)&&s.push(h.path),!u&&a.length<oO){let m=Db(h,i),p=ss(m);l+p<=pn?(a.push(m),l+=p):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function Bb(e,t){return Oi({kind:"scope-detail-overflow",source:"implementation-scope",path:null,evidence:{changeCount:t.changes,hash:e,unattributedCount:t.unattributed,unresolvedCount:t.unresolved}},`Implementation scope summarized ${t.changes} additional change details and ${t.unresolved} unresolved details (${t.unattributed} unattributed); overflow hash ${e}`)}function wO(e){let t=/^Implementation scope summarized ([0-9]+) additional change details and ([0-9]+) unresolved details \(([0-9]+) unattributed\); overflow hash ([a-f0-9]{64})$/u.exec(e.reason);if(!t)throw new Error("Implementation scope detail overflow is invalid");let i={changes:ga(Number(t[1]),"Scope overflow change count"),unresolved:ga(Number(t[2]),"Scope overflow unresolved count"),unattributed:ga(Number(t[3]),"Scope overflow unattributed count")},r=hn(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(Bb(r,i)))throw new Error("Implementation scope detail overflow is inconsistent");return{...i,hash:r}}function yO(e){let t=jb("sha256");t.update(`${nO}
|
|
204
|
+
`);let i=0;dp(e.baseline,e.current,n=>{if(i>=e.detailedChangeCount){Pr(t,"change",n);let a=0;for(let o of e.declaredArtifacts)ls(o,n.path)&&(a+=1,Pr(t,"change-attribution",o));Pr(t,"change-end",{attributionCount:a}),a===0&&Pr(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}i+=1});let r=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)r>=e.detailedOmissionCount&&Pr(t,"snapshot-omission",{source:n,...o}),r+=1;return t.digest("hex")}function Vb(e,t,i){let{contractHash:r,declaredArtifacts:n,noCodeReason:a}=i,o=gO(e,t,n,i.gitChangedPaths,i.externalDrift?new Set(i.externalDrift.paths):void 0);if(i.externalDrift){let R=new Set(i.externalDrift.paths),N=new Set(o.changePaths),w=i.externalDrift.paths.filter(P=>!N.has(P)||n.some(F=>ls(F,P)));if(w.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${w.slice(0,8).join(", ")}`);if(R.size!==i.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=D(as,e),c=D(as,t),l=[],u=new Set(i.externalDrift?.paths??[]);for(let[R,N]of[["baseline",e],["current",t]])for(let w of N.omitted){if(l.length>=sO)break;l.push(Oi({kind:"snapshot-omission",source:R,path:w.path,evidence:{reason:w.reason,size:w.size,type:w.type}},`${R} snapshot omitted ${w.path}: ${w.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...xb("baseline",e),...xb("current",t),...o.totalChanges===0&&a===null?[Oi({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:s,currentProjectionHash:c}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],h=()=>{if(i.gitChangedPaths===void 0)return;let R=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:i.gitChangedPaths,pathsPresentInSnapshotChanges:i.gitChangedPaths.filter(N=>R.has(N)),pathsAbsentFromSnapshotChanges:i.gitChangedPaths.filter(N=>!R.has(N))}},v=R=>{let N=o.candidates.slice(0,R.detailedChangeCount),w=N.filter(Vt=>Vt.attributedTo.length===0&&!u.has(Vt.path)),P=o.totalChanges-N.length,F=o.totalUnattributed-w.length,$=d-R.detailedOmissionCount,Fe=F+$,ue=[...w.map(Vt=>Oi({kind:"unattributed-change",source:"implementation-scope",path:Vt.path,evidence:{after:Vt.after,before:Vt.before,changeKind:Vt.kind}},`Changed path is not covered by a declared artifact: ${Vt.path}`)),...l.slice(0,R.detailedOmissionCount),...f,...Fe>0?[Bb(R.overflowHash,{changes:P,unattributed:F,unresolved:Fe})]:[]],te=mO(ue),ai=R.includeGitAdvisory?h():void 0;return{schema:op,contractHash:r,baselineProjectionRef:sp(s),baselineProjectionHash:s,currentProjectionRef:sp(c),currentProjectionHash:c,complete:te.length===0,declaredArtifacts:n,changes:N,unattributed:w,unresolvedScopes:te,noCodeReason:a,...ai?{gitAdvisory:ai}:{},...i.externalDrift?{externalDrift:i.externalDrift}:{}}},m=o.candidates.length,p=l.length,b=i.gitChangedPaths!==void 0,g="0".repeat(64);for(;;){let R=v({detailedChangeCount:m,detailedOmissionCount:p,includeGitAdvisory:b,overflowHash:g});if(ss({...R,scopeHash:g})<=pn)break;if(b){b=!1;continue}if(p>0){p-=Math.max(1,Math.ceil(p/4));continue}if(m>0){m-=Math.max(1,Math.ceil(m/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let E=o.totalChanges>m||d>p?yO({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:m,detailedOmissionCount:p}):g,k=v({detailedChangeCount:m,detailedOmissionCount:p,includeGitAdvisory:b,overflowHash:E}),S={...k,scopeHash:D(Ob,k)};if(ss(S)>pn)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return S}function hp(e){let t=cp(e.baseline),i=cp(e.current),r=Fb(e);return{authority:r,baseline:t,current:i,scope:Vb(t,i,r)}}var NO=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"]);function gi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function wi(e,t,i,r){let n=new Set([...t,...i]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${r} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${r} is missing field(s): ${o.join(", ")}`)}function hn(e,t){if(typeof e!="string"||!up.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function _b(e,t,i){let r=sp(t);if(e!==r)throw new Error(`${i} ref/hash mismatch`);return r}function wa(e,t){let i=gi(e,"Native snapshot projection");if(wi(i,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),i.schema!==$b)throw new Error("Native snapshot projection schema is invalid");let r=Ii({schema:"comet.native.content-snapshot.v1",origin:i.origin,...i.capture===void 0?{}:{capture:i.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:i.complete,limits:i.limits,...i.policy===void 0?{}:{policy:i.policy},entries:i.entries,omitted:i.omitted,omittedCount:i.omittedCount,...i.omissionOverflow===void 0?{}:{omissionOverflow:i.omissionOverflow}}),n=cp(r);if(D(as,i)!==D(as,n))throw new Error("Native snapshot projection is not canonical");let a=D(as,n);if(t!==void 0&&hn(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function pp(e,t){let i=gi(e,`Declared artifact ${t}`);if(wi(i,["path","kind"],[],`Declared artifact ${t}`),i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Rr(i.path,`Declared artifact ${t} path`),kind:i.kind}}function Tb(e,t){if(e===null)return null;let i=gi(e,t);return wi(i,["hash","size"],[],t),{hash:hn(i.hash,`${t} hash`),size:ga(i.size,`${t} size`)}}function Ib(e,t){let i=gi(e,`Implementation change ${t}`);if(wi(i,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),i.kind!=="added"&&i.kind!=="modified"&&i.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(i.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let r=i.attributedTo.map(pp),n=cs(r);if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=Tb(i.before,`Implementation change ${t} before`),o=Tb(i.after,`Implementation change ${t} after`);if(i.kind==="added"&&(a!==null||o===null)||i.kind==="removed"&&(a===null||o!==null)||i.kind==="modified"&&(a===null||o===null||JSON.stringify(a)===JSON.stringify(o)))throw new Error(`Implementation change ${t} before/after state is invalid`);return{path:Rr(i.path,`Implementation change ${t} path`),kind:i.kind,before:a,after:o,attributedTo:r}}function bO(e,t){let i=gi(e,`Unresolved scope ${t}`);wi(i,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let r=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof i.kind!="string"||!r.has(i.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(i.source!=="baseline"&&i.source!=="current"&&i.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof i.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(i.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(i.path!==null&&typeof i.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof i.reason!="string"||i.reason.length===0||i.reason.trim()!==i.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:i.id,kind:i.kind,source:i.source,path:i.path===null?null:i.kind==="snapshot-omission"?Hb(i.path,`Unresolved scope ${t} path`):Rr(i.path,`Unresolved scope ${t} path`),reason:i.reason}}function os(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let i=e.map((n,a)=>Rr(n,`${t} ${a}`)),r=[...new Set(i)].sort(Ge);if(JSON.stringify(i)!==JSON.stringify(r))throw new Error(`${t} must be sorted and unique`);return i}function qb(e){let t=gi(e,"Native implementation external drift");if(wi(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let i=os(t.paths,"Native external drift paths");return Mb({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:i})}function ya(e){let t=gi(e,"Native implementation scope"),i=[...NO].filter(w=>w!=="gitAdvisory"&&w!=="externalDrift");if(wi(t,i,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==op)throw new Error("Native implementation scope schema is invalid");let r=hn(t.contractHash,"Implementation scope contractHash"),n=hn(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=_b(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=hn(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=_b(t.currentProjectionRef,o,"Implementation scope current projection");if(typeof t.complete!="boolean")throw new Error("Implementation scope complete flag is invalid");if(!Array.isArray(t.declaredArtifacts)||!Array.isArray(t.changes)||!Array.isArray(t.unattributed)||!Array.isArray(t.unresolvedScopes))throw new Error("Implementation scope collections are invalid");let c=t.declaredArtifacts.map(pp);if(JSON.stringify(c)!==JSON.stringify(cs(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(Ib),u=[...l].sort((w,P)=>Ge(w.path,P.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(w=>w.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(w=>`${w.kind}:${w.path}`));if(l.some(w=>w.attributedTo.some(P=>!d.has(`${P.kind}:${P.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(w=>JSON.stringify(w.attributedTo)!==JSON.stringify(c.filter(P=>ls(P,w.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(Ib),h=t.externalDrift===void 0?void 0:qb(t.externalDrift),v=new Set(h?.paths??[]),m=l.filter(w=>w.attributedTo.length===0&&!v.has(w.path));if(JSON.stringify(f)!==JSON.stringify(m))throw new Error("Implementation scope unattributed changes are inconsistent");let p=t.unresolvedScopes.map(bO),b=p.filter(w=>w.kind==="scope-detail-overflow");if(b.length>1)throw new Error("Implementation scope has multiple detail overflow records");let g=b[0]===void 0?null:wO(b[0]);if(g&&(g.changes+g.unresolved===0||g.unattributed>g.changes||g.unattributed>g.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let y=t.noCodeReason,E=[...m.map(w=>Oi({kind:"unattributed-change",source:"implementation-scope",path:w.path,evidence:{after:w.after,before:w.before,changeKind:w.kind}},`Changed path is not covered by a declared artifact: ${w.path}`)),...l.length+(g?.changes??0)===0&&y===null?[Oi({kind:"missing-no-code-reason",source:"implementation-scope",path:null,evidence:{baselineProjectionHash:n,currentProjectionHash:o}},"A non-empty no-code reason is required when the snapshots contain no changes")]:[]],k=p.filter(w=>w.kind==="unattributed-change"||w.kind==="missing-no-code-reason");if(JSON.stringify(p)!==JSON.stringify([...p].sort(lp))||new Set(p.map(w=>w.id)).size!==p.length||JSON.stringify(k)!==JSON.stringify(E.sort(lp))||t.complete!==(p.length===0))throw new Error("Implementation scope unresolved scopes are inconsistent");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Implementation scope no-code reason is invalid");let S;if(t.gitAdvisory!==void 0){let w=gi(t.gitAdvisory,"Implementation scope Git advisory");if(wi(w,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),w.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let P=os(w.changedPaths,"Git changed paths"),F=os(w.pathsPresentInSnapshotChanges,"Git present paths"),$=os(w.pathsAbsentFromSnapshotChanges,"Git absent paths"),Fe=[...F,...$].sort(Ge);if(JSON.stringify(Fe)!==JSON.stringify(P)||$.some(ue=>l.some(te=>te.path===ue)))throw new Error("Implementation scope Git advisory partition is invalid");S={advisoryOnly:!0,changedPaths:P,pathsPresentInSnapshotChanges:F,pathsAbsentFromSnapshotChanges:$}}let R={schema:op,contractHash:r,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:p,noCodeReason:y,...S?{gitAdvisory:S}:{},...h?{externalDrift:h}:{}},N=hn(t.scopeHash,"Implementation scope scopeHash");if(D(Ob,R)!==N)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:N}}function kO(e){let t=gi(e,"Native implementation scope authority");if(wi(t,["contractHash","declaredArtifacts","noCodeReason"],["gitChangedPaths","externalDrift"],"Native implementation scope authority"),!Array.isArray(t.declaredArtifacts))throw new Error("Native implementation scope authority declarations must be an array");let i=t.declaredArtifacts.map(pp);if(JSON.stringify(i)!==JSON.stringify(cs(i)))throw new Error("Native implementation scope authority declarations must be canonical");if(t.noCodeReason!==null&&(typeof t.noCodeReason!="string"||t.noCodeReason.length===0||t.noCodeReason.trim()!==t.noCodeReason))throw new Error("Native implementation scope authority no-code reason is invalid");let r;t.gitChangedPaths!==void 0&&(r=os(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:qb(t.externalDrift),a=Fb({contractHash:t.contractHash,declaredArtifacts:i,noCodeReason:t.noCodeReason,...r===void 0?{}:{gitChangedPaths:r},...n===void 0?{}:{externalDrift:n}});if(a.contractHash!==t.contractHash)throw new Error("Native implementation scope authority contract hash is not canonical");return a}function us(e){let t=gi(e,"Native implementation scope bundle");wi(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let i=kO(t.authority),r=wa(t.baseline),n=wa(t.current),a=ya(t.scope),o=Vb(r,n,i);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:i,baseline:r,current:n,scope:o}}function Wb(e){let t=ya(e.scope);return us({authority:{contractHash:t.contractHash,declaredArtifacts:t.declaredArtifacts,noCodeReason:t.noCodeReason,...t.gitAdvisory?{gitChangedPaths:t.gitAdvisory.changedPaths}:{},...t.externalDrift?{externalDrift:t.externalDrift}:{}},baseline:e.baseline,current:e.current,scope:t})}import zb from"node:path";var SO=/\b(Bearer|Basic)\s+[^\s"']+/giu,EO=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,PO=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,RO=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,CO=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,xO=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,AO=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function $t(e){return e.replace(SO,"$1 [REDACTED]").replace(EO,"[REDACTED PRIVATE KEY]").replace(PO,"$1[REDACTED]@").replace(RO,"[REDACTED TOKEN]").replace(CO,'$1"[REDACTED]"').replace(xO,"$1$2$1$3$4[REDACTED]$4").replace(AO,"$1$2[REDACTED]")}var Gb=/^[a-f0-9]{64}$/u;var _O="comet.native.acceptance-trace.v2",TO="comet.native.partial-allowance.v1",IO="comet.native.verification-evidence.v2";function Hi(e,t){if(!Gb.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Ub(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function Kb(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native evidence change name: ${e}`);return e}function mp(e,t,i=2e3){let r=$t(e).trim();if(r.length===0||r.length>i)throw new Error(`${t} must be between 1 and ${i} characters`);return r}function ds(e,t){let i=zb.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||zb.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function jO(e,t,i){let r=ds(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(r))return r;let n=ci(r),a=r.toLowerCase(),o=i?ds(i,"Native root ref").toLowerCase():null;if(n||a==="runtime"||a.startsWith("runtime/")||o!==null&&(a===o||a.startsWith(`${o}/`)))throw new Error(`${t} is excluded as sensitive (${n??"native-runtime"}): ${r}`);return r}function vp(e){let t=ds(e,"Verification typed receipt ref");if(!/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u.test(t))throw new Error("Verification receipt ref must identify a typed v3 receipt");return t}function Na(e,t){return e<t?-1:e>t?1:0}function tu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function iu(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Yb(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let i=new Date(e);if(Number.isNaN(i.valueOf())||i.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function Jb(e,t,i){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let r=`runtime/evidence/${t}/${i}.json`;if(e!==r)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function $O(e){let t=tu(e,"Native acceptance trace");if(iu(t,["schema","nativeRootRef","criteriaHash","total","evidenced","skipped","entries","traceHash"],"Native acceptance trace"),t.schema!=="comet.native.acceptance-trace.v2"||typeof t.nativeRootRef!="string"||typeof t.criteriaHash!="string"||!Gb.test(t.criteriaHash)||!Number.isSafeInteger(t.total)||!Number.isSafeInteger(t.evidenced)||!Number.isSafeInteger(t.skipped)||!Array.isArray(t.entries))throw new Error("Native acceptance trace is invalid");let i=ds(t.nativeRootRef,"Native root ref"),r=t.entries.map((o,s)=>{let c=tu(o,`Native acceptance trace entry ${s}`);if(iu(c,["acceptanceId","status","kind","source","evidenceRefs","skippedReason"],`Native acceptance trace entry ${s}`),typeof c.acceptanceId!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(c.acceptanceId)||c.kind!=="brief-example"&&c.kind!=="spec-scenario"&&c.kind!=="spec-must"||typeof c.source!="string"||!Array.isArray(c.evidenceRefs)||c.status!=="passed"&&c.status!=="failed"&&c.status!=="missing"||c.evidenceRefs.some(d=>typeof d!="string")||c.skippedReason!==null&&(typeof c.skippedReason!="string"||c.skippedReason.length===0||c.skippedReason.trim()!==c.skippedReason))throw new Error(`Native acceptance trace entry ${s} is invalid`);let l=c.evidenceRefs.map(d=>vp(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Na))||u==="passed"&&(l.length===0||c.skippedReason!==null)||u==="failed"&&l.length===0&&c.skippedReason===null||u==="missing"&&(l.length>0||c.skippedReason!==null))throw new Error(`Native acceptance trace entry ${s} evidence state is invalid`);return{acceptanceId:c.acceptanceId,status:u,kind:c.kind,source:ds(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:mp(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(r)!==JSON.stringify([...r].sort((o,s)=>Na(o.acceptanceId,s.acceptanceId)))||new Set(r.map(o=>o.acceptanceId)).size!==r.length||t.total!==r.length||t.evidenced!==r.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==r.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:i,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:r},a=Hi(t.traceHash,"Native acceptance trace hash");if(D(_O,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function ru(e){let t=tu(e,"Native partial allowance");if(iu(t,["schema","change","scopeHash","scopeIds","reason","confirmedSummary","sourceRevision","confirmedAt","allowanceHash"],"Native partial allowance"),t.schema!=="comet.native.partial-allowance.v1"||typeof t.change!="string"||typeof t.scopeHash!="string"||!Array.isArray(t.scopeIds)||t.scopeIds.length===0||t.scopeIds.some(n=>typeof n!="string"||!/^scope:[a-f0-9]{64}$/u.test(n))||JSON.stringify(t.scopeIds)!==JSON.stringify([...new Set(t.scopeIds)].sort(Na))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let i={schema:"comet.native.partial-allowance.v1",change:Kb(t.change),scopeHash:Hi(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:mp(t.reason,"Partial allowance reason"),confirmedSummary:mp(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:Ub(t.sourceRevision),confirmedAt:Yb(t.confirmedAt,"Native partial allowance timestamp")};if(i.reason!==t.reason||i.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let r=Hi(t.allowanceHash,"Native partial allowance hash");if(D(TO,i)!==r)throw new Error("Native partial allowance content hash mismatch");return{...i,allowanceHash:r}}function fs(e){let t=tu(e,"Native verification evidence");if(iu(t,["schema","change","sourceRevision","result","freshness","contractHash","acceptanceCriteriaHash","implementationScopeRef","implementationScopeHash","reportRef","reportHash","acceptanceTrace","partialAllowanceRef","partialAllowanceHash","requiredReceiptRefs","receiptRefs","createdAt","envelopeHash"],"Native verification evidence"),t.schema!=="comet.native.verification-evidence.v2"||typeof t.change!="string"||t.result!=="pass"&&t.result!=="fail"||t.freshness!=="complete"&&t.freshness!=="partial"||typeof t.implementationScopeHash!="string"||typeof t.reportRef!="string"||!Array.isArray(t.requiredReceiptRefs)||!Array.isArray(t.receiptRefs))throw new Error("Native verification evidence is invalid");let i=Hi(t.implementationScopeHash,"Native verification implementation scope hash"),r=$O(t.acceptanceTrace),n=Hi(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(r.criteriaHash!==n)throw new Error("Native verification acceptance trace does not match its criteria hash");let a=t.partialAllowanceRef!==null||t.partialAllowanceHash!==null;if(t.partialAllowanceRef===null!=(t.partialAllowanceHash===null)||t.freshness==="complete"&&a||t.freshness==="partial"&&!a)throw new Error("Native verification partial allowance state is invalid");let o=t.partialAllowanceHash===null?null:Hi(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>vp(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(Na)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(r.entries.flatMap(f=>f.evidenceRefs))].sort(Na);if(JSON.stringify(s)!==JSON.stringify(c))throw new Error("Native verification envelope receipt refs do not match its matrix");let l=t.requiredReceiptRefs.map(f=>vp(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(Na)))throw new Error("Native required receipt refs must be canonical");if(t.result==="pass"&&l.length===0)throw new Error("Passing verification has no current static receipt");let u={schema:"comet.native.verification-evidence.v2",change:Kb(t.change),sourceRevision:Ub(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Hi(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:Jb(t.implementationScopeRef,"scopes",i),implementationScopeHash:i,reportRef:jO(t.reportRef,"Native verification report ref"),reportHash:Hi(t.reportHash,"Native verification report hash"),acceptanceTrace:r,partialAllowanceRef:o===null?null:Jb(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:Yb(t.createdAt,"Native verification timestamp")},d=Hi(t.envelopeHash,"Native verification envelope hash");if(D(IO,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}import Xb from"node:path";var Qb="comet.native.check-receipt.v1",OO="comet.native.check-receipt.v1",ba="scoped-text-safety",gp=1,dt=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),HO=/^[a-f0-9]{64}$/u,DO=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,LO="comet.native.checker-policy.v1",MO="comet.native.check-input.v1",FO=2048,Zb=D(LO,{policy:ba,version:gp,limits:dt,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),BO=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),ek=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],ik=["contract-before-does-not-match-scope","implementation-before-does-not-match-scope","contract-changed-during-check","implementation-changed-during-check","contract-after-does-not-match-scope","implementation-after-does-not-match-scope"],VO=new Set(ik);function Cr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function xr(e,t,i,r=[]){let n=new Set([...t,...r]),a=Object.keys(e).filter(s=>!n.has(s)),o=t.filter(s=>!(s in e));if(a.length>0)throw new Error(`${i} has unknown field(s): ${a.join(", ")}`);if(o.length>0)throw new Error(`${i} is missing field(s): ${o.join(", ")}`)}function Di(e,t){if(typeof e!="string"||!HO.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function St(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function rk(e,t){let i=St(e,t);if(i<1)throw new Error(`${t} must be a positive integer`);return i}function tk(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let i=new Date(e);if(!Number.isFinite(i.getTime())||i.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function qO(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>FO||e.includes("\\")||e.includes("\0")||e.endsWith("/")||/^[a-zA-Z]:/u.test(e))throw new Error(`${t} must be a bounded normalized project-relative path`);let i=Xb.posix.normalize(e);if(i!==e||i==="."||i===".."||i.startsWith("../")||Xb.posix.isAbsolute(i))throw new Error(`${t} must stay inside the project root`);return e}function WO(e){let t=Cr(e,"Native check receipt checker");xr(t,["policy","version","hash","limits"],"Native check receipt checker");let i=Cr(t.limits,"Native check receipt limits");if(xr(i,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==ba||t.version!==gp||t.hash!==Zb||i.maxFiles!==dt.maxFiles||i.maxFileBytes!==dt.maxFileBytes||i.maxTotalBytes!==dt.maxTotalBytes||i.maxIssues!==dt.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:ba,version:gp,hash:Zb,limits:{...dt}}}function zO(e){let t=Cr(e,"Native check receipt contract");return xr(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:Di(t.expectedHash,"Native check expected contract hash"),beforeHash:Di(t.beforeHash,"Native check before contract hash"),afterHash:Di(t.afterHash,"Native check after contract hash")}}function JO(e){let t=Cr(e,"Native check receipt implementation");return xr(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:Di(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:Di(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:Di(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:Di(t.afterSnapshotHash,"Native check after snapshot hash")}}function GO(e,t){let i=Cr(e,`Native check batch ${t}`);xr(i,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let r={filesSelected:St(i.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:St(i.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:St(i.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:St(i.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:St(i.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:St(i.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(r.filesSelected>dt.maxFiles||r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.bytesScanned>dt.maxTotalBytes||r.recordedIssueCount>r.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return r}function UO(e){let t=Cr(e,"Native check receipt counts");xr(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let i={filesSelected:St(t.filesSelected,"Native check filesSelected"),filesScanned:St(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:St(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:St(t.bytesScanned,"Native check bytesScanned"),issueCount:St(t.issueCount,"Native check issueCount"),recordedIssueCount:St(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(GO):(()=>{throw new Error("Native check receipt batches must be an array")})()}},r=i.batches;if(r!==void 0){if(r.length===0)throw new Error("Native check receipt batches must not be empty");let n=r.reduce((a,o)=>({filesSelected:a.filesSelected+o.filesSelected,filesScanned:a.filesScanned+o.filesScanned,binaryFilesSkipped:a.binaryFilesSkipped+o.binaryFilesSkipped,bytesScanned:a.bytesScanned+o.bytesScanned,issueCount:a.issueCount+o.issueCount,recordedIssueCount:a.recordedIssueCount+o.recordedIssueCount}),{filesSelected:0,filesScanned:0,binaryFilesSkipped:0,bytesScanned:0,issueCount:0,recordedIssueCount:0});if(JSON.stringify(n)!==JSON.stringify({...i,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.recordedIssueCount>i.issueCount||i.recordedIssueCount>dt.maxIssues||r===void 0&&(i.filesScanned+i.binaryFilesSkipped>dt.maxFiles||i.bytesScanned>dt.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return i}function KO(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||ek.indexOf(e.kind)-ek.indexOf(t.kind)}function YO(e){if(!Array.isArray(e)||e.length>dt.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((r,n)=>{let a=Cr(r,`Native check issue ${n}`);if(xr(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!BO.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:qO(a.path,`Native check issue ${n} path`),line:rk(a.line,`Native check issue ${n} line`),kind:a.kind}}),i=[...t].sort(KO);if(JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function XO(e){if(!Array.isArray(e)||e.some(r=>typeof r!="string"||!VO.has(r)))throw new Error("Native check receipt stale reasons are invalid");let t=e,i=ik.filter(r=>t.includes(r));if(new Set(t).size!==t.length||JSON.stringify(i)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function QO(e){return D(MO,e)}function nu(e){let t=Cr(e,"Native check receipt");if(xr(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==Qb)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!DO.test(t.change))throw new Error("Native check receipt change name is invalid");let i=rk(t.sourceRevision,"Native check source revision"),r=WO(t.checker),n=zO(t.contract),a=JO(t.implementation),o=QO({change:t.change,sourceRevision:i,checkerHash:r.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(Di(t.inputHash,"Native check input hash")!==o)throw new Error("Native check receipt input hash mismatch");if(t.status!=="passed"&&t.status!=="failed")throw new Error("Native check receipt status is invalid");let s=tk(t.startedAt,"Native check receipt startedAt"),c=tk(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=UO(t.counts),u=YO(t.issues);if(l.recordedIssueCount!==u.length)throw new Error("Native check receipt recorded issue count is inconsistent");if(typeof t.issuesTruncated!="boolean"||t.issuesTruncated!==l.issueCount>u.length)throw new Error("Native check receipt issue truncation flag is inconsistent");let d=XO(t.staleReasons);if(typeof t.stale!="boolean"||t.stale!==d.length>0)throw new Error("Native check receipt stale flag is inconsistent");let f=l.issueCount===0&&!t.stale?"passed":"failed";if(t.status!==f)throw new Error("Native check receipt status is inconsistent with its evidence");if(t.status==="passed"&&(l.batches===void 0&&l.filesSelected>dt.maxFiles||l.filesScanned+l.binaryFilesSkipped!==l.filesSelected))throw new Error("Passed Native check receipt must cover every selected file");if(l.batches===void 0&&l.filesSelected>dt.maxFiles&&!u.some(m=>m.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let h={schema:Qb,change:t.change,sourceRevision:i,checker:r,inputHash:o,status:t.status,startedAt:s,endedAt:c,contract:n,implementation:a,counts:l,issues:u,issuesTruncated:t.issuesTruncated,stale:t.stale,staleReasons:d},v=Di(t.receiptHash,"Native check receipt content hash");if(D(OO,h)!==v)throw new Error("Native check receipt content hash mismatch");return{...h,receiptHash:v}}var yp="comet.native.verification-receipt.v3",ZO=yp,e0="comet.native.declared-artifacts.v1",t0=/^[a-f0-9]{64}$/u,i0=/^acceptance-[a-f0-9]{64}$/u,r0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,n0=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,a0=4096,o0=256,s0=1024;function ka(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function Ar(e,t,i){let r=Object.keys(e).sort(),n=[...t].sort();if(r.length!==n.length||r.some((a,o)=>a!==n[o]))throw new Error(`${i} fields are invalid`)}function Li(e,t){if(typeof e!="string"||!t0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function ii(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let i=$t(e).trim();if(!i||i.length>a0||i!==e.trim())throw new Error(`${t} is invalid`);return i}function wp(e,t){let i=ii(e,t),r=new Date(i);if(Number.isNaN(r.getTime())||r.toISOString()!==i)throw new Error(`${t} must be a canonical timestamp`);return i}function hs(e,t,i=ii,r=!1,n=o0){if(!Array.isArray(e)||e.length>n||!r&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>i(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function c0(e,t){if(typeof e!="string"||!i0.test(e))throw new Error(`${t} is invalid`);return e}function l0(e){let t=ka(e,"Native verification receipt bindings");if(Ar(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!r0.test(t.change)||!Number.isSafeInteger(t.sourceRevision)||t.sourceRevision<1)throw new Error("Native verification receipt bindings are invalid");return{change:t.change,sourceRevision:t.sourceRevision,contractHash:Li(t.contractHash,"Native verification receipt contract hash"),scopeHash:Li(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:Li(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:Li(t.artifactHash,"Native verification receipt artifact hash")}}function u0(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=n0.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function d0(e,t,i,r){let n=ka(t,`Native ${e} evidence`);if(e==="automated-check"){if(Ar(n,["executable","args","cwd","exitCode","signal","timedOut","timeoutMs","startedAt","endedAt","worktree","afterFence","outputHash","outputSummary","outputTruncated"],"Native automated-check evidence"),!Number.isSafeInteger(n.exitCode)||!Number.isSafeInteger(n.timeoutMs)||n.timeoutMs<1||n.timeoutMs>3600*1e3||typeof n.timedOut!="boolean"||typeof n.outputTruncated!="boolean"||n.signal!==null&&typeof n.signal!="string")throw new Error("Native automated-check exit code is invalid");let a=wp(n.startedAt,"Native automated-check start time"),o=wp(n.endedAt,"Native automated-check end time");if(Date.parse(o)<Date.parse(a))throw new Error("Native automated-check time range is invalid");if(i==="passed"&&n.exitCode!==0||i==="failed"&&n.exitCode===0||i==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=ka(n.worktree,"Native automated-check worktree");if(Ar(s,["provider","root","beforeCommit","afterCommit"],"Native automated-check worktree"),s.provider!=="git"&&s.provider!=="none"||s.beforeCommit!==null&&(typeof s.beforeCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.beforeCommit))||s.afterCommit!==null&&(typeof s.afterCommit!="string"||!/^[a-f0-9]{40,64}$/u.test(s.afterCommit)))throw new Error("Native automated-check worktree identity is invalid");let c=ka(n.afterFence,"Native automated-check after fence");if(Ar(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(i==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:ii(n.executable,"Native automated-check executable"),args:hs(n.args,"Native automated-check arguments",ii,!0),cwd:ii(n.cwd,"Native automated-check cwd"),exitCode:n.exitCode,signal:n.signal,timedOut:n.timedOut,timeoutMs:n.timeoutMs,startedAt:a,endedAt:o,worktree:{provider:s.provider,root:ii(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:Li(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:Li(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:Li(n.outputHash,"Native automated-check output hash"),outputSummary:ii(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){Ar(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=u0(n.checkReceiptRef);if(Li(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:hs(n.subjects,"Native static inspection subjects",ii,r==="required-check"),rule:ii(n.rule,"Native static inspection rule"),resultSummary:ii(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return Ar(n,["steps","observations"],"Native manual-evidence evidence"),{steps:hs(n.steps,"Native manual evidence steps"),observations:hs(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function f0(e){let t=ka(e,"Native verification receipt");if(Ar(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence"],"Native verification receipt input"),!["automated-check","static-inspection","manual-evidence"].includes(t.kind)||t.role!=="required-check"&&t.role!=="acceptance-evidence"||!["passed","failed","skipped","blocked"].includes(t.status))throw new Error("Native verification receipt kind or status is invalid");let i=t.kind,r=t.role,n=t.status,a=ii(t.actor,"Native verification receipt actor"),o=hs(t.acceptanceIds,"Native receipt acceptance IDs",c0,r==="required-check",s0).sort();if(r==="required-check"&&o.length!==0||r==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(r==="required-check"&&i!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:yp,kind:i,role:r,status:n,bindings:l0(t.bindings),acceptanceIds:o,actor:a,issuedAt:wp(t.issuedAt,"Native verification receipt issue time"),evidence:d0(i,t.evidence,n,r)};if(r==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==ba||s.actor!==`native-runtime:${ba}`))throw new Error("Native required check policy identity is invalid");return s}function au(e){let t=ka(e,"Native verification receipt");if(Ar(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==yp)throw new Error("Native verification receipt schema is invalid");let{receiptHash:i,...r}=t,n=f0(r),a=Li(t.receiptHash,"Native verification receipt hash");if(D(ZO,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Np(e){return D(e0,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,i)=>t.path.localeCompare(i.path)||t.kind.localeCompare(i.kind)))}var sk=/^[a-f0-9]{64}$/u,_r=pn,_z=3*_r;function bp(e,t){let i=yi.relative(e,t);return i===""||!yi.isAbsolute(i)&&i!==".."&&!i.startsWith(`..${yi.sep}`)}function p0(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ou(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function nk(e){let t=await ri.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await ri.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function m0(e,t){let i=yi.resolve(e),r=yi.resolve(t);if(!bp(i,r))throw new Error("Native evidence path is outside its change");let n=[await nk(i)],a=i;for(let o of yi.relative(i,r).split(yi.sep).filter(Boolean)){a=yi.join(a,o);let s=await nk(a);if(!bp(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function ak(e){for(let t of e){let i=await ri.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!p0(t,i)||await ri.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function v0(e,t,i={}){let r=await m0(t,yi.dirname(e));await i.afterParentChainCaptured?.();let n=await ri.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await ri.realpath(e);if(!bp(r[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await ri.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),ri.lstat(e),ri.realpath(e)]);if(await ak(r),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!ou(s,n)||!ou(s,c))throw new Error("Native evidence document changed while opening");if(s.size>_r)throw new Error(`Native evidence document exceeds ${_r} bytes`);await i.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let p=_r+1-d,b=await o.read(f,0,Math.min(f.length,p),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,d>_r)throw new Error(`Native evidence document exceeds ${_r} bytes`);u.push(Buffer.from(f.subarray(0,b.bytesRead)))}await i.beforeFinalCheck?.();let[h,v,m]=await Promise.all([o.stat(),ri.lstat(e),ri.realpath(e)]);if(await ak(r),!v.isFile()||v.isSymbolicLink()||m!==a||!ou(s,h)||!ou(s,v))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function Ea(e,t){if(!sk.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function ck(e){return Ea("reports",e)}async function g0(e,t,i,r,n){if(!sk.test(i))throw new Error("Native report evidence hash is invalid");let a=await mn({paths:e,name:t,kind:"reports",hash:i,hooks:r,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==i||typeof o.content!="string"||h0("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==i)throw new Error("Native report evidence does not match its hash");return o.content}function Sa(e,t){let i=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!i||i[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return i[2]}function w0(e,t,i,r,n){let a=Ea(i,r);return n?yi.join(n,...a.split("/")):lr(H(e,t),a)}async function mn(e){let t=w0(e.paths,e.name,e.kind,e.hash,e.changeDir),i=e.changeDir??j(e.paths,t);return await T(i,t),v0(t,i,e.hooks)}function ok(e,t){return wa(e,t)}function y0(e,t){let i=ya(e);if(i.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return i}function N0(e,t,i){let r=ru(e);if(r.change!==t||r.allowanceHash!==i)throw new Error("Native partial allowance ref/hash/change mismatch");return r}function b0(e,t,i){let r=fs(e);if(r.change!==t||r.envelopeHash!==i)throw new Error("Native verification evidence ref/hash/change mismatch");return r}async function k0(e,t,i,r=!1,n){let a=await su(e,t,i.implementationScopeRef,void 0,n);if(r&&await g0(e,t,i.reportHash,void 0,n),a.scopeHash!==i.implementationScopeHash||a.contractHash!==i.contractHash||(a.complete?"complete":"partial")!==i.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(i.partialAllowanceRef===null)return;let o=await lk(e,t,i.partialAllowanceRef,void 0,n);if(o.allowanceHash!==i.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=i.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function ps(e,t,i,r,n){let a=Sa(i,"scopes"),o=y0(await mn({paths:e,name:t,kind:"scopes",hash:a,hooks:r,changeDir:n}),a),s=Sa(o.baselineProjectionRef,"snapshots"),c=Sa(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([mn({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>ok(d,s)),mn({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>ok(d,c))]);return Wb({baseline:l,current:u,scope:o})}async function su(e,t,i,r,n){return(await ps(e,t,i,r,n)).scope}async function lk(e,t,i,r,n){let a=Sa(i,"allowances");return N0(await mn({paths:e,name:t,kind:"allowances",hash:a,hooks:r,changeDir:n}),t,a)}async function ms(e,t,i,r,n){let a=Sa(i,"receipts"),o=au(await mn({paths:e,name:t,kind:"receipts",hash:a,hooks:r,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function Pa(e,t,i,r,n){let a=Sa(i,"verifications"),o=b0(await mn({paths:e,name:t,kind:"verifications",hash:a,hooks:r,changeDir:n}),t,a);return await k0(e,t,o,!1,n),o}var S0=4096;async function E0(e,t=ut.maxChanges){try{let i=await wt({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function uk(e,t){let i=await He(e,t),[r,n]=await Promise.all([i.implementation_scope?su(e,t,i.implementation_scope):null,kt(e,t).catch(()=>null)]);return{name:i.name,revision:i.revision,specs:i.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:r?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function cu(e,t,i={}){let n=(await E0(e,S0)).filter(c=>c.isDirectory()&&!c.isSymbolicLink()).map(c=>c.name).sort();if(!n.includes(t))throw new Error(`Native conflict target is not visible: ${t}`);let a=await uk(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await uk(e,c).catch(d=>{if(i.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=Pb([a,l]).relationships[0];u.classification==="definite-conflict"&&(o+=1),u.classification==="possible-overlap"&&(s+=1)}return{definiteConflictCount:o,possibleOverlapCount:s,findingCodes:[...o>0?["native-change-conflict"]:[],...s>0?["native-change-overlap"]:[]]}}import{promises as B0}from"fs";import V0 from"path";import{isDeepStrictEqual as uu}from"util";var Ra={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var P0=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function R0(e,t){return e<t?-1:e>t?1:0}function C0(e,t,i,r){if(!Array.isArray(e)||e.length>i||!r&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!P0.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(R0)}function kp(e=[]){return C0(e,"Native repair failed check IDs",Ra.maxFailedCheckIds,!0)}function dk(e,t){let i=new Set(t);return e.every(r=>i.has(r))}function x0(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:dk(e.failedAcceptanceIds,t.failedAcceptanceIds)&&dk(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function Sp(e,t){let i=1,r=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(x0(r,a))break;i+=1,r=a}return i}function Ep(e,t){if(typeof e!="string"||e.trim().length===0||e.length>4096)throw new Error(`${t} must be between 1 and 4096 characters`)}var fk="repairStagnation",Et={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},_0=/^[a-f0-9]{64}$/u;var T0=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),I0=["data","runId","sequence","timestamp","type"],hk=["disposition","overrideSummaryHash","signatureHash"],j0=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],pk=12;function Rp(e,t){return e<t?-1:e>t?1:0}function mk(e,t,i){let r=Object.keys(e).sort(Rp);if(r.length!==t.length||r.some((n,a)=>n!==t[a]))throw new Error(`${i} fields are invalid`)}function lu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let i=Object.getPrototypeOf(e);if(i!==Object.prototype&&i!==null)throw new Error(`${t} must be a plain object`);return e}function vs(e,t){if(typeof e!="string"||!_0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function $0(e){if(!Array.isArray(e)||e.length>Ra.maxFailedAcceptanceIds||e.some(t=>typeof t!="string"||!/^acceptance-[a-f0-9]{64}$/u.test(t)))throw new Error("Native repair trajectory failed acceptance IDs are invalid");return[...new Set(e)].sort(Rp)}function vk(e){if(typeof e!="string"||e.length===0||e.length>Et.maxRunIdCharacters||Array.from(e).some(t=>{let i=t.codePointAt(0)??0;return i<=31||i===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Pp(e,t,i,r,n=!1){if(i.nodes+=1,i.nodes>Et.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>Et.maxDataDepth)throw new Error("Native repair trajectory event data exceeds its depth boundary");if(!(e===null||typeof e=="boolean")){if(typeof e=="number"){if(!Number.isFinite(e))throw new Error(`${r} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>Et.maxTextCharacters&&(!n||e.length>Et.maxEventDataCharacters))throw new Error(`${r} contains oversized text`);if(i.characters+=e.length,i.characters>Et.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${r} contains a non-JSON value`);if(i.ancestors.has(e))throw new Error(`${r} contains a cycle`);i.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>Et.maxArrayEntries)throw new Error(`${r} contains an oversized array`);e.forEach((s,c)=>Pp(s,t+1,i,`${r}[${c}]`));return}let a=lu(e,r),o=Object.keys(a);if(o.length>Et.maxObjectFields)throw new Error(`${r} contains too many fields`);for(let s of o){if(s.length===0||s.length>Et.maxKeyCharacters)throw new Error(`${r} contains an invalid field name`);if(i.characters+=s.length,i.characters>Et.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Pp(a[s],t+1,i,`${r}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{i.ancestors.delete(e)}}}function O0(e){if(typeof e!="string"||e.length>64)throw new Error("Native repair trajectory timestamp is invalid");let t=new Date(e);if(!Number.isFinite(t.valueOf())||t.toISOString()!==e)throw new Error("Native repair trajectory timestamp is invalid");return e}function H0(e,t,i){let r=lu(e,`Native repair trajectory event ${t+1}`);if(mk(r,I0,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(r.sequence)||r.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(O0(r.timestamp),typeof r.type!="string"||!T0.has(r.type))throw new Error("Native repair trajectory event type is invalid");if(vk(r.runId)!==i)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Pp(r.data,0,n,"Native trajectory event data"),lu(r.data,"Native repair trajectory event data"),{event:r,dataNodes:n.nodes,dataCharacters:n.characters}}function Cp(e){let t=lu(e,"Native repair trajectory projection"),i=Object.keys(t).sort(Rp),r=i.length===hk.length&&i.every((l,u)=>l===hk[u]);r||mk(t,j0,"Native repair trajectory projection");let n=vs(t.signatureHash,"Native repair trajectory signature hash");if(t.disposition!=="continue"&&t.disposition!=="warn"&&t.disposition!=="manual-stop"&&t.disposition!=="hard-stop")throw new Error("Native repair trajectory disposition is invalid");let a=t.overrideSummaryHash===null?null:vs(t.overrideSummaryHash,"Native repair trajectory override summary hash");if(a!==null&&t.disposition!=="continue")throw new Error("Native repair trajectory override must continue exactly once");if(r)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=vs(t.contractHash,"Native repair trajectory contract hash"),s=$0(t.failedAcceptanceIds),c=kp(t.failedCheckIds);if(!Number.isSafeInteger(t.maxVerifyFailures)||t.maxVerifyFailures<1)throw new Error("Native repair trajectory maximum Verify failures is invalid");return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:o,failedAcceptanceIds:s,failedCheckIds:c,maxVerifyFailures:t.maxVerifyFailures}}function D0(e,t){if(t.overrideSummaryHash===null){if(e.previousPhase!=="verify"||e.nextPhase!=="build"||e.verificationResult!=="fail")throw new Error("Native repair failure projection is only valid on a failed Verify-to-Build transition");return}if(t.disposition!=="continue"||e.previousPhase!=="build"||e.nextPhase!=="verify"||e.verificationResult!==null)throw new Error("Native repair override projection is only valid on a Build-to-Verify transition")}function L0(e,t){let i=t.filter(s=>s.kind==="failure"),r=i.length+1,n=e.maxVerifyFailures??pk;if(r>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=Sp({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},i),o=r>=n?"hard-stop":a<Ra.warningAtConsecutiveFailures?"continue":a<Ra.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function M0(e,t,i){let r=t.filter(a=>a.kind==="failure"),n=i?.maxVerifyFailures??pk;if(r.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(i?.disposition!=="manual-stop"||i.signatureHash!==e.signatureHash||r.at(-1)?.signatureHash!==e.signatureHash)throw new Error("Native repair trajectory override does not match the latest manual stop");if(t.some(a=>a.kind==="override"&&a.signatureHash===e.signatureHash))throw new Error("Native repair trajectory signature was already overridden")}function gk(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>Et.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=vk(e.runId);if(!Number.isSafeInteger(e.committedTrajectoryOffset)||e.committedTrajectoryOffset<0||e.committedTrajectoryOffset>e.trajectory.length)throw new Error("Native repair committed trajectory offset is invalid");let i=[],r=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=H0(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>Et.maxTotalDataNodes||c>Et.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,h=Object.hasOwn(f,"repairScopeHash")?vs(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?vs(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,fk)){if(r?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(h!==null&&n!==null&&h!==n||h===null&&(r?.disposition==="manual-stop"||r?.disposition==="hard-stop"))){i.length=0,r=null,n=h,o=0;continue}continue}if(d.type!=="state_transitioned")throw new Error("Native repair projection must belong to a state_transitioned event");let v=Cp(f[fk]);if(D0(f,v),v.overrideSummaryHash===null)v.contractHash!==null&&a!==null&&v.contractHash!==a&&(i.length=0,o=0),v.contractHash!==null&&(a=v.contractHash),v.contractHash===null&&h!==null&&n!==null&&h!==n&&(i.length=0,o=0),h!==null&&(n=h),L0(v,i),o+=1,i.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:v.signatureHash,...v.contractHash===null?{}:{failedAcceptanceIds:[...v.failedAcceptanceIds],failedCheckIds:[...v.failedCheckIds]}});else{if(r?.contractHash===null&&h!==null&&n!==null&&h!==n)throw new Error("Native repair override cannot cross implementation scope progress");M0(v,i,r);let m=i.at(-1);if(!m||m.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");i.push({kind:"override",revision:d.sequence,iteration:m.iteration,signatureHash:v.signatureHash,summaryHash:v.overrideSummaryHash})}if(r=v,i.length>Ra.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:i,latestProjection:r}}function wk(e){return gk(e).history}function yk(e){let t=gk(e).latestProjection;return t?{...t}:null}var Ni={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},gs=L("comet-native-runtime:v3:scope-reopen"),F0=[{skillVersion:"3",skillHash:L("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:L("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:L("comet-native-runtime:v1")}];function Nk(e){return e.skillVersion===Ni.definition.metadata.version&&e.skillHash===gs||F0.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var xp={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(i=>i.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};async function Tr(e){let i={sequence:(await it(e.changeDir,e.run.trajectoryRef)).length+1,timestamp:(e.now??new Date).toISOString(),type:e.type,runId:e.run.runId,data:e.data};return await FN(e.changeDir,e.run.trajectoryRef,i),i}async function vn(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:L(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await BN(e.changeDir,e.run.checkpointRef,t),t}function bk(e){return L(JSON.stringify({summary:e.summary,returnToBuild:e.returnToBuild??!1,confirmed:e.confirmed??!1,artifacts:[...e.artifacts??[]].sort(),noCodeReason:e.noCodeReason??null,verificationResult:e.verificationResult??null,verificationReport:e.verificationReport??null,allowPartialScopeHash:e.allowPartialScopeHash??null,partialReason:e.partialReason??null,repairOverrideSignature:e.repairOverrideSignature??null,repairOverrideSummary:e.repairOverrideSummary??null}))}var Ak=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],q0=new Set(Ak),_k=new Set([...Ak,"minimum_runtime_version","revision"]),W0=new Set([..._k,"operation"]),z0=512*1024,Ap=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),J0=new Set([...Ap,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),ws=class extends Error{constructor(i){super(`Native transition for ${i} requires doctor migration before recovery`);this.change=i;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function Ue(e,t){return V0.join(H(e,t),"transition.json")}function G0(e){return`transition-${e}`}async function U0(e,t,i){let r=G0(t);return dr(e,r,i)}async function gn(e,t,i,r){let n=await U0(e,t,i);try{return await r()}finally{await fr(n)}}function fu(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Tp(e,t){let i=Object.keys(e).find(r=>!t.has(r));if(i)throw new Error(`Native transition journal contains unknown field: ${i}`)}function du(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function bi(e,t){return uu(e,t)}function _p(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let i=e,r=Object.keys(i),n=r.find(u=>!J0.has(u)),a=[...Ap].find(u=>!Object.hasOwn(i,u)),o=Ap.size+(Object.hasOwn(i,"implementationScopeHash")?1:0)+(Object.hasOwn(i,"repairScopeHash")?1:0)+(Object.hasOwn(i,"repairStagnation")?1:0)+(Object.hasOwn(i,"returnToBuild")?1:0);if(n||a||r.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(i.previousPhase)||!["shape","build","verify","archive"].includes(i.nextPhase))throw new Error("Native transition journal event phases are invalid");if(i.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(i.returnToBuild!==void 0&&typeof i.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(Ep(i.summary,"Native transition journal event summary"),$t(i.summary)!==i.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(i.artifacts)||i.artifacts.length>128||i.artifacts.some(u=>typeof u!="string"||u.length===0||Buffer.byteLength(u,"utf8")>512))throw new Error("Native transition journal event artifacts are invalid");if(i.noCodeReason!==null&&(Ep(i.noCodeReason,"Native transition journal event no-code reason"),$t(i.noCodeReason)!==i.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(i.verificationResult!==null&&i.verificationResult!=="pass"&&i.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(i,"implementationScopeHash")?i.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||i.previousPhase!=="build"&&i.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(i,"repairStagnation")?Cp(i.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(i.previousPhase!=="verify"||i.nextPhase!=="build"||i.verificationResult!=="fail")||!u&&(i.previousPhase!=="build"||i.nextPhase!=="verify"||i.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(i,"repairScopeHash")?i.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||i.previousPhase!=="build"&&i.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:t,summary:i.summary,artifacts:[...i.artifacts],noCodeReason:i.noCodeReason,verificationResult:i.verificationResult,...i.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function K0(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e,r=Object.keys(i),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(r.length===n.size&&r.every(a=>n.has(a))&&i.reason==="spec-rebase")return _p({previousPhase:i.previousPhase,nextPhase:i.nextPhase,evidenceHash:i.evidenceHash,summary:i.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return _p(e,t)}function Ip(e,t,i=!1){if(e.change!==t)throw new Error("Native transition journal change mismatch");if(typeof e.id!="string"||e.id.length===0)throw new Error("Native transition journal id is invalid");if(typeof e.evidenceHash!="string"||!/^[a-f0-9]{64}$/u.test(e.evidenceHash))throw new Error("Native transition journal evidence hash is invalid");if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native transition journal timestamp is invalid");let r=i?K0(e.eventData,e.evidenceHash):_p(e.eventData,e.evidenceHash),n=Er(e.nextRun),a=e.previousRun===null?null:Er(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:r}}function kk(e,t,i=!1){if(e.skill!==Ni.definition.metadata.name||(i?!Nk(e):e.skillVersion!==Ni.definition.metadata.version||e.skillHash!==gs)||e.orchestration!==Ni.definition.orchestration.mode||e.pendingRef!==Nt.pendingRef||e.trajectoryRef!==Nt.trajectoryRef||e.contextRef!==Nt.contextRef||e.artifactsRef!==Nt.artifactsRef||e.checkpointRef!==Nt.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function Sk(e){return{runId:e.runId,skill:e.skill,skillVersion:e.skillVersion,skillHash:e.skillHash,orchestration:e.orchestration,pendingRef:e.pendingRef,trajectoryRef:e.trajectoryRef,contextRef:e.contextRef,artifactsRef:e.artifactsRef,checkpointRef:e.checkpointRef,retries:e.retries}}function Ek(e,t){if(e.status!=="running")throw new Error(`Native transition journal ${t} status must be running`);if(e.pending!==null)throw new Error(`Native transition journal ${t} pending action must be null`)}function jp(e,t,i,r=!1,n="advance"){let{previousRun:a,nextRun:o}=i;if(kk(o,"next Run",r||a!==null),Ek(o,"next Run"),o.runId!==t.run_id||o.currentStep!==t.phase)throw new Error("Native transition journal next Run does not match the next change state");if(n==="runtime-rebuild"){if(a!==null||e.phase==="shape"||t.phase!=="build"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native Runtime rebuild Run transition is invalid");return}if(a===null){if(e.run_id!==null||e.phase!=="shape"||o.iteration!==1||Object.keys(o.retries).length!==0)throw new Error("Native transition journal first Run transition is invalid");return}if(kk(a,"previous Run",!0),Ek(a,"previous Run"),e.run_id!==a.runId||a.currentStep!==e.phase||t.run_id!==a.runId)throw new Error("Native transition journal previous Run does not match the change state");if(o.iteration!==a.iteration+1)throw new Error("Native transition journal next Run iteration must advance exactly once");if(!uu(Sk(a),Sk(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function Y0(e,t,i){return L(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:i}))}function Tk(e,t,i){return e.phase!=="shape"&&t.phase==="build"&&i.verificationResult===null?"spec-rebase":"advance"}function Pk(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function $p(e,t,i,r,n=!1){let a=i.eventData,o=Pk(e),s=Pk(t);if(a.previousPhase!==e.phase||a.nextPhase!==t.phase)throw new Error("Native transition journal event phases do not match its states");if(e.archived||t.archived)throw new Error("Native transition journal cannot mutate an archived change");if(r==="runtime-rebuild"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&uu(e.spec_changes,t.spec_changes);if(e.phase==="shape"||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||!c||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native Runtime rebuild transition semantics are invalid");return}if(r==="evidence-retreat"){let c=e.name===t.name&&e.language===t.language&&e.brief===t.brief&&e.approval===t.approval&&("approved_contract_hash"in e?"approved_contract_hash"in t&&e.approved_contract_hash===t.approved_contract_hash:!("approved_contract_hash"in t))&&e.created_at===t.created_at&&e.run_id===t.run_id&&uu(e.spec_changes,t.spec_changes),l=bk({summary:a.summary,...a.returnToBuild?{returnToBuild:!0}:{}});if(!(e.phase==="archive"&&e.verification_result==="pass"||e.phase==="verify"&&e.verification_result==="pending")||t.phase!=="build"||t.verification_result!=="pending"||t.verification_report!==null||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||i.evidenceHash!==l||!c||o===null||s===null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null)throw new Error("Native transition journal evidence retreat semantics are invalid");return}if(r==="spec-rebase"){let c=Y0(e.name,a.summary,t.spec_changes),l=L(`spec-rebase:${e.name}:${a.summary}`);if(e.phase==="shape"||t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!=="pending"||t.verification_report!==null||!n&&i.evidenceHash!==c||n&&i.evidenceHash!==c&&i.evidenceHash!==l||"implementation_scope"in t&&(t.implementation_scope!==null||t.verification_evidence!==null||t.partial_allowance!==null))throw new Error("Native transition journal spec rebase semantics are invalid");return}if(e.phase==="shape"){if(t.phase!=="build"||a.verificationResult!==null||a.artifacts.length!==0||a.noCodeReason!==null||e.verification_result!=="pending"||t.verification_result!=="pending"||e.verification_report!==null||t.verification_report!==null||o!==null&&s!==null&&(o.implementation_scope!==null||o.verification_evidence!==null||o.partial_allowance!==null||s.implementation_scope!==null||s.verification_evidence!==null||s.partial_allowance!==null))throw new Error("Native transition journal Shape to Build semantics are invalid");return}if(e.phase==="build"){if(t.phase!=="verify"||a.verificationResult!==null||a.artifacts.length===0&&a.noCodeReason===null||t.verification_result!=="pending"||t.verification_report!==null||o!==null&&s!==null&&(s.implementation_scope===null||s.verification_evidence!==null||s.implementation_scope!==o.implementation_scope&&s.partial_allowance!==null&&s.partial_allowance===o.partial_allowance))throw new Error("Native transition journal Build to Verify semantics are invalid");return}if(e.phase==="verify"){let c=a.verificationResult==="pass"?"archive":"build";if(a.verificationResult!=="pass"&&a.verificationResult!=="fail"||t.phase!==c||a.artifacts.length!==0||a.noCodeReason!==null||t.verification_result!==a.verificationResult||t.verification_report===null||o!==null&&s!==null&&(o.implementation_scope===null||s.implementation_scope!==o.implementation_scope||s.partial_allowance!==o.partial_allowance||o.verification_evidence!==null||s.verification_evidence===null))throw new Error("Native transition journal Verify outcome semantics are invalid");return}throw new Error("Native transition journal cannot advance from Archive")}function Op(e,t){let i=fu(e);if(Tp(i,W0),i.schema!==pr)throw new Error(`Expected Native transition schema ${pr}`);let r=du(i.minimum_runtime_version,"Native transition minimum_runtime_version");if(r>3)throw new Error(`Native transition requires runtime protocol ${r}; current protocol is ${3}`);if(r!==3)throw new Error(`Native transition ${pr} minimum_runtime_version must be ${3}`);let n=du(i.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(i.operation!=="advance"&&i.operation!=="spec-rebase"&&i.operation!=="evidence-retreat"&&i.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=Ip(i,t),o=lt(i.previousState),s=lt(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if($p(o,s,a,i.operation),jp(o,s,a,!1,i.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:pr,minimum_runtime_version:3,revision:n,operation:i.operation,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function X0(e,t){let i=fu(e);if(Tp(i,q0),i.schema!==an)throw new Error(`Expected Native transition schema ${an}`);let r=Ip(i,t,!0),n=on(i.previousState),a=on(i.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return $p(n,a,r,Tk(n,a,r.eventData),!0),jp(n,a,r,!0),{schema:an,id:r.id,change:t,evidenceHash:r.evidenceHash,createdAt:r.createdAt,previousState:n,nextState:a,previousRun:r.previousRun,nextRun:r.nextRun,eventData:r.eventData}}function Hp(e,t){let i=fu(e);if(Tp(i,_k),i.schema!==Ti)throw new Error(`Expected Native transition schema ${Ti}`);if(du(i.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Ti} minimum_runtime_version must be 2`);let n=du(i.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=Ip(i,t,!0),o=di(i.previousState),s=di(i.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if($p(o,s,a,Tk(o,s,a.eventData),!0),jp(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Ti,minimum_runtime_version:2,revision:n,id:a.id,change:t,evidenceHash:a.evidenceHash,createdAt:a.createdAt,previousState:o,nextState:s,previousRun:a.previousRun,nextRun:a.nextRun,eventData:a.eventData}}function Q0(e,t){let i=fu(e);if(i.schema===pr)return{status:"current",journal:Op(i,t)};if(i.schema===an)return{status:"migration-required",journal:X0(i,t)};if(i.schema===Ti)return{status:"migration-required",journal:Hp(i,t)};throw new Error(`Unsupported Native transition journal schema: ${String(i.schema)}`)}async function Dp(e,t){let i=Ue(e,t),r=j(e,i);await T(r,i);try{let n=await re({root:r,file:i,maxBytes:z0,label:`Native transition journal ${t}`});return Q0(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Mi(e,t){let i=await Dp(e,t);if(!i)return null;if(i.status==="migration-required")throw new ws(t);return i.journal}function Rk(e,t){if(bi(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(bi(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function Ck(e,t){if(bi(e,t.nextState))return"next";if(bi(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function Z0(e){let{journal:t}=e;return Ik({sequence:e.sequence,timestamp:t.createdAt,type:e.type,runId:t.nextRun.runId,data:e.type==="run_started"?{runtime:"comet-native",phase:t.previousState.phase,transitionId:t.id}:{...t.eventData,transitionId:t.id}})}function Ik(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function xk(e,t){let i=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),r=i.filter(({event:a})=>a.type==="run_started"),n=i.filter(({event:a})=>a.type==="state_transitioned");if(i.length!==r.length+n.length||r.length>(t.previousRun===null?1:0)||n.length>1||t.previousRun===null&&n.length===1&&(r.length!==1||r[0].index>=n[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...r,...n]){let o=Z0({sequence:a.index+1,journal:t,type:a.event.type});if(!bi(Ik(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:r[0]?.event??null,transitioned:n[0]?.event??null}}async function hu(e,t,i){if(await pa(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Wl(e,t);let r=await Mi(e,t);if(!r)return null;let n=H(e,t),a=xk(await it(n,r.nextRun.trajectoryRef),r),[o,s]=await Promise.all([$e(n),He(e,t)]),c=Rk(o,r),l=Ck(s,r);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${r.change}; recovery journal was preserved`);if(c==="previous"&&(await un(n,r.nextRun),await i?.afterRunStateWritten?.(r)),!bi(await $e(n),r.nextRun))throw new Error(`Native transition Run content changed while continuing ${r.change}; recovery journal was preserved`);if(l==="previous"){let p=await Ql(e,r.nextState,r.previousState.revision);if(!bi(p,r.nextState))throw new Error(`Native transition change write diverged for ${r.change}; recovery journal was preserved`);await i?.afterChangeStateWritten?.(r)}if(!bi(await He(e,t),r.nextState))throw new Error(`Native transition change content changed while continuing ${r.change}; recovery journal was preserved`);let u=await Mi(e,t);if(!u||!bi(u,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was preserved`);let d=xk(await it(n,r.nextRun.trajectoryRef),r);r.previousRun===null&&(d.started||await Tr({changeDir:n,run:r.nextRun,type:"run_started",data:{runtime:"comet-native",phase:r.previousState.phase,transitionId:r.id},now:new Date(r.createdAt)}));let f=d.transitioned;f||(f=await Tr({changeDir:n,run:r.nextRun,type:"state_transitioned",data:{...r.eventData,transitionId:r.id},now:new Date(r.createdAt)})),await vn({changeDir:n,run:r.nextRun,trajectoryOffset:f.sequence,evidenceHash:r.evidenceHash,now:new Date(r.createdAt)});let[h,v]=await Promise.all([$e(n),He(e,t)]);Rk(h,{...r,previousRun:r.nextRun}),Ck(v,{...r,previousState:r.nextState});let m=await Mi(e,t);if(!m||!bi(m,r))throw new Error(`Native transition journal changed while continuing ${r.change}; it was not removed`);return await B0.rm(Ue(e,t),{force:!0}),r.nextState}async function jk(e,t,i){return se(e,`continue transition ${t}`,()=>gn(e,t,`continue transition ${t}`,()=>hu(e,t,i)))}import $k from"node:path";var eH="comet.native.contract.v1",tH="comet.native.acceptance-set.v1",Ok=/^[a-f0-9]{64}$/u,ys={maxAcceptanceCriteria:Do.maxCriteria};function Hk(e,t){let i=$k.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(r=>{let n=r.codePointAt(0)??0;return n<=31||n===127})||$k.posix.isAbsolute(i)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||i!==e||i==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function Dk(e){return D("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
|
|
205
|
+
`))}function iH(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.capability))throw new Error(`Invalid Native contract capability: ${e.capability}`);if(e.operation!=="create"&&e.operation!=="replace"&&e.operation!=="remove")throw new Error(`Invalid Native contract operation for ${e.capability}`);if(e.operation==="remove"){if(e.source!==null||e.markdown!==null||!e.baseHash?.match(Ok))throw new Error(`Remove contract ${e.capability} requires only a base hash`);return{snapshot:{capability:e.capability,operation:"remove",source:null,baseHash:e.baseHash,contentHash:null},markdown:null}}if(e.source===null||e.markdown===null)throw new Error(`${e.operation} contract ${e.capability} requires source content`);if(e.operation==="create"&&e.baseHash!==null)throw new Error(`Create contract ${e.capability} requires a null base hash`);if(e.operation==="replace"&&!e.baseHash?.match(Ok))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=Hk(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:Dk(e.markdown)},markdown:e.markdown}}function rH(e,t){return Lk(e.id,t.id)}function Lk(e,t){return e<t?-1:e>t?1:0}function Mk(e){let t=Hk(e.briefSource??"brief.md","Native brief source"),i=e.specs.map(iH).sort((d,f)=>Lk(d.snapshot.capability,f.snapshot.capability)),r=i.map(({snapshot:d})=>d.capability);if(new Set(r).size!==r.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...i.flatMap(({snapshot:d})=>d.source===null?[]:[d.source])];if(new Set(n).size!==n.length)throw new Error("Native contract contains duplicate artifact sources");let a=dl(e.briefMarkdown,t,ys.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of i)f===null||d.source===null||(a.push(...fl(f,d.source,ys.maxAcceptanceCriteria-a.length)),a.push(...Ay(f,d.source,ys.maxAcceptanceCriteria-a.length)));if(a.sort(rH),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>ys.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${ys.maxAcceptanceCriteria}-criterion acceptance budget`);let o=a.map(({id:d})=>d);if(new Set(o).size!==o.length)throw new Error("Native contract contains duplicate acceptance criteria");let s={source:t,contentHash:Dk(e.briefMarkdown)},c=i.map(({snapshot:d})=>d),l=D(tH,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:D(eH,u)}}var pu={maxSpecs:64,maxFileBytes:So,maxTotalBytes:4*1024*1024};async function Ca(e){if(e.specChanges.length>pu.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await Z({root:e.changeDir,ref:e.briefRef,maxBytes:pu.maxFileBytes}),i=t.size,r=[];for(let n of e.specChanges){if(n.operation==="remove"){r.push({capability:n.capability,operation:"remove",source:null,baseHash:n.base_hash,markdown:null});continue}if(!n.source)throw new Error(`Native contract ${n.capability} has no proposed spec source`);let a=await Z({root:e.changeDir,ref:n.source,maxBytes:pu.maxFileBytes});if(i+=a.size,i>pu.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");r.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:Mk({briefSource:t.ref,briefMarkdown:t.text,specs:r}),sourceCount:r.filter(n=>n.source!==null).length+1,totalBytes:i}}import{execFile as kH}from"node:child_process";import{promisify as SH}from"node:util";var IJ=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");import{promises as uH}from"fs";import xa from"path";var jr={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},Aa=/^[a-f0-9]{64}$/u;function mu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function vu(e,t,i){let r=new Set(t),n=Object.keys(e).filter(o=>!r.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${i} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${i} is missing field(s): ${a.join(", ")}`)}function Ir(e,t,i=2e3){if(typeof e!="string"||e.length===0||e.length>i)throw new Error(`${t} must be a non-empty string of at most ${i} characters`);return e}function Fk(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Lp(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function nH(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||xa.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let i=xa.posix.normalize(t);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return i}function Mp(e,t){return xa.join(H(e,t),"checkpoints","progress.json")}function $r(e,t){return xa.join(H(e,t),"checkpoint-journal.json")}function Fp(e,t,i){if(!Aa.test(i))throw new Error("Native checkpoint manifest hash is invalid");return xa.join(H(e,t),"checkpoints","manifests",`${i}.json`)}function aH(e){if(!Aa.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Bp(e,t,i){let r=await re({root:e,file:t,maxBytes:jr.maxDocumentBytes,label:i});return JSON.parse(r.bytes.toString("utf8"))}function oH(e,t){let i=mu(e,`checkpoint manifest artifact ${t}`);vu(i,["path","hash","size"],`checkpoint manifest artifact ${t}`);let r=nH(Ir(i.path,`checkpoint artifact ${t} path`,4096)),n=ci(r);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${r}`);if(typeof i.hash!="string"||!Aa.test(i.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:r,hash:i.hash,size:Lp(i.size,`checkpoint artifact ${t} size`)}}function gu(e,t){let i=mu(e,"Native checkpoint manifest");if(vu(i,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),i.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(i.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(i.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(i.artifacts.length>jr.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let r=i.artifacts.map(oH),n=[...r].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(r)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(r.map(o=>o.path)).size!==r.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Lp(i.totalBytes,"checkpoint manifest totalBytes");if(r.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>jr.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:r,totalBytes:a}}function Vp(e){return L(JSON.stringify(gu(e,e.change)))}function qp(e,t){let i=mu(e,"Native progress checkpoint");if(vu(i,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),i.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(i.change!==t)throw new Error("Native checkpoint change mismatch");let r=i.phase;if(r!=="shape"&&r!=="build"&&r!=="verify"&&r!=="archive")throw new Error("Native checkpoint phase is invalid");let n=Fk(i.previousRevision,"Native checkpoint previousRevision"),a=Fk(i.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=Ir(i.manifestHash,"Native checkpoint manifestHash",64);if(!Aa.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=aH(o);if(i.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=Ir(i.inputHash,"Native checkpoint inputHash",64);if(!Aa.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=Ir(i.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Lp(i.artifactCount,"Native checkpoint artifactCount");if(u>jr.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=Ir(i.summary,"Native checkpoint summary"),f=Ir(i.nextAction,"Native checkpoint nextAction");if($t(d)!==d||$t(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:Ir(i.id,"Native checkpoint id",128),change:t,phase:r,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function sH(e,t){let i=mu(e,"Native checkpoint journal");if(vu(i,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),i.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(i.change!==t)throw new Error("Native checkpoint journal change mismatch");let r=lt(i.previousState),n=lt(i.nextState),a=qp(i.checkpoint,t),o=gu(i.manifest,t),s=Ir(i.inputHash,"Native checkpoint journal inputHash",64),c=L(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!Aa.test(s)||s!==a.inputHash||s!==c||i.id!==a.id||i.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(r.name!==t||n.name!==t||n.revision!==r.revision+1||a.previousRevision!==r.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==Vp(o)||a.artifactCount!==o.artifacts.length)throw new Error("Native checkpoint journal state mismatch");return{schema:"comet.native.checkpoint-journal.v1",id:a.id,change:t,inputHash:s,createdAt:a.createdAt,previousState:r,nextState:n,checkpoint:a,manifest:o}}async function cH(e,t,i){let r=xa.resolve(e.projectRoot,...t.split("/"));if(!O(e.projectRoot,r)||O(e.nativeRoot,r)||O(e.runtimeDir,r))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=Kf(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await re({root:e.projectRoot,file:r,maxBytes:jr.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>i?.afterParentChainCaptured?.(t),afterOpen:()=>i?.afterOpen?.(t),beforeRead:()=>i?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function lH(e,t){let i=Mp(e,t),r=j(e,i);await T(r,i);try{return qp(await Bp(r,i,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Wp(e,t,i){let r=Fp(e,t,i),n=j(e,r);await T(n,r);let a=await Bp(n,r,"Native checkpoint manifest"),o=gu(a,t);if(zp(e,o),Vp(o)!==i)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function Or(e,t){let i=$r(e,t),r=j(e,i);await T(r,i);try{let n=sH(await Bp(r,i,"Native checkpoint journal"),t);return zp(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function Bk(e,t,i,r){let n=gu(i,t);zp(e,n);let a=Vp(n),o=Fp(e,t,a),s=j(e,o);await T(s,o);try{let c=await Wp(e,t,a);if(JSON.stringify(c)!==JSON.stringify(n))throw new Error("Native checkpoint manifest hash collision")}catch(c){if(c.code!=="ENOENT")throw c}return await ee(o,n,{containedRoot:s,beforeCommit:r?.beforeCommit}),a}function zp(e,t){for(let i of t.artifacts){let r=Kf(e,i.path);if(r)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${r}): ${i.path}`)}}async function Vk(e,t){let i=qp(t,t.change),r=await Wp(e,i.change,i.manifestHash),n=L(JSON.stringify({summary:i.summary,nextAction:i.nextAction,artifacts:r.artifacts}));if(i.inputHash!==n||i.artifactCount!==r.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=Mp(e,t.change),o=j(e,a);await T(o,a),await ee(a,i,{containedRoot:o})}async function qk(e){let t;try{t=await lH(e.paths,e.name)}catch(a){return{checkpoint:null,manifest:null,freshness:"stale",reasons:["checkpoint-progress-invalid"],findings:[{code:"checkpoint-progress-invalid",message:`Native progress checkpoint is invalid: ${a.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint file aside before retrying`,path:Mp(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let i=[],r=[];t.stateRevision!==e.stateRevision&&i.push("state-revision-changed");let n=null;try{n=await Wp(e.paths,e.name,t.manifestHash);let a=L(JSON.stringify({summary:t.summary,nextAction:t.nextAction,artifacts:n.artifacts}));if(t.inputHash!==a||t.artifactCount!==n.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");for(let o of n.artifacts)try{let s=await cH(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&i.push(`artifact-changed:${o.path}`)}catch{i.push(`artifact-unavailable:${o.path}`)}}catch(a){i.push("checkpoint-manifest-invalid"),r.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:Fp(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:i.length===0?"fresh":"stale",reasons:i,findings:r}}async function Wk(e,t,i){let r=await Or(e,t);if(!r)return null;if(await Bk(e,r.change,r.manifest)!==r.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Ql(e,r.nextState,r.previousState.revision,{allowPendingCheckpointRecovery:!0}),await i?.afterStateWritten?.(r),await Vk(e,r.checkpoint),await i?.afterProgressWritten?.(r),await uH.rm($r(e,t),{force:!0}),r}async function zk(e,t,i){return se(e,`continue checkpoint ${t}`,()=>gn(e,t,`continue checkpoint ${t}`,async()=>(await hu(e,t),Wk(e,t,i))))}import{constants as Jp,promises as Ot}from"node:fs";import _a from"node:path";var dH=/^[a-f0-9]{64}$/u,fH=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,Ns=512*1024;function hH(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function wu(e,t){let i={...e,birthtime:e.birthtimeMs},r={...t,birthtime:t.birthtimeMs};return vt(i,r)?z(i,r):z(i,r)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function pH(e,t){let i=_a.resolve(e),r=_a.resolve(t);if(!O(i,r))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=i;for(let o of["",..._a.relative(i,r).split(_a.sep).filter(Boolean)]){o&&(a=_a.join(a,o));let s=await Ot.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Ot.realpath(a);if(n.length>0&&!O(n[0].realPath,c))throw new Error("Native check receipt parent resolves outside the Native root");n.push({path:a,realPath:c,dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs})}return n}async function Jk(e){for(let t of e){let i=await Ot.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!hH(t,i)||await Ot.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function mH(e){if(!dH.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function vH(e){let t=fH.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function gH(e,t,i){return lr(H(e,t),mH(i))}async function wH(e,t,i){let r=await pH(i,_a.dirname(e)),n=await Ot.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>Ns)throw new Error(`Native check receipt exceeds ${Ns} bytes`);let[a,o]=await Promise.all([Ot.realpath(t),Ot.realpath(e)]);if(!O(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":Jp.O_RDONLY|Jp.O_NOFOLLOW|Jp.O_NONBLOCK,c=await Ot.open(e,s).catch(l=>{throw l.code==="ELOOP"||l.code==="ENXIO"?new Error("Native check receipt became unsafe while opening"):l});try{let[l,u,d]=await Promise.all([c.stat(),Ot.lstat(e),Ot.realpath(e)]);if(await Jk(r),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!wu(n,l)||!wu(l,u))throw new Error("Native check receipt changed while opening");let f=[],h=0,v=Buffer.allocUnsafe(16*1024);for(;;){let g=Ns+1-h,y=await c.read(v,0,Math.min(v.length,g),null);if(y.bytesRead===0)break;if(h+=y.bytesRead,h>Ns)throw new Error(`Native check receipt exceeds ${Ns} bytes`);f.push(Buffer.from(v.subarray(0,y.bytesRead)))}let[m,p,b]=await Promise.all([c.stat(),Ot.lstat(e),Ot.realpath(e)]);if(await Jk(r),!p.isFile()||p.isSymbolicLink()||b!==o||!O(a,b)||!wu(l,m)||!wu(l,p))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,h).toString("utf8"))}finally{await c.close()}}async function Gk(e,t,i){let r=vH(i),n=H(e,t),a=gH(e,t,r),o=j(e,a);await T(o,a);let s=nu(await wH(a,n,o));if(s.change!==t||s.receiptHash!==r)throw new Error("Native check receipt ref/hash/change mismatch");return s}var bs=class extends Error{recovery;constructor(t,i){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=i}};var CG=64*1024;var xG=3600*1e3;var AG=SH(kH);var EH=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function Uk(e,t){let i=[];for(let r of EH){let n=e.bindings[r],a=t[r];n!==a&&i.push(`${r}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:i.length===0,mismatches:i}}async function Kk(e){if(e.receipt.kind!=="static-inspection")return null;let t=await Gk(e.paths,e.state.name,e.receipt.evidence.checkReceiptRef);if(t.receiptHash!==e.receipt.evidence.checkReceiptHash)throw new Error("Native static receipt dependency hash mismatch");return t}var Hr=class extends Error{details;constructor(t){let i=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(r=>`${r.ref}${r.acceptanceId?`[${r.acceptanceId}]`:""} -> ${r.mismatches.join("; ")}`).join(" | ")}`;super(i),this.name="NativeVerificationReceiptBindingError",this.details=t}};function PH(e){return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...e.capture?{capture:e.capture}:{},createdAt:"1970-01-01T00:00:00.000Z",complete:e.complete,limits:e.limits,...e.policy?{policy:e.policy}:{},entries:e.entries,omitted:e.omitted,omittedCount:e.omittedCount,...e.omissionOverflow?{omissionOverflow:e.omissionOverflow}:{}}}async function RH(e){let t=PH(e.bundle.baseline),i=await qh(e.paths,t,{origin:"explicit",now:e.now});return hp({baseline:t,current:i,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function Xk(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await ps(e.paths,e.state.name,e.state.implementation_scope),i=await Ca({changeDir:ne(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),r=await RH({paths:e.paths,bundle:t,now:e.now}),n=[];return i.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),r!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:i.contract,contractHash:i.contract.contractHash,acceptanceHash:i.contract.acceptanceHash,findingCodes:n}}async function Qk(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await Xk(e),i=[...new Set(t.findingCodes)].sort();return{freshness:i.length===0?"fresh":"stale",findingCodes:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function CH(e){let t=await Z({root:ne(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:Ty(t.text)}}function xH(e){let{receipt:t,implementationScope:i}=e,r=[],n=fp({baseline:i.baseline,current:i.current,declaredArtifacts:i.scope.declaredArtifacts}).filter(o=>o.attributedTo.length>0&&o.after!==null),a=n.reduce((o,s)=>o+s.after.size,0);return(t.stale||t.sourceRevision!==e.sourceRevision||t.contract.expectedHash!==e.contractHash||t.contract.beforeHash!==e.contractHash||t.contract.afterHash!==e.contractHash||t.implementation.scopeHash!==i.scope.scopeHash||t.implementation.expectedSnapshotHash!==i.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==i.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==i.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&r.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&r.push("verification-receipt-outcome-mismatch"),r}function AH(e){return{change:e.state.name,sourceRevision:e.sourceRevision??e.state.revision,contractHash:e.contractHash,scopeHash:e.implementationScope.scope.scopeHash,snapshotHash:e.implementationScope.scope.currentProjectionHash,artifactHash:Np(e.implementationScope.scope.declaredArtifacts)}}async function Yk(e){let t=await ms(e.paths,e.state.name,e.ref),i=[];t.role!==e.role&&i.push(`role: expected ${e.role}, got ${t.role}`);let r=Uk(t,e.expectedBindings);if(i.push(...r.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&i.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),i.length>0)throw new Hr([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:i}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await Kk({paths:e.paths,state:e.state,receipt:t});if(n){let a=xH({receipt:n,sourceRevision:e.expectedBindings.sourceRevision,result:e.result,contractHash:e.contractHash,implementationScope:e.implementationScope});if(a.length>0)throw new Error(`Native static receipt dependency is invalid: ${a.join(", ")}`)}return t}async function _H(e){let t=AH({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),i=[];for(let r of e.requiredReceiptRefs){let n=await Yk({...e,ref:r,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof Hr)return i.push(...a.details),null;throw a});if(n!==null&&n.kind!=="static-inspection")throw new Error("Native required-check evidence must be a static-inspection receipt")}for(let r of e.trace.entries)if(r.status!=="missing")for(let n of r.evidenceRefs){let a=await Yk({...e,result:r.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:r.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof Hr)return i.push(...o.details),null;throw o});if(a!==null){if(a.kind!=="automated-check"&&a.kind!=="manual-evidence")throw new Error("Native acceptance evidence must be automated-check or manual-evidence");if(r.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(i.length>0)throw new Hr(i)}function Gp(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function yu(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:Gp(e.state.verification_result,"missing"),envelope:null};try{let[t,i]=await Promise.all([Xk(e),Pa(e.paths,e.state.name,e.state.verification_evidence)]);if(i.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:Gp(e.state.verification_result,"stale"),envelope:null};let r=await CH({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(r.hash!==i.reportHash||r.ref!==i.reportRef)&&n.push("verification-report-stale"),(i.result!==e.state.verification_result||i.implementationScopeRef!==e.state.implementation_scope||i.partialAllowanceRef!==e.state.partial_allowance||i.sourceRevision>=e.state.revision||i.contractHash!==t.bundle.scope.contractHash||i.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await _H({paths:e.paths,state:e.state,result:i.result,trace:i.acceptanceTrace,requiredReceiptRefs:i.requiredReceiptRefs,contractHash:i.contractHash,implementationScope:t.bundle,sourceRevision:i.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":i.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:i.contractHash,acceptanceHash:i.acceptanceCriteriaHash,implementationScopeHash:i.implementationScopeHash,reportHash:i.reportHash,envelopeHash:i.envelopeHash,partialAllowanceHash:i.partialAllowanceHash,skippedAcceptanceCount:i.acceptanceTrace.skipped},envelope:i}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:Gp(e.state.verification_result,"invalid"),envelope:null}}}function IH(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function eS(e){try{return await TH.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function jH(e,t){try{return(await Z({root:e,ref:t})).hash}catch(i){if(i.code==="ENOENT")return null;throw i}}async function $H(e,t,i){let r=Zl(e,i.capability);if(!O(e.nativeRoot,r))throw new Error(`Native canonical spec escapes its root: ${i.capability}`);let n=Zk.relative(e.nativeRoot,r).replaceAll("\\","/"),a=await jH(e.nativeRoot,n),o=null;if(i.operation!=="remove"){if(!i.source)throw new Error(`Native proposed spec is missing: ${i.capability}`);o=(await Z({root:ne(e,t),ref:i.source})).hash}return{capability:i.capability,operation:i.operation,expectedBaseHash:i.operation==="create"?null:i.base_hash,actualBaseHash:a,proposedHash:o}}async function OH(e,t){return eS(Ue(e,t))}async function Nu(e){let t=e.now??new Date,i=await He(e.paths,e.name),r=await kt(e.paths,e.name),n=await ye(e.paths.projectRoot),a=IH(i.name,t),o=Zk.resolve(e.paths.nativeRoot,...a.split("/"));if(!O(e.paths.nativeRoot,o))throw new Error("Native archive target escapes its root");let[s,c,l,u,d,f,h]=await Promise.all([Promise.all(i.spec_changes.map(v=>$H(e.paths,i.name,v))),yu({paths:e.paths,state:i,now:t}),cu(e.paths,i.name),pa(e.paths,i.name),ma(e.paths,i.name),OH(e.paths,i.name),eS(o)]);return yb({change:i.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:i.schema,revision:i.revision,phase:i.phase,archived:i.archived,pendingJournal:u||d||f,targetRef:a,targetExists:h,specs:s,evidence:c.evidence,workspace:r?.schema==="comet.native.workspace.v3"?{schema:r.schema,isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch,finish:r.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}import{promises as Up}from"node:fs";import Fi from"node:path";var HH="comet.native.archive-tree.v1",DH={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function rS(e){let t={...DH,...e};for(let[i,r]of Object.entries(t))if(!Number.isSafeInteger(r)||r<=0)throw new Error(`Native Archive content limit ${i} must be a positive safe integer`);return t}function tS(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,i)=>t.name.localeCompare(i.name)))}function iS(e,t,i,r){if(i.entryCount+=1,i.entryCount>r.maxEntries)throw new Error(`Native Archive content exceeds ${r.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>r.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${r.maxRefBytes} bytes: ${t.ref}`);let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(i.manifestBytes+=n+(e.length===0?0:1),i.manifestBytes+2>r.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${r.maxManifestBytes} bytes`);e.push(t)}async function nS(e,t,i,r,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await wt({root:e,directory:t,label:`Native Archive content directory ${Fi.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=tS(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=Fi.join(t,u.name),f=Fi.relative(e,d).replaceAll("\\","/"),h=await Up.lstat(d);if(u.isSymbolicLink()||h.isSymbolicLink())throw new Error(`Native Archive content must not contain symlinks or junctions: ${f}`);if(u.isDirectory()&&h.isDirectory()){iS(i,{ref:f,kind:"directory"},r,n),await nS(e,d,i,r,n,a+1);continue}if(!u.isFile()||!h.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let v=await re({root:e,file:d,maxBytes:n.maxFileBytes,label:`Native Archive content file ${f}`});if(r.totalBytes+=v.size,r.totalBytes>n.maxTotalBytes)throw new Error(`Native Archive content exceeds ${n.maxTotalBytes} total file bytes`);iS(i,{ref:f,kind:"file",hash:v.hash,size:v.size},r,n),await o.verify()}await o.verify();let l=await wt({root:e,directory:t,label:`Native Archive content directory ${Fi.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(tS(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${Fi.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function aS(e,t={}){let i=rS(t);e=Fi.resolve(e);let r=await Up.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await nS(e,e,n,{entryCount:0,totalBytes:0,manifestBytes:0},i,0);let o=JSON.stringify(n);if(Buffer.byteLength(o,"utf8")>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);return L(`${HH}\0${o}`)}async function ni(e,t={}){let i=rS(t);e=Fi.resolve(e);let r;try{r=await Up.lstat(e)}catch(n){if(n.code==="ENOENT")return null;throw n}if(r.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(r.isFile())return{kind:"file",hash:(await re({root:Fi.dirname(e),file:e,maxBytes:i.maxFileBytes,label:`Native Archive transaction file ${Fi.basename(e)}`})).hash};if(r.isDirectory())return{kind:"directory",hash:await aS(e,i)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}import{promises as rt}from"node:fs";import xe from"node:path";var Yp=16*1024*1024,LH=256*1024,MH=16*1024,ks="comet.native.archive-cas.v1";function FH(e,t){let i="runtime/",r=t.startsWith(i),n=r?e.runtimeDir:e.nativeRoot,a=r?t.slice(i.length):t,o=xe.resolve(n,...a.split("/"));if(!O(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function De(e,t){let i=FH(e,t);return T(j(e,i),i)}function Dr(e,t,i="file"){return t===null?e===null:e?.kind===i&&e.hash===t}function Ta(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function ft(e){let t=await ni(e.target);if(!Dr(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${Ta(t)}`);return t}async function Xp(e,t){let i=await hi(e,t),r=await re({root:e.runtimeDir,file:i.journal,maxBytes:LH,label:`Native Archive transaction journal ${t}`}),n=xl(JSON.parse(r.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function bu(e,t,i){let r=xl({...t,status:i}),n=await hi(e,r.id);return await ee(n.journal,r,{containedRoot:e.runtimeDir}),r}function ku(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function oS(e){return{...ku(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Lr(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function BH(e,t){return Lr(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function ie(e){try{return await rt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function ki(e){let t=await rt.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let i=oS(t),r=await re({root:j(e.paths,e.file),file:e.file,maxBytes:Yp,label:e.label}),n=await rt.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!BH(i,oS(n))||r.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:ku(n),size:r.size}}function VH(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${i} record must be an object`);let n=e;if(Object.keys(n).sort().join(",")!=="hash,identity,operationId,role,schema")throw new Error(`Archive CAS ${t.id} ${i} record has an invalid shape`);let o=n.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${i} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${i} identity has an invalid shape`);for(let c of["dev","ino","birthtimeMs"])if(typeof s[c]!="number"||!Number.isFinite(s[c])||s[c]<0)throw new Error(`Archive CAS ${t.id} ${i} identity ${c} is invalid`);if(n.schema!==ks||n.operationId!==t.id||n.role!==i||n.hash!==r)throw new Error(`Archive CAS ${t.id} ${i} record is not transaction-bound`);return{schema:ks,operationId:t.id,role:i,hash:r,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function Si(e,t,i,r){let n=await hi(e,t.id),a=xe.join(n.backups,".cas"),o=`.${xe.basename(r)}.comet-archive-cas-${t.id}-${i.id}`,s={directory:a,originalRecord:xe.join(a,`${i.id}.original.json`),postRecord:xe.join(a,`${i.id}.post.json`),candidate:xe.join(a,`${i.id}.candidate`),originalQuarantine:xe.join(xe.dirname(r),`${o}.original`),rollbackQuarantine:xe.join(xe.dirname(r),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>T(j(e,c),c))),s}async function Ht(e){if(!await ie(e.file))return null;let t=await re({root:e.paths.runtimeDir,file:e.file,maxBytes:MH,label:`Archive CAS ${e.operation.id} ${e.role} record`});return VH(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function Su(e){let t=await Ht(e);if(t){if(!Lr(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await fi({root:e.paths.runtimeDir,directory:xe.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let i={schema:ks,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await ee(e.file,i,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let r=await Ht(e);if(!r||!Lr(r.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return r}async function Re(e){let t=await ki({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!Lr(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function qH(e){let t=await ki({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),i=await Su({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Re({paths:e.paths,file:e.file,operation:e.operation,record:i,label:e.label}),i}async function WH(e){if(!await ie(e.quarantine)||await ie(e.target))return;let t=await Qt({root:j(e.paths,e.target),directory:xe.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await rt.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[i,r]=await Promise.all([rt.lstat(e.quarantine),rt.lstat(e.target)]);if(!Lr(ku(i),ku(r)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await rt.unlink(e.quarantine),await t.verify()}async function uS(e){if(await ie(e.quarantine)){await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await Qt({root:j(e.paths,e.target),directory:xe.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Re({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`}),await e.hooks?.afterArchiveTargetBound?.(e.phase,e.operation,e.target),await t.verify(),await Re({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await rt.rename(e.target,e.quarantine),await t.verify(),await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(i){throw await WH(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:i})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function wn(e){if(!await ie(e.file))return;await Re(e);let t=await Qt({root:j(e.paths,e.file),directory:xe.dirname(e.file),label:e.label});await t.verify(),await Re(e),await rt.unlink(e.file),await t.verify()}async function sS(e,t,i){if(!t.backup||t.expectedTargetHash===null)return;let r=await De(e,t.target),n=await De(e,t.backup),a=await ni(n);if(a!==null){if(!Dr(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await ft({target:r,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await wr({sourceRoot:j(e,r),source:r,targetRoot:j(e,n),target:n,maxBytes:Yp,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>i?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await ft({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function dS(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let i=await Si(e.paths,e.journal,e.operation,e.target),r=await Ht({paths:e.paths,file:i.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await ie(i.originalQuarantine)){if(!r)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Re({paths:e.paths,file:i.originalQuarantine,operation:e.operation,record:r,label:`Archive apply quarantine ${e.operation.target}`}),await sS(e.paths,e.operation,e.hooks),{record:r,quarantine:i.originalQuarantine}}if(!await ie(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return r??=await qH({paths:e.paths,file:e.target,recordFile:i.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Re({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive apply target ${e.operation.target}`}),await sS(e.paths,e.operation,e.hooks),await uS({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:i.originalQuarantine,record:r,hooks:e.hooks}),{record:r,quarantine:i.originalQuarantine}}async function cS(e){let t=await Si(e.paths,e.journal,e.operation,e.target);return await ie(t.candidate)?(await ki({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await fi({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await wr({sourceRoot:j(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:Yp,label:`Archive transaction staged file ${e.operation.staged}`,expectedHash:e.operation.stagedHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>e.hooks?.afterProtectedCopySourceParentCaptured?.("apply",e.operation.staged)}}),t.candidate)}async function zH(e){let t=e.operation.stagedHash,i=await Si(e.paths,e.journal,e.operation,e.target),r=await Ht({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t});if(r&&await ie(e.target))return await Re({paths:e.paths,file:e.target,operation:e.operation,record:r,label:`Archive write target ${e.operation.target}`}),await ie(i.candidate)&&await wn({paths:e.paths,file:i.candidate,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r;if(await ie(e.target)){let c=await cS(e),l=await ki({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await ki({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Lr(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return r=await Su({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await wn({paths:e.paths,file:c,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}let n=await cS(e),a=await ki({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await fi({root:j(e.paths,e.target),directory:xe.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await Qt({root:j(e.paths,e.target),directory:xe.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Re({paths:e.paths,file:n,operation:e.operation,record:{schema:ks,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await rt.link(n,e.target)}catch(c){throw c.code==="EEXIST"?new Error(`Archive write target ${e.operation.target} was created before exclusive install`,{cause:c}):c}await o.verify(),await e.hooks?.afterArchiveTargetInstalled?.("apply",e.operation,e.target);let s=await ki({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!Lr(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return r=await Su({paths:e.paths,file:i.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await wn({paths:e.paths,file:n,operation:e.operation,record:r,label:`Archive write candidate ${e.operation.target}`}),r}async function JH(e,t,i,r){let n=await De(e,i.target),a=await De(e,i.staged);if(await ft({target:a,expectedHash:i.stagedHash,label:`Archive transaction staged file ${i.staged}`}),i.expectedTargetHash!==null){let o=await Si(e,t,i,n);(!await Ht({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash})||!await ie(n))&&await dS({paths:e,journal:t,operation:i,target:n,hooks:r})}else{let o=await ni(n);if(o!==null&&!Dr(o,i.stagedHash))throw new Error(`Archive transaction target ${i.target} changed before create: ${Ta(o)}`)}await zH({paths:e,journal:t,operation:i,staged:a,target:n,hooks:r}),await ft({target:n,expectedHash:i.stagedHash,label:`Archive transaction target ${i.target}`})}async function GH(e,t,i,r){let n=await De(e,i.target);await dS({paths:e,journal:t,operation:i,target:n,hooks:r}),await ft({target:n,expectedHash:null,label:`Archive transaction target ${i.target}`})}async function UH(e,t){let i=await De(e,t.source),r=await De(e,t.target),[n,a]=await Promise.all([ni(i),ni(r)]);if(!(n===null&&Dr(a,t.expectedSourceHash,"directory"))){if(!Dr(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${Ta(n)}, target=${Ta(a)}`);await rt.mkdir(xe.dirname(r),{recursive:!0}),await rt.rename(i,r),await ft({target:r,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function KH(e,t,i,r){return i.type==="write"?JH(e,t,i,r):i.type==="remove"?GH(e,t,i,r):UH(e,i)}function YH(e){let t=0,i=!1,r=[];for(let n of e.events){if(n.type!=="operation-started"&&n.type!=="operation-completed")continue;let a=e.journal.operations[t];if(!a||n.operationId!==a.id)throw new Error(`Native Archive transaction ${e.journal.id} operation events are out of order`);if(n.type==="operation-started"){i=!0;continue}if(!i)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);r.push(a.id),t+=1,i=!1}return r}async function XH(e,t,i,r){let n=await De(e,i.target);if(i.type==="write"){let a=await De(e,i.staged);await ft({target:a,expectedHash:i.stagedHash,label:`Completed Archive staged file ${i.staged}`});let o=await Si(e,t,i,n),s=await Ht({paths:e,file:o.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!s)throw new Error(`Completed Archive target ${i.target} has no CAS identity`);if(await Re({paths:e,file:n,operation:i,record:s,label:`Completed Archive target ${i.target}`}),i.expectedTargetHash!==null){await ft({target:await De(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let c=await Ht({paths:e,file:o.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${i.target} has no original CAS identity`);if(await ie(o.originalQuarantine))await Re({paths:e,file:o.originalQuarantine,operation:i,record:c,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`)}return}if(i.type==="remove"){await ft({target:n,expectedHash:null,label:`Completed Archive target ${i.target}`}),await ft({target:await De(e,i.backup),expectedHash:i.expectedTargetHash,label:`Completed Archive backup ${i.backup}`});let a=await Si(e,t,i,n),o=await Ht({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${i.target} has no original CAS identity`);if(await ie(a.originalQuarantine))await Re({paths:e,file:a.originalQuarantine,operation:i,record:o,label:`Completed Archive original quarantine ${i.target}`});else if(!r)throw new Error(`Completed Archive original quarantine ${i.target} disappeared`);return}r||(await ft({target:await De(e,i.source),expectedHash:null,label:`Completed Archive move source ${i.source}`}),await ft({target:n,expectedHash:i.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${i.target}`}))}async function fS(e,t,i){let r=t.status==="prepared"?await bu(e,t,"applying"):t;if(r.status!=="applying")throw new Error(`Native Archive transaction ${r.id} cannot apply from ${r.status}`);let n=await Nr(e,r.id),a=YH({journal:r,events:n}),o=new Set(a),s=n.some(l=>l.type==="archive-finalization-started");for(let l of r.operations.slice(0,a.length))await XH(e,r,l,s);let c=o.size;for(let l of r.operations)o.has(l.id)||(l.id==="archive-change"&&await i?.beforeArchiveChangeMove?.(l),await Tt(e,r.id,"operation-started",l.id),await KH(e,r,l,i),await Tt(e,r.id,"operation-completed",l.id),c+=1,await i?.afterOperation?.(l,c));return r=await Xp(e,r.id),r}async function QH(e){try{return await Re(e),!0}catch{return!1}}async function ZH(e){await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await Qt({root:j(e.paths,e.target),directory:xe.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Re({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await rt.link(e.quarantine,e.target)}catch(i){throw i.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:i}):i}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await Re({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function Kp(e){if(e.operation.type!=="write")return;let t=await Si(e.paths,e.journal,e.operation,e.target);if(!await ie(t.candidate))return;let i=await ki({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await wn({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:ks,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:i.identity},label:`Archive write candidate ${e.operation.target}`})}async function eD(e,t,i,r){let n=await De(e,i.target),a=await Si(e,t,i,n),o=i.expectedTargetHash,s=o===null?null:await Ht({paths:e,file:a.originalRecord,operation:i,role:"original",expectedHash:o}),c=i.type==="write"?await Ht({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash}):null;if(i.type==="write"&&!c&&await ie(a.candidate)&&await ie(n)){let l=await ki({paths:e,file:a.candidate,expectedHash:i.stagedHash,label:`Archive write candidate ${i.target}`}),u=await ki({paths:e,file:n,expectedHash:i.stagedHash,label:`Archive rollback target ${i.target}`});Lr(l.identity,u.identity)&&(c=await Su({paths:e,file:a.postRecord,operation:i,role:"post",expectedHash:i.stagedHash,identity:u.identity}))}if(await ie(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${i.target} has no CAS identity`);await Re({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`})}if(await ie(n)&&!(s!==null&&await QH({paths:e,file:n,operation:i,record:s,label:`Archive rollback target ${i.target}`}))){if(!c){if(!s){let u=await ni(n);if(Dr(u,o)){await Kp({paths:e,journal:t,operation:i,target:n});return}}throw new Error(`Archive rollback target ${i.target} is occupied by an external object`)}await uS({paths:e,operation:i,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:r})}if(o===null){if(await ie(n))throw new Error(`Archive rollback create target ${i.target} could not be removed`)}else if(!await ie(n)){if(!s||!await ie(a.originalQuarantine))throw new Error(`Archive rollback original target ${i.target} cannot be recovered safely`);await ZH({paths:e,operation:i,target:n,quarantine:a.originalQuarantine,record:s,hooks:r})}s&&await ie(a.originalQuarantine)&&await wn({paths:e,file:a.originalQuarantine,operation:i,record:s,label:`Archive rollback original quarantine ${i.target}`}),c&&await ie(a.rollbackQuarantine)&&await wn({paths:e,file:a.rollbackQuarantine,operation:i,record:c,label:`Archive rollback quarantine ${i.target}`}),await Kp({paths:e,journal:t,operation:i,target:n}),await ft({target:n,expectedHash:o,label:`Archive rollback target ${i.target}`})}async function tD(e,t){let i=await De(e,t.source),r=await De(e,t.target),[n,a]=await Promise.all([ni(i),ni(r)]);if(!(Dr(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!Dr(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${Ta(n)}, target=${Ta(a)}`);await rt.mkdir(xe.dirname(i),{recursive:!0}),await rt.rename(r,i)}}async function hS(e,t,i){let r=await Nr(e,t.id);if(r.some(o=>o.type==="archive-finalization-started"||o.type==="archive-finalized"))throw new Error("An archive whose finalization started can only be recovered by continuing it");let n=await bu(e,t,"rolling-back");await Tt(e,n.id,"rollback-started");let a=new Set(r.filter(o=>o.type==="operation-started"||o.type==="operation-completed").map(o=>o.operationId));for(let o of[...n.operations].reverse())a.has(o.id)&&(o.type==="move"?await tD(e,o):await eD(e,n,o,i));return await Tt(e,n.id,"rollback-completed"),n=await bu(e,n,"rolled-back"),n}async function lS(e,t,i){let r=await De(e,i.target);if(i.type==="write"){let n=await Si(e,t,i,r),a=await Ht({paths:e,file:n.postRecord,operation:i,role:"post",expectedHash:i.stagedHash});if(!a)throw new Error(`Archive commit target ${i.target} has no CAS identity`);await Re({paths:e,file:r,operation:i,record:a,label:`Archive commit target ${i.target}`});return}await ft({target:r,expectedHash:null,label:`Archive commit target ${i.target}`})}async function iD(e,t){for(let i of t.operations){if(i.type==="move")continue;let r=await De(e,i.target),n=await Si(e,t,i,r);if(await ie(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${i.target}`);if(await lS(e,t,i),i.expectedTargetHash!==null){let a=await Ht({paths:e,file:n.originalRecord,operation:i,role:"original",expectedHash:i.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${i.target} has no original CAS identity`);await ie(n.originalQuarantine)&&await wn({paths:e,file:n.originalQuarantine,operation:i,record:a,label:`Archive commit original quarantine ${i.target}`})}await Kp({paths:e,journal:t,operation:i,target:r})}for(let i of t.operations)i.type!=="move"&&await lS(e,t,i)}async function Eu(e,t,i){return i==="commit"&&await iD(e,t),await Tt(e,t.id,i),i==="commit"?bu(e,t,"committed"):t}var SU=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});import{promises as rD}from"fs";import nD from"path";var Qp="comet.selection.v2",aD=16*1024;function Pu(e){return nD.join(e,".comet","current-change.json")}function oD(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function pS(e){return e===null||typeof e=="string"}function sD(e){let t;try{t=JSON.parse(e)}catch(i){throw new Error(`current change selection contains invalid JSON: ${i instanceof Error?i.message:String(i)}`,{cause:i})}if(!oD(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&&!pS(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Qp,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Qp)throw new Error(`current change selection schema must be ${Qp}`);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(!pS(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 Zp(e){let t;try{let r=Pu(e),{bytes:n}=await en(r,aD,{label:"current change selection"});t=n.toString("utf8")}catch(r){if(r.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${r instanceof Error?r.message:String(r)}`,{cause:r})}return{status:"selected",...sD(t)}}async function mS(e){await rD.rm(Pu(e),{force:!0})}async function vS(e,t,i){let r=await Zp(e);return r.status!=="selected"||r.selection.workflow!==t||r.selection.change!==i?!1:(await mS(e),!0)}import{promises as _s}from"node:fs";import Vr from"node:path";var om=Rn(Qr(),1);import{promises as HS}from"node:fs";import Dt from"node:path";import{execFileSync as cD}from"node:child_process";var lD=3e4,uD=8*1024*1024,em=class extends Error{constructor(i,r,n){super(`git ${r.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=i;this.args=r;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function dD(e,t){try{return cD("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:lD,maxBuffer:uD,windowsHide:!0})}catch(i){let r=typeof i.stderr=="string"?i.stderr.trim():Buffer.isBuffer(i.stderr)?i.stderr.toString("utf8").trim():"";throw new em(e,t,r)}}function Ae(e,t){return dD(e,t).trim()}function Ss(e){return Ae(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}import Le from"node:path";import{promises as xu}from"node:fs";import Ru from"node:path";function gS(...e){if(e.length===0)return Ru.resolve();if(Ru.win32.isAbsolute(e[0])){let t=Ru.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return Ru.resolve(...e)}var Cu=class extends Error{constructor(i,r,n){super(i,n);this.preparation=r;this.name="NativeWorkspacePreparationError"}preparation};var im="comet.native.supervisor.v2",fD=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function hD(e,t){let i=Le.relative(Le.resolve(e),Le.resolve(t));return i===""||!Le.isAbsolute(i)&&!i.startsWith(`..${Le.sep}`)}function pD(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function mD(e,t,i){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(i))throw new Error("Native Supervisor parent and child names are invalid");return gS(e,".worktrees",`${t}-${i}`)}function bS(e,t){return Le.join(We(e,t),"supervisor")}function kS(e,t){return Le.join(bS(e,t),"state.json")}function SS(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==im)throw new Error(`Native Supervisor state schema must be ${im}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(typeof a!="string"||a.length===0)throw new Error(`Native Supervisor integration field ${n} is invalid`);if(Es(t.integration.targetCommit,"Native Supervisor target commit"),Es(t.integration.headCommit,"Native Supervisor integration head commit"),!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let i=new Set,r=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(i.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(i.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&Es(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if(Es(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),r.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(r.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function Mr(e,t){try{let i=await xu.readFile(kS(e,t),"utf8"),r=JSON.parse(i);return SS(r),r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Ia(e,t){SS(t),await xu.mkdir(e.changesRuntimeDir,{recursive:!0}),await ee(kS(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Es(e,t){if(!fD.test(e))throw new Error(`${t} must be a Git commit`)}function rm(e){return structuredClone(e)}function ES(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function PS(e){Es(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:r})=>r)),i=e.contract.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.depends_on],status:r.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null}));for(let r of i)for(let n of r.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${r.name} depends on unknown child ${n}`);return{schema:im,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:i,history:[],finalVerification:{status:"pending",summary:null}}}async function nm(e){let t=pD(e.parent),i=xi(e.paths.projectRoot,t);if(!i)return null;let r=xi(e.paths.projectRoot,e.targetBranch);if(!r)return null;let n=Jt(e.paths.projectRoot).map(o=>Le.resolve(o)).find(o=>fe(o).currentBranch===t);if(!n)return null;let a=PS({parent:e.parent,targetBranch:e.targetBranch,targetCommit:r,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(i!==r){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=i}return ES(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function RS(e){if(!Ss(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=Ae(e.integration.worktree,["rev-parse","--show-toplevel"]);if(Le.resolve(t)!==Le.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let i=Ae(e.integration.worktree,["branch","--show-current"]);if(i!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${i||"(detached)"}`);return Ae(e.integration.worktree,["rev-parse","HEAD"])}async function vD(e){let t=xi(e.paths.projectRoot,e.state.integration.targetBranch);if(!t||t===e.state.integration.targetCommit)return null;let i=e.state;if(RS(i)!==i.integration.headCommit)throw new Error("Native Supervisor integration head changed before target refresh");try{Ae(i.integration.worktree,["merge","--no-edit",i.integration.targetBranch])}catch(o){throw new Error(`Native Supervisor target drift requires conflict resolution in ${i.integration.worktree}`,{cause:o})}let n=Ae(i.integration.worktree,["rev-parse","HEAD"]),a=rm(i);return a.integration.headCommit=n,a.finalVerification={status:"pending",summary:null},ES(a,{kind:"target-refreshed",child:null,runId:null,summary:`Target ${i.integration.targetBranch} was refreshed before delivery`}),a.stateVersion+=1,await Ia(e.paths,a),a}async function Ps(e){let i=await Mr(e.paths,e.state.parent)??e.state;if(i.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before delivery; reload status first");if(i.finalVerification.status!=="passed")throw new Error("Native Supervisor delivery requires a passed final verification");if(!i.children.every(({status:v})=>v==="integrated"||v==="archived"))throw new Error("Native Supervisor delivery requires every child to be integrated");let n=Jt(e.paths.projectRoot).map(v=>Le.resolve(v)).find(v=>fe(v).currentBranch===i.integration.targetBranch);if(!n)throw new Error(`Native Supervisor target branch worktree is unavailable: ${i.integration.targetBranch}`);if(!Ss(n))throw new Error(`Native Supervisor target worktree is not clean: ${n}`);let a=Ae(n,["rev-parse","HEAD"]);if((()=>{try{return Ae(n,["merge-base","--is-ancestor",i.integration.headCommit,a]),!0}catch{return!1}})()){let v=await yS({paths:e.paths,state:i,targetCommit:a});if(await NS({paths:e.paths,plan:v}),i.children.every(({status:p})=>p==="archived"))return await tm(e.paths,i.parent),{state:i,targetRoot:n,targetCommit:a};let m=rm(i);for(let p of m.children)p.status="archived";return m.stateVersion+=1,await Ia(e.paths,m),await tm(e.paths,i.parent),{state:m,targetRoot:n,targetCommit:a}}let c=RS(i);if(c!==i.integration.headCommit)throw new Error("Native Supervisor integration head changed after final verification");let l=xi(e.paths.projectRoot,i.integration.targetBranch),u=(()=>{if(!l)return!1;try{return Ae(i.integration.worktree,["merge-base","--is-ancestor",l,c]),!0}catch{return!1}})();if(l!==c&&!u&&l!==i.integration.targetCommit&&await vD({paths:e.paths,state:i}))throw new Error("Native Supervisor target changed; parent integration checks must be rerun before delivery");let d=await yS({paths:e.paths,state:i,targetCommit:c});l!==c&&Ae(n,["merge","--ff-only",i.integration.branch]);let f=Ae(n,["rev-parse","HEAD"]);if(f!==c)throw new Error("Native Supervisor target did not receive the verified integration head");let h=rm(i);for(let v of h.children)v.status="archived";return await NS({paths:e.paths,plan:d}),h.stateVersion+=1,await Ia(e.paths,h),await tm(e.paths,i.parent),{state:h,targetRoot:n,targetCommit:f}}function CS(e,t){return Le.join(bS(e,t),"cleanup.json")}function wS(e){let t=Jt(e.paths.projectRoot).map(s=>Le.resolve(s)),i=Le.resolve(process.cwd()),r=[{root:e.state.integration.worktree,branch:e.state.integration.branch},...e.state.children.map(({name:s})=>({root:mD(e.paths.projectRoot,e.state.parent,s),branch:`comet/supervisor/${e.state.parent}/${s}`}))].map(s=>({...s,root:Le.resolve(s.root)})),n=e.targetCommit,a=[e.state.integration.branch,...e.state.children.map(({name:s})=>`comet/supervisor/${e.state.parent}/${s}`)],o=r.flatMap(s=>{let c=t.find(l=>l===s.root);return c?[{...s,root:c}]:[]});for(let s of o){if(hD(s.root,i))throw new Error(`Native Supervisor cannot clean the current worktree: ${s.root}`);if(!Ss(s.root))throw new Error(`Native Supervisor cleanup requires a clean worktree: ${s.root}`);let c=fe(s.root).currentBranch;if(!c)throw new Error(`Native Supervisor worktree is detached: ${s.root}`);if(c!==s.branch)throw new Error(`Native Supervisor cleanup found unexpected branch ${c} for ${s.root}; expected ${s.branch}`);try{Ae(e.paths.projectRoot,["merge-base","--is-ancestor",c,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${c}`)}}for(let s of a)if(ko(e.paths.projectRoot,s))try{Ae(e.paths.projectRoot,["merge-base","--is-ancestor",s,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${s}`)}return{parent:e.state.parent,targetCommit:e.targetCommit,worktrees:o.map(({root:s})=>s),expectedBranches:Object.fromEntries(o.map(({root:s,branch:c})=>[s,c])),branches:a}}async function yS(e){let t=CS(e.paths,e.state.parent);try{let r=JSON.parse(await xu.readFile(t,"utf8"));if(r.parent===e.state.parent&&r.targetCommit===e.targetCommit&&Array.isArray(r.worktrees)&&r.expectedBranches&&typeof r.expectedBranches=="object"&&Array.isArray(r.branches)){let n=wS(e);return{parent:r.parent,targetCommit:r.targetCommit,worktrees:[...new Set([...r.worktrees,...n.worktrees])],expectedBranches:{...r.expectedBranches,...n.expectedBranches},branches:[...new Set([...r.branches,...n.branches])]}}}catch(r){if(r.code!=="ENOENT")throw r}let i=wS(e);return await ee(t,i,{containedRoot:e.paths.changesRuntimeDir}),i}async function NS(e){for(let t of e.plan.worktrees){if(!Jt(e.paths.projectRoot).map(a=>Le.resolve(a)).includes(Le.resolve(t)))continue;let r=e.plan.expectedBranches[t];if(!r)throw new Error(`Native Supervisor cleanup has no expected branch for ${t}`);let n=fe(t).currentBranch;if(n!==r)throw new Error(`Native Supervisor cleanup found unexpected branch ${n??"(detached)"} for ${t}; expected ${r}`);Ae(e.paths.projectRoot,["worktree","remove",t])}for(let t of e.plan.branches)ko(e.paths.projectRoot,t)&&Ae(e.paths.projectRoot,["branch","-d",t])}async function tm(e,t){await xu.rm(CS(e,t),{force:!0})}function xS(e){let t=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:[],status:i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:i.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:i})=>i==="ready").map(({name:i})=>i),allDone:t.every(({status:i})=>i==="integrated"||i==="archived")}}var AS="children.yaml",Rs="comet.native.children.v1",ja="comet.native.children.v2",DS=ja,gD=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_S=new Set(["schema","children"]),wD=new Set(["schema","acceptance_index","children"]),yD=new Set(["name","depends_on","covers"]),ND=new Set(["name","summary","depends_on"]),bD=new Set(["name","depends_on","covers"]);function _u(e,t,i=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${i}`);return e}function Au(e,t,i){let r=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(r.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...r.length>0?[`unexpected ${r.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${i} fields are invalid: ${a.join("; ")}`)}}function TS(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((i,r)=>i.localeCompare(r,"en"))}function am(e,t){let i=Dt.normalize(Dt.resolve(e)),r=Dt.normalize(Dt.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function kD(e){let t=new Map(e.map(a=>[a.name,a])),i=new Set,r=new Set,n=a=>{if(!r.has(a)){if(i.has(a))throw new Error(`Native children dependency cycle includes ${a}`);i.add(a);for(let o of t.get(a).depends_on)n(o);i.delete(a),r.add(a)}};for(let a of e)n(a.name)}function IS(e,t,i=t){let r=new Set(t);for(let o of e){let s=o.covers.filter(c=>!r.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function SD(e,t,i){let r={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===DS&&e.acceptance_index){let n=i.requiredAcceptanceIds??t??[],a=Object.keys(e.acceptance_index);r.missing=n.filter(c=>!(c in e.acceptance_index)),r.extra=a.filter(c=>!n.includes(c));let o=new Map((i.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of n){let l=o.get(c),u=e.acceptance_index[c];l&&u&&(u.source!==l.source||u.text!==l.text)&&r.mismatched.push(c)}let s=new Set(a);for(let c of e.children)r.unknownCovers.push(...c.covers.filter(l=>!s.has(l)));return r.uncovered=a.filter(c=>!jS(e.children,c)),$S(r)?r:null}if(e.schema===Rs&&t){let n=new Set(t);for(let a of e.children)r.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return r.uncovered=t.filter(a=>!jS(e.children,a)),$S(r)?r:null}return null}function jS(e,t){return e.some(i=>i.covers.includes(t))}function $S(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function sm(e){let t=new Set(e.acceptance.filter(({source:i})=>i===e.brief).map(({id:i})=>i));if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let i=[...e.history].reverse().find(({outcome:r})=>r==="fail");for(let r of i?.unresolved_ids??[])t.add(r)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...t]}}function ED(e){let t=_u(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),i={};for(let[r,n]of Object.entries(t)){let a=_u(n,`Native children acceptance_index.${r}`);if(Au(a,new Set(["source","text"]),`Native children acceptance_index.${r}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${r}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${r}.text must be a non-empty string`);i[r]={source:a.source,text:a.text}}return i}function PD(e,t,i){let r=i.requiredAcceptanceIds??t??[],n=Object.keys(e),a=r.filter(c=>!(c in e)),o=n.filter(c=>!r.includes(c));if(a.length>0||o.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${a.join(", ")||"none"}; extra ${o.join(", ")||"none"}`);let s=new Map((i.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of r){let l=s.get(c);if(!l)continue;let u=e[c];if(u.source!==l.source||u.text!==l.text){let d=["source","text"].filter(f=>u[f]!==l[f]);throw new Error(`Native children acceptance_index.${c} does not match the acceptance catalog: copy ${d.join(", ")} exactly from the current acceptance catalog`)}}}function RD(e,t,i={}){let r=(0,om.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${r.errors[0].message}`);let n=_u(r.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Rs&&a!==ja)throw Au(n,_S,"Native children contract"),new Error(`Native children schema must be ${Rs} or ${ja}`);let o=a===Rs?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Au(n,o==="indexed-v2"?wD:_S,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((f,h)=>{let v=_u(f,`Native child ${h}`);if(Au(v,o==="indexed-v2"?bD:o==="summary-v2"?ND:yD,`Native ${s} child fields (child ${h})`),typeof v.name!="string"||!gD.test(v.name))throw new Error(`Native child ${h} name is invalid`);let m=o==="summary-v2";if(m){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:m?v.summary:null,depends_on:TS(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?TS(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:f})=>f);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let u=new Set(l);for(let f of c){let h=f.depends_on.filter(v=>!u.has(v));if(h.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${h.join(", ")}`)}kD(c);let d=i.policy==="advisory";if(a===DS){if(o==="indexed-v2"){let f=ED(n.acceptance_index);d||PD(f,t,i);let h=Object.keys(f);return d||IS(c,h,h),{schema:ja,acceptance_index:f,children:c}}return{schema:ja,children:c}}return t&&!d&&IS(c,t),{schema:Rs,children:c}}async function cm(e){let t=Dt.join(e.changeDir,AS);try{await HS.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let i=await Z({root:e.changeDir,ref:AS}),r=e.policy==="advisory",n=r?{...e.validation,policy:"advisory"}:e.validation??{},a=RD(i.text,e.acceptanceIds,n);return{contract:a,size:i.size,drift:r?SD(a,e.acceptanceIds,e.validation??{}):null}}function CD(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let i=e.slice(t.index+t[0].length);return i.split(/^#\s+/mu,1)[0]??i}function xD(e){let t=CD(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let i=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),r=t.match(/\bChild\s+\d+\b/giu);return Math.max(i?.length??0,r?.length??0)>=2}async function LS(e){try{let t=await Z({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return xD(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function lm(e){return D("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:i,text:r})=>({id:t,source:i,text:r})),children:e.children})}async function AD(e){let t=Jt(e.projectRoot);t.some(r=>am(r,e.projectRoot))||t.push(e.projectRoot);let i=[];for(let r of[...new Set(t.map(n=>Dt.resolve(n)))]){let n=await ye(r);n&&i.push({projectRoot:r,paths:await qe(r,n.native.artifact_root),parent:am(r,e.projectRoot)})}return i.some(({parent:r})=>r)||i.push({projectRoot:e.projectRoot,paths:e,parent:!0}),i}async function _D(e,t){let i=Dt.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Ze(i)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function TD(e,t){let i;try{i=await HS.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Dt.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Ze(o);t.has(s.name)&&r.push({file:o,state:s})}catch{}return r}function ID(e,t,i){let r=Dt.relative(e.projectRoot,t);if(!r||r===".."||r.startsWith(`..${Dt.sep}`))return null;let n=r.split(Dt.sep).join("/");try{let a=(0,om.parseDocument)(Ae(e.projectRoot,["show",`${i}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:ct(a.toJS({mapAsMap:!1}))}catch{return null}}function jD(e,t,i){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==i||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${i??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function OS(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Cs(e){let t=Dt.join(e.paths.changesDir,e.state.name),i=await LS(t),r=await cm({changeDir:t,validation:sm(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:p})=>p)}:{},policy:"advisory"});if(!r)return e.state.children_contract_hash?{...i?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:i?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let n=lm({acceptance:e.state.acceptance,children:r.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n&&!r.drift;if(r.contract.schema===ja){let p=await Mr(e.paths,e.state.name);if(!p){let y=e.state.workspace.target_branch??e.state.workspace.change_branch;if(y){let E=await nm({paths:e.paths,parent:e.state.name,targetBranch:y,contract:r.contract});E&&(p=E,await Ia(e.paths,E))}}if(p){let y=xS(p);return e.state.children_contract_hash!==n||r.drift?{...y,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(E=>({...E,message:r.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...y,schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let b=new Map(r.contract.children.map(y=>[y.name,y])),g=r.contract.children.map(y=>({name:y.name,summary:y.summary,dependsOn:[...y.depends_on],covers:[],status:o&&y.depends_on.every(E=>r.contract.children.filter(({name:k})=>k!==y.name).every(({name:k})=>k!==E))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let y of g){if(y.status!=="ready")continue;b.get(y.name).depends_on.length>0&&(y.status="pending")}return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:g,readyChildren:g.filter(({status:y})=>y==="ready").map(({name:y})=>y),allDone:!1}}let s=await AD(e.paths),c=new Set(r.contract.children.map(({name:p})=>p)),l=new Map,u=new Map;for(let p of s){let b=p.parent&&a?`refs/heads/${a}`:"HEAD";for(let g of await TD(p,c)){let y={...g,source:p,committedState:ID(p,g.file,b)};l.set(g.state.name,[...l.get(g.state.name)??[],y])}for(let g of c){let y=await _D(p,g);y&&u.set(g,[...u.get(g)??[],{source:p,state:y}])}}let d=new Map;for(let p of r.contract.children){let b=(l.get(p.name)??[]).find(({source:E,committedState:k})=>E.parent&&k?.name===p.name&&OS(k,a));if(b){d.set(p.name,{kind:"done",phase:b.state.phase,projectRoot:b.source.projectRoot,message:null});continue}let g=l.get(p.name)?.[0];if(g){d.set(p.name,{kind:"blocked",phase:g.state.phase,projectRoot:g.source.projectRoot,message:`Native child ${p.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let y=u.get(p.name)??[];y.length>1?d.set(p.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${p.name} has multiple active workspace owners`}):y[0]&&d.set(p.name,jD(y[0].state,y[0].source,a))}let f=new Map(r.contract.children.map(p=>[p.name,p])),h=new Map,v=p=>{let b=h.get(p);if(b)return b;let g=f.get(p),E=g.depends_on.map(v).every(({status:P})=>P==="done"),k=d.get(p),S=k?.kind==="active"&&E?g.depends_on.filter(P=>!(l.get(P)??[]).some(({source:F,committedState:$})=>am(F.projectRoot,k.projectRoot)&&$?.name===P&&OS($,a))):[],R,N=k?.message??null;k?.kind==="done"?(R=E?"done":"blocked",E||(N=`Native child ${p} was merged before its dependencies`)):k?.kind==="active"?(R=E&&S.length===0?"active":"blocked",E?S.length>0&&(N=`Native child ${p} does not include merged dependencies: ${S.join(", ")}`):N=`Native child ${p} started before its dependencies merged`):k?.kind==="blocked"?R="blocked":(R=o&&E?"ready":"pending",o||(N="Parent Shape confirmation is required"));let w={name:p,summary:g.summary,dependsOn:[...g.depends_on],covers:[...g.covers],status:R,phase:k?.phase??null,projectRoot:k?.projectRoot??null,message:N};return h.set(p,w),w},m=r.contract.children.map(({name:p})=>v(p));return{schema:r.contract.schema,...i?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:m,readyChildren:m.filter(({status:p})=>p==="ready").map(({name:p})=>p),allDone:m.every(({status:p})=>p==="done")}}var xs="skill-coordinated";function OD(e){return e.state_version+1}function HD(e){return e.map(t=>({...t,result:"pending",reason:null}))}function DD(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:hr(e.summary),completed_at:e.completedAt}}function um(e){let t=ct(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let i=(e.now??new Date).toISOString(),r=Yn(t,DD({state:t,outcome:"recovery",summary:e.reason,completedAt:i})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?HD(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return ct({...r,phase:"build",status:"active",state_version:OD(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:a,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,stop_reason:void 0,next_action:"submit-builder-candidate"}})}import{promises as FS}from"node:fs";import As from"node:path";function Tu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Iu(e,t,i){let r=Object.keys(e).filter(n=>!t.has(n));if(r.length>0)throw new Error(`${i} has unknown field(s): ${r.join(", ")}`)}function Ei(e,t,i=!1){if(typeof e!="string"||!i&&e.length===0)throw new Error(`${t} must be ${i?"a string":"a non-empty string"}`);return e}function MS(e,t){return e===null?null:Ei(e,t)}function $u(e,t,i=0){if(!Number.isSafeInteger(e)||e<i)throw new Error(`${t} must be a safe integer greater than or equal to ${i}`);return e}function LD(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function MD(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ju(e,t,i){if(typeof e!="string"||!t.includes(e))throw new Error(`${i} must be one of: ${t.join(", ")}`);return e}function dm(e,t){if(e===null)return null;let i=Ei(e,t);if(Number.isNaN(Date.parse(i)))throw new Error(`${t} must be an ISO timestamp`);return i}function fm(e,t){let i=Ei(e,t);if(!As.isAbsolute(i))throw new Error(`${t} must be absolute`);return As.resolve(i)}function FD(e,t){let i=`Native local checks[${t}]`,r=Tu(e,i);if(Iu(r,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),i),!Array.isArray(r.argv)||r.argv.length===0)throw new Error(`${i}.argv must be a non-empty array`);let n=r.argv.map((l,u)=>Ei(l,`${i}.argv[${u}]`,!0)),a=ju(r.status,["planned","running","passed","failed","interrupted"],`${i}.status`),o=dm(r.startedAt,`${i}.startedAt`),s=dm(r.completedAt,`${i}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${i} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${i} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${i} completed check requires startedAt and completedAt`);let c=$u(r.timeoutMs,`${i}.timeoutMs`);if(c<1)throw new Error(`${i}.timeoutMs must be positive`);return{id:Ei(r.id,`${i}.id`),name:Ei(r.name,`${i}.name`),operationId:Ei(r.operationId,`${i}.operationId`),status:a,repeatable:MD(r.repeatable,`${i}.repeatable`),timeoutMs:c,executionCount:$u(r.executionCount,`${i}.executionCount`),argv:n,cwd:fm(r.cwd,`${i}.cwd`),exitCode:LD(r.exitCode,`${i}.exitCode`),startedAt:o,completedAt:s,log:Ei(r.log,`${i}.log`)}}function hm(e){let t="Native local execution state",i=Tu(e,t);if(Iu(i,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),i.schema!==Lo)throw new Error(`Native local execution schema must be ${Lo}`);let r=Tu(i.workspace,"Native local workspace");Iu(r,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(i.execution!==null){let o=Tu(i.execution,"Native local execution");Iu(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=dm(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Ei(o.operationId,"Native local execution.operationId"),stage:ju(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:ju(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:MS(o.executionId,"Native local execution.executionId"),status:ju(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:$u(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(i.checks))throw new Error("Native local checks must be an array");let a=i.checks.map(FD);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:Lo,change:Ei(i.change,"Native local change"),basedOnStateVersion:$u(i.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:fm(r.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:fm(r.worktreeRoot,"Native local workspace.worktreeRoot"),branch:MS(r.branch,"Native local workspace.branch")},execution:n,checks:a}}function yn(e){return hm({schema:Lo,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:As.resolve(e.projectRoot),worktreeRoot:As.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Ou(e){let t;try{t=await FS.readFile(e,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}let i;try{i=JSON.parse(t)}catch(r){throw new Error(`Native local execution state is invalid JSON: ${r.message}`,{cause:r})}return hm(i)}async function Fr(e,t,i={}){let r=hm(t);await FS.mkdir(As.dirname(e),{recursive:!0}),await ee(e,r,i)}import{promises as BD}from"node:fs";function Br(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
206
|
+
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Bi(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function VD(e){return e.archived?qt(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?qt(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?qt(e.language,"Verification passed; ready to archive","验收通过,可归档"):qt(e.language,"Verification passed","验收通过")}function qD(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?qt(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?VD(e):e.verification_result==="blocked"?qt(t,"Blocked","已阻塞"):e.verification_result==="fail"?qt(t,"Failed","未通过"):qt(t,"Pending","待处理")}function WD(e){let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===xs?xs:"host-attested"),i=t===xs&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":i?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","skill-coordinated":i?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function zD(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let i=e.language,r=d=>fd(i,d),n=(d,f)=>qt(i,d,f),a=e.acceptance.map(d=>`| ${Bi(d.id)} | ${Bi(d.result)} | ${Bi(d.source)} | ${Bi(d.text)} | ${Bi(Br(d.reason))} |`).join(`
|
|
207
|
+
`),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(d=>{let f=d.argv_display.map(Br).join(" ");return`| ${Bi(Br(d.name))} | ${Bi(f||"—")} | ${Bi(d.cwd_ref)} | ${d.status} | ${d.exit_code??"—"} | ${d.duration_ms} ms |`})].join(`
|
|
208
|
+
`),s=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(d=>`- **${d.owner}**: ${Br(d.reason)}${d.acceptance_ids.length>0?` (acceptance: ${d.acceptance_ids.join(", ")})`:""} — next: \`${d.resolution_action}\``).join(`
|
|
209
|
+
`),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(d=>`- ${Br(d)}`).join(`
|
|
210
|
+
`),l=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(d=>`| ${d.goal_cycle} | ${d.iteration} | ${d.attempt} | ${d.outcome} | ${d.unresolved_ids.join(", ")||"—"} | ${Bi(Br(d.summary))} | ${d.completed_at} |`)].join(`
|
|
211
211
|
`),u=t?.finalVerification.layers?`
|
|
212
212
|
## ${n("Supervisor evidence layers","Supervisor 分层证据")}
|
|
213
213
|
|
|
@@ -224,13 +224,13 @@ generated_from_state_version: ${e.state_version}
|
|
|
224
224
|
|
|
225
225
|
## ${r("currentResult")}
|
|
226
226
|
|
|
227
|
-
- ${n("Result","结果")}: **${
|
|
228
|
-
- ${n("Verification status","验证情况")}: **${
|
|
227
|
+
- ${n("Result","结果")}: **${qD(e)}**
|
|
228
|
+
- ${n("Verification status","验证情况")}: **${WD(e)}**
|
|
229
229
|
- ${n("Goal cycle","目标周期")}: ${e.loop.goal_cycle}
|
|
230
230
|
- ${n("Iteration","迭代")}: ${e.verification.iteration}
|
|
231
231
|
- ${n("Verifier attempt","验证器尝试次数")}: ${e.verification.attempt}
|
|
232
232
|
- ${n("Completed","完成时间")}: ${e.verification.completed_at}
|
|
233
|
-
- ${n("Summary","摘要")}: ${
|
|
233
|
+
- ${n("Summary","摘要")}: ${Br(e.verification.summary)}
|
|
234
234
|
|
|
235
235
|
## ${r("acceptance")}
|
|
236
236
|
|
|
@@ -260,21 +260,27 @@ ${e.history_overflow.dropped_entries>0?`${n("Earlier history entries folded into
|
|
|
260
260
|
|
|
261
261
|
`:""}## ${r("conclusion")}
|
|
262
262
|
|
|
263
|
-
${
|
|
264
|
-
`}function xD(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let i=Number(t[1]);return Number.isSafeInteger(i)?i:null}async function ju(e){let t;try{t=await SD.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=xD(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function $u(e){await fe(e.file,CD(e.state,e.supervisor))}var jS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,AD="comet-state.yaml",_D="state.json",KK=Ws("en");function Dt(e,t){if(!jS.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Fr.join(e.changesDir,t);if(!O(e.changesDir,i))throw new Error("Native change path escaped");return i}function Et(e,t){return Fr.join(Dt(e,t),AD)}function wn(e,t){return Fr.join(qe(e,t),_D)}async function Br(e,t){try{let i=await Cs.readFile(Et(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function TD(e){return de(e).currentBranch}async function Ia(e,t){return Qe(Et(e,t))}async function ID(e){let t=await tn({file:Et(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let i=Fr.join(Dt(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,i),await Cs.rm(i,{force:!0})}return t}async function jD(e){let t=Dt(e.paths,e.state.name),i=Fr.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await Cs.readdir(i,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!jS.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(r.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=Fr.join(t,...s.split("/")),l=await Cs.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=Fr.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let f=await Cs.lstat(u);if(!f.isFile()||f.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(f){if(f.code!=="ENOENT")throw f}a.push({capability:o.name,operation:d,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function $D(e){let t=Dt(e.paths,e.state.name),i=await Q({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await Q({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return ll({briefMarkdown:i.text,specs:r})}async function $S(e){let t=await jD(e),i=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,l)=>{let u=e.state.spec_changes[l];return u!==void 0&&c.capability===u.capability&&c.source===u.source&&(c.operation===u.operation||i?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await $D({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!_y(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await om({changeDir:Dt(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c),validation:am({...e.state,acceptance:n})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?sm({acceptance:n,children:o.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function OS(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...Un(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:dr(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete r.children_contract_hash;let n=await ID({paths:e.paths,previous:t,next:r});return await Mr(wn(e.paths,t.name),gn({portableState:n,projectRoot:e.paths.projectRoot,branch:TD(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Ou(e){if(e.state.verification===null)return"not-applicable";let t=Fr.join(Dt(e.paths,e.state.name),"verification.md");return await ju({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await $u({file:t,state:e.state}),"rebuilt")}async function HS(e){let t=await Ia(e.paths,e.name),i=wn(e.paths,e.name);try{let r=await Iu(i);return r===null?{state:t,local:null,localStatus:"missing"}:r.change!==t.name||r.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}var rY=16*1024;async function Hu(e){let t=await Xp(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Wl(t.selection.change),t.selection)}function DS(e){return bu(e.projectRoot)}async function xs(e,t){return await Vn(e.projectRoot),dS(e.projectRoot,"native",t)}var IY=16*1024*1024,Du=class extends Error{constructor(i,r,n,a){super(`Canonical spec conflict for ${i}: expected ${r??"(missing)"}, actual ${n??"(missing)"}`);this.capability=i;this.expectedHash=r;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},As=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function LS(e,t){let i=t.operations.find(r=>r.id==="archive-change");if(!i||i.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return ja.resolve(e.nativeRoot,...i.target.split("/"))}async function FS(e,t,i){let r=await wr(e,t.id);if(r.some(p=>p.type==="archive-finalized"))return;let n=r.some(p=>p.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let p=t.operations.find(g=>g.id==="archive-change");if(!p||p.type!=="move"||!p.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let b=await ri(LS(e,t));if(b?.kind!=="directory"||b.hash!==p.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=LS(e,t),o=ja.join(a,_e),s=await ob(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=H(e,s.name),l=await je(c);if(!l||l.runId!==s.run_id||l.currentStep!=="archive"&&!(l.currentStep===null&&l.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let u=l;if(l.currentStep==="archive"){let p=qm(yi,l,new Set,Rp,void 0);if(!p.action)throw new Error(p.reason??"Native archive produced no action");u=Wm(yi,p.state,{actionId:p.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},Rp,void 0)}let d=M(`archive:${t.id}:${s.name}`),f=await tt(c,u.trajectoryRef),h=f.filter(p=>p.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(h.length>1||h.some(p=>p.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let v=h.find(p=>p.type==="state_transitioned"),m={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(v&&t.schema==="comet.native.transaction.v2"&&(!OD(v.data,m)||v.runId!==u.runId||v.timestamp!==t.createdAt||v!==f.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!n&&(s.archived||l.currentStep===null||h.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(n||(t.schema==="comet.native.transaction.v2"?(await Nu(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await Zn(e,t,"archive-finalization-started")),!s.archived){let p={...s,archived:!0};await ab(o,p)}v||(v=await Ar({changeDir:c,run:u,type:"state_transitioned",data:m,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await pn({changeDir:c,run:u,trajectoryOffset:v.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await cn(c,u),await xs(e,s.name),t.schema==="comet.native.transaction.v2"?await Nu(e,t,"archive-finalized"):await Zn(e,t,"archive-finalized")}async function fm(e,t){let i=qe(e,t);try{let r=await MS.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Runtime cleanup target is not a real directory: ${i}`);return await T(e.runtimeDir,i),await MS.rm(i,{recursive:!0,force:!0}),null}catch(r){return r.code==="ENOENT"?null:`Archived change ${t}, but local Runtime cleanup failed: ${r.message}`}}async function HD(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await wr(e,t.id)).some(c=>c.type==="operation-started")){let c=await vu({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new As(c,"Native Archive facts changed before the first transaction operation")}let o=await sS(e,t,{...i,beforeArchiveChangeMove:async c=>{await i?.beforeArchiveChangeMove?.(c);let l=await Oe(e,t.change),u=await mu({paths:e,state:l,now:new Date(t.createdAt)});if(l.phase!=="archive"||l.archived||l.verification_result!=="pass"||!["complete","partial"].includes(u.freshness)||u.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${u.findingCodes.join(", ")||u.freshness}`)}});await FS(e,o,i);let s=await Nu(e,o,"commit");return{journal:s,runtimeCleanupWarning:await fm(e,s.change)}}let r=await tN(e,t);await FS(e,r,i);let n=await Zn(e,r,"commit");return{journal:n,runtimeCleanupWarning:n.change?await fm(e,n.change):null}}function DD(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(ja.resolve(t.projectRoot)!==ja.resolve(e.projectRoot)||ja.resolve(t.nativeRoot)!==ja.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function BS(e){return oe(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await lr(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await wt(e.paths,e.transactionId),r=i.schema==="comet.native.transaction.v2"?await Kp(e.paths,e.transactionId):i;return DD(e.paths,r),r.status==="committed"?(r.change&&await fm(e.paths,r.change),r):r.status==="rolled-back"?r:e.strategy==="continue"?(await HD(e.paths,r)).journal:r.schema==="comet.native.transaction.v2"?cS(e.paths,r):Rl(e.paths,r)}finally{await ur(t)}},{allowedTransactionId:e.transactionId})}import{promises as QD}from"fs";async function VS(e,t){let i=[],r=H(e,t.name),n=sr(r,yt.stateRef),a;try{a=await je(r)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=sr(r,a.trajectoryRef),s=await sa(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await tt(r,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=sr(r,a.checkpointRef);try{let u=await oa(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}var MD=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function LD(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function FD(e){return e?e.map(LD).join(" "):null}function BD(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(i=>{if(i.startsWith('"')&&i.endsWith('"'))try{return JSON.parse(i)}catch{return i.slice(1,-1)}return i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i})}function Mt(e,t,i,r={}){return{input:e,flags:t,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function VD(e){return e.map(t=>Mt(t,[],null))}function qD(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[Mt("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push(Mt("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),i.push(Mt("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),Mt("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push(Mt("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),i.push(Mt("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),Mt("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Ue(e,t){let i=t.commandArgs===void 0?BD(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?FD(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??VD(t.requiredInputs??[])}}function Mu(e){let i=(e.findings??[]).filter(d=>!ca(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||MD.test(d.code)),a=i.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=i.find(d=>d.code==="repair-stagnation-stop"),s=i.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=i.find(d=>d.code==="runtime-missing"),l=[...new Set(i.map(d=>d.requiredAction))].sort();if(e.done)return Ue(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Ue(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[Mt("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return Ue(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Ue(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Ue(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Ue(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[Mt("summary",["--summary"],"<summary>")]});if(n)return Ue(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return Ue(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[Mt("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Ue(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?Ue(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Ue(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Ue(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),Ue(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[Mt("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Ue(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Ue(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=qD(e.state);return Ue(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import _s from"path";var qS=8,WD={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function zD(e){let t=WD[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:ca(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function JD(e,t,i){if(!i.path)return null;let r;if(_s.isAbsolute(i.path)?r=_s.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=_s.resolve(re(e,t.name),...i.path.split(/[\\/]/u)):r=_s.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!O(e.projectRoot,r))return null;let n=_s.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function GD(e,t,i){return e==="next"?`comet native next ${t.name} --summary "<summary>"${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function hm(e){return e.findings.map(t=>{let i=zD(t.code);return{code:t.code,message:t.message,severity:i.severity,path:JD(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:GD(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let r={error:0,warning:1,info:2};return r[t.severity]-r[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function pm(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,qS),truncated:t.length>qS}}var WS=240,zS=8,Lu=50;function JS(e){let t=Array.from(e);return t.length<=WS?e:`${t.slice(0,WS-1).join("")}…`}function UD(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function KD(e){let t=[...new Set(e.map(UD))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,zS),reasonCount:e.length,codesTruncated:t.length>zS};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Lu),reasonsTruncated:e.length>Lu}}}async function GS(e){let t=null;try{let s=await jr(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:Ir(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:Ir(e.paths,e.state.name)}}let i=await Mk({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=KD(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:Tr.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:JS(i.checkpoint.summary),nextAction:JS(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:i.checkpoint.manifestRef,artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:Tr.maxArtifacts}}async function YD(e,t){let i=H(e,t.name),r=await je(i);if(!r||!t.run_id||r.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await oa(i,r.checkpointRef);if(!n||n.runId!==r.runId||n.stateVersion!==r.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await tt(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function XD(e,t){let i=await YD(e,t);return{committed:i,latest:pk(i),history:hk(i)}}async function US(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await XD(e,t),n=r.latest;if(!n)return null;let a=r.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:r.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var ZD=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,$a=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function mm(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function eM(e){return(await Hu(e))?.change??null}function tM(e,t,i=!1,r){return Mu({state:e,archiveReady:t,evidenceRetreat:i}).command}async function iM(e,t){let i=re(e,t.name),r=[...(await Zh(i,t.brief)).findings,...(await db(e,t)).findings,...await VS(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await aa(e,t.name);if(n===null)r.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await jl(e,n);a.complete||r.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){r.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await Pa({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){r.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await Mi(e,t.name)&&r.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){r.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?r.push(...(await ep(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function vm(e,t,i){let r=await eM(e)===t,n=await To(e,t),a=await GN(e,t),o;try{let w=await mi(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.state.spec_changes.length,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};o=w.state}catch(w){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:w.message}}if(n.status!=="available"){let w={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},P=hm({paths:e,state:o,findings:[w]}),F=Mu({state:o,findings:P});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:F.command,archiveReady:!1,inspection:{freshness:"stale",codes:[w.code],reasonCount:1,codesTruncated:!1},findingSummary:pm(P),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:F,workspace:a,runtime:n,...i?.details?{findings:P}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:w.message}:{}}}let s=await GS({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await US(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let w=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:w,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(i?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let w=await Pa({changeDir:re(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),P=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let Le=await Sa(e,o.name,o.verification_evidence);for(let le of Le.acceptanceTrace.entries)P.set(le.acceptanceId,le.status==="failed"?"failed":le.status==="missing"?"missing":"satisfied")}let F=Sy({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:P,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),$=F.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",F.nextCursor,"--project-root",e.projectRoot]:null;u={...F,...$?{nextPageCommand:mm($),nextPageArgs:$}:{}}}catch(w){if(i.acceptanceCursor)throw w;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let w=await nu(e,o.name,{tolerateInvalidSiblings:!0});d.push(...w.findingCodes.map(P=>({code:P,message:`Native change overlap is visible in the current root: ${P}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let w=await bt(e,o.name);if(w)if(w.schema==="comet.native.workspace.v3"){let P=await ua({paths:e,identity:w});P.state==="drifted"&&P.code&&f.push({code:P.code,message:P.message??"Native workspace binding is no longer valid"})}else{let P=await Yo({paths:e,identity:w});f.push(...P.findingCodes.map(F=>({code:F,message:`Native workspace advisory changed: ${F} (${P.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let h=[],v=!1;if(o.phase==="verify"){let w=await Gk({paths:e,state:o});v=w.freshness!=="fresh",h.push(...w.findingCodes.map(P=>({code:P,message:`Native Verify implementation scope is not current: ${P}`})))}let m=null,p=[];if(o.phase==="archive")try{m=await vu({paths:e,name:o.name}),p.push(...m.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{p.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let b=[...await iM(e,o),...s.findings,...d,...f,...h,...l,...p].filter((w,P,F)=>F.findIndex($=>$.code===w.code&&$.path===w.path)===P),g=hm({paths:e,state:o,findings:b}),y=g.filter(w=>!ca(w.code)),E=o.phase==="archive"&&m?.ready===!0&&y.length===0,k=v||o.phase==="archive"&&(m?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),S=g.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),R=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",N=g.find(w=>w.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:S||R?null:tM(o,E,k,i?.clarificationMode),archiveReady:E,inspection:s.inspection,findingSummary:pm(g),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Mu({state:o,findings:g,archiveReady:E,evidenceRetreat:k,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:g.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:Lu,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:g.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...N?{error:N.message}:{}}}async function rM(e){let t;try{t=await Xt({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await QD.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>$a.maxChanges))throw new Error(`Native status exceeds ${$a.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}function Fu(e,t){let i=t.toString(36),r=D("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${r}`}function nM(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=ZD.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let r=D("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:i});if(t[3]!==r)throw new Error("Native status cursor integrity check failed");return i}async function aM(e,t){let i=await rM(e),r=D("comet.native.status-names.v1",i),n=nM({namesHash:r,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(n,n+$a.maxItems).map(u=>vm(e,u,{includeConflictFindings:!1,clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let u of a){let d=[...o,u],f=n+d.length,h={schema:"comet.native.status-page.v1",total:i.length,offset:n,items:d,nextCursor:f<i.length?Fu(r,f):null,nextPageCommand:f<i.length?mm(["comet","native","status","--cursor",Fu(r,f)]):null,nextPageArgs:f<i.length?["comet","native","status","--cursor",Fu(r,f)]:null,limits:{...$a}};if(Buffer.byteLength(JSON.stringify(h),"utf8")>$a.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(u)}let s=n+o.length,c=s<i.length?Fu(r,s):null,l=c?["comet","native","status","--cursor",c]:null;return{schema:"comet.native.status-page.v1",total:i.length,offset:n,items:o,nextCursor:c,nextPageCommand:l?mm(l):null,nextPageArgs:l,limits:{...$a}}}async function gm(e,t){return(await aM(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}import{createHash as EM,randomUUID as PM}from"node:crypto";import{constants as km,promises as X}from"node:fs";import ce from"node:path";var qu=En(Yr(),1);import{randomUUID as oM}from"crypto";import{promises as ZS}from"fs";import ym from"path";import{isDeepStrictEqual as Nm}from"util";var yn=/^[a-f0-9]{64}$/u,sM=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),cM=new Set(["sourceHash","targetHash","nextJournal"]),lM=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),KS=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),uM=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function Bu(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function YS(e){return JSON.stringify(e,null,2)+`
|
|
265
|
-
`}function
|
|
266
|
-
`)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(r&&a.schema===Ne?Oa(a,u.previousState)||Oa(a,u.nextState):a.schema===ye&&(QS(a,u.previousState)||QS(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(r&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(i.transitionSupersede!==void 0){if(!n||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==ye)throw new Error("Schema migration transition supersede target schema is invalid");s=hM(i.transitionSupersede,t,a,i.id)}let c;if(i.runRetreat!==void 0){if(!n||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!i.runRetreat||typeof i.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");Bu(i.runRetreat,uM,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=kr(l.previousRun),d=kr(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!yn.test(l.evidenceHash)||!l.eventData||typeof l.eventData!="object"||Array.isArray(l.eventData))throw new Error("Schema migration Run retreat is invalid");if(a.schema!==ye||a.phase!=="build"||a.run_id!==d.runId||u.runId!==d.runId||u.currentStep!=="verify"&&u.currentStep!=="archive"||d.currentStep!=="build"||d.iteration!==u.iteration+1)throw new Error("Schema migration Run retreat does not match target state");c={previousRun:u,nextRun:d,evidenceHash:l.evidenceHash,eventData:l.eventData}}if(o&&c||s&&c)throw new Error("Schema migration has conflicting recovery plans");return{schema:"comet.native.schema-migration.v1",id:i.id,change:t,fromSchema:i.fromSchema,toSchema:i.toSchema,sourceHash:i.sourceHash,targetHash:i.targetHash,createdAt:i.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function Is(e,t){let i=Ts(e,t),r=j(e,i);await T(r,i);try{let n=await yl({root:r,file:i,maxBytes:524288,label:"Native schema migration journal"});return pM(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function mM(e,t,i){let r=await aa(e,t),n=r?await jl(e,r):await $l(e,{now:new Date(i),origin:"legacy-migration"});if(!n.complete){let a=Lh(n),o=n.omitted.reduce((c,l)=>(c[l.reason]=(c[l.reason]??0)+1,c),{}),s=n.omissionOverflow?.count??0;throw s>0&&(o.overflow=s),new da(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}r===null&&await Vh(e,t,n)}async function eE(e){try{return await Qt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function vM(e,t){let i=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:i.nextRun.runId,data:{...i.eventData,migrationId:e.id,evidenceHash:i.evidenceHash}}}async function tE(e,t){let i=t.transitionSupersede,r=H(e,t.change),n=await tt(r,i.nextRun.trajectoryRef),a=n.map((s,c)=>({event:s,index:c})).filter(({event:s})=>s.data.migrationId===t.id);if(a.length>1)throw new Error(`Native schema migration event ${t.id} is duplicated`);let o=a[0];if(o&&!Nm(o.event,vM(t,o.index+1)))throw new Error(`Native schema migration event ${t.id} changed`);return{trajectoryLength:n.length,sequence:o?.event.sequence??null}}async function gM(e,t,i){if(!t.transitionSupersede)return;let r=Ge(e,t.change),n=await eE(r);if(n===t.transitionSupersede.sourceHash)return;if(n!==null)throw new Error(`Native superseded transition source changed for ${t.change}: expected ${t.transitionSupersede.sourceHash}, actual ${n}`);let a=H(e,t.change),o=await je(a),s=await tE(e,t),c=await oa(a,t.transitionSupersede.nextRun.checkpointRef);if(!i||!o||!Bi(o,t.transitionSupersede.nextRun)||s.sequence===null||!c||c.runId!==t.transitionSupersede.nextRun.runId||c.stateVersion!==t.transitionSupersede.nextRun.iteration||c.trajectoryOffset!==s.sequence||c.contextHash!==null||c.artifactsHash!==M(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function wM(e,t,i){let r=t.transitionSupersede;if(!r)return;let n=H(e,t.change),a=await je(n);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Bi(a,r.nextRun)){if(!Bi(a,r.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await cn(n,r.nextRun),await i?.afterRunStateWritten?.(t)}if(!Bi(await je(n),r.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await tE(e,t);if(o.sequence===null){let l=await Ar({changeDir:n,run:r.nextRun,type:"state_migrated",data:{...r.eventData,migrationId:t.id,evidenceHash:r.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await i?.afterTrajectoryWritten?.(t),await pn({changeDir:n,run:r.nextRun,trajectoryOffset:o.sequence,evidenceHash:r.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=Ge(e,t.change),c=await eE(s);if(c!==null){if(c!==r.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await ZS.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function yM(e,t,i){if(!t.runRetreat)return;let r=H(e,t.change),n=await je(r);if(!n)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Bi(n,t.runRetreat.nextRun)){if(!Bi(n,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await cn(r,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await tt(r,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await Ar({changeDir:r,run:t.runRetreat.nextRun,type:"state_migrated",data:{...t.runRetreat.eventData,migrationId:t.id,evidenceHash:t.runRetreat.evidenceHash},now:new Date(t.createdAt)}),a=[...a,o]),await i?.afterTrajectoryWritten?.(t),await pn({changeDir:r,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function NM(e,t,i){let r=await Is(e,t);if(!r)return null;if(await ha(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=ym.join(re(e,t),_e),a=await Qt(n);if(await gM(e,r,a===r.targetHash),await mM(e,t,r.createdAt),a!==r.targetHash){if(a!==r.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${r.sourceHash}, actual ${a}`);await fe(n,(0,qu.stringify)(bm(r.nextState))),await i?.afterStateWritten?.(r)}if(r.transition){let o=Ge(e,t),s=await Qt(o);if(s!==r.transition.targetHash){if(s!==r.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${r.transition.sourceHash}, actual ${s}`);await Z(o,r.transition.nextJournal),await i?.afterTransitionWritten?.(r)}}return await wM(e,r,i),await yM(e,r,i),await ZS.rm(Ts(e,t),{force:!0}),r.nextState}async function bM(e){let t=H(e.paths,e.state.name),i=await je(t);if(!i||i.runId!==e.state.run_id||i.currentStep!==e.state.phase||i.currentStep!=="verify"&&i.currentStep!=="archive"||i.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let r={...i,currentStep:"build",iteration:i.iteration+1,pending:null,status:"running"},n=M(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:r,evidenceHash:n,eventData:{fromSchema:Ne,toSchema:ye,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function kM(e){let{journal:t,state:i}=e;if(!(t.previousState.phase==="build"&&t.nextState.phase==="verify"||t.previousState.phase==="verify"&&(t.nextState.phase==="build"||t.nextState.phase==="archive")))throw new Error("Only a pending v2 evidence-bearing transition can be superseded");let n=Oa(i,t.previousState),a=Oa(i,t.nextState);if(!n&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=H(e.paths,i.name),s=await je(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&Bi(s,t.previousRun),l=Bi(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${i.name}`);let d=(await tt(o,t.nextRun.trajectoryRef)).map((b,g)=>({event:b,index:g})).filter(({event:b})=>b.data.transitionId===t.id);if(d.length>1)throw new Error(`Native v2 evidence transition ${t.id} has duplicate trajectory events`);let f=d[0];if(f){let b={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!Nm(f.event,b)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let h={...Vu(i),revision:i.revision+(i.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},v=s,m=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,p=M(JSON.stringify({operation:"supersede-v2-evidence-transition",change:i.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:h.revision}));return{nextState:h,plan:{sourceHash:await Qt(Ge(e.paths,i.name)),transitionId:t.id,previousRun:v,nextRun:m,evidenceHash:p,eventData:{fromSchema:Ne,toSchema:ye,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function SM(e){let t,i,r,n;if(e.state.schema===Ze){if(t=wm(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==rn)throw new Error("Native v1 change has a transition from another schema generation");let s=dM(e.pendingTransition.journal);if(XS(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(XS(e.state,e.pendingTransition.journal.nextState))t=s.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v1 transition journal`);let c=Ge(e.paths,e.name);i={sourceHash:await Qt(c),targetHash:M(YS(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==_i)throw new Error("Native v2 change has a transition from another schema generation");let s=e.pendingTransition.journal;if(s.previousState.phase==="build"&&s.nextState.phase==="verify"||s.previousState.phase==="verify"&&(s.nextState.phase==="build"||s.nextState.phase==="archive")){let l=await kM({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,r=l.plan}else{let l=fM(s);if(Oa(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(Oa(e.state,e.pendingTransition.journal.nextState))t=l.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v2 transition journal`);let u=Ge(e.paths,e.name);i={sourceHash:await Qt(u),targetHash:M(YS(l)),nextJournal:l}}}else t=Vu(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await bM({paths:e.paths,state:e.state,migrationId:e.id}));let a=ym.join(re(e.paths,e.name),_e),o=(0,qu.stringify)(bm(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===Ze?Ne:ye,sourceHash:await Qt(a),targetHash:M(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...r?{transitionSupersede:r}:{},...n?{runRetreat:n}:{}}}async function iE(e){return oe(e.paths,`migrate schema for ${e.name}`,()=>mn(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await NM(e.paths,e.name,e.hooks);if(i?.schema===ye)return i;let r=await mi(e.paths,e.name);if(r.status==="current"&&r.state)return r.state;if(r.status!=="migration-required"||!r.state)throw new Error(r.message??`Native change ${e.name} cannot be migrated`);if(await ha(e.paths,e.name))throw new Error(`Native change ${e.name} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=r.state;if(n.schema!==Ze&&n.schema!==Ne)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await Op(e.paths,e.name);if(a?.status==="current")throw new Error(`Native change ${e.name} has a current-schema pending transition; recover it before schema migration`);let o=await SM({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??oM()}),s=Ts(e.paths,e.name),c=j(e.paths,s);await T(c,s),await Z(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var Vi=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),RM=512*1024,Nn=/^([a-f0-9]{64})\.json$/u,CM=/^\.([a-f0-9]{64}\.json)\.([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.gc$/u,xM=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,Wu=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function Em(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ei(e,t){return Em(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function sE(e,t){return Em(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function Ha(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function rt(e,t){return e<t?-1:e>t?1:0}function AM(e,t){let i=ce.relative(e.projectRoot,t);if(i.length===0||ce.isAbsolute(i)||i===".."||i.startsWith(`..${ce.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(ce.sep).join("/")}function cE(e,t){return ce.join(H(e,t),"evidence")}function zu(e,t){return AM(e,cE(e,t))}async function Ju(e,t){let i=ce.resolve(e),r=ce.resolve(t);if(!O(i,r))throw new Error("Native evidence retention path escapes its managed change");let n=ce.relative(i,r).split(ce.sep).filter(Boolean),a=[],o=i;for(let s of["",...n]){s&&(o=ce.join(o,s));let c=await X.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await X.realpath(o);if(a.length>0&&!O(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...Ha(c)})}return a}async function Lt(e){for(let t of e){let i=await X.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Em(t,i)||await X.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function lE(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:ka(e,t)}function rE(e){return e!==null&&xM.test(e)?[e]:[]}function _M(e,t,i,r){if(e==="snapshots")return{canonical:va(i,t),dependencies:[]};if(e==="scopes"){let a=ga(i);if(a.scopeHash!==t)throw new Error("Native scope filename does not match its hash");return{canonical:a,dependencies:[a.baselineProjectionRef,a.currentProjectionRef]}}if(e==="allowances"){let a=Zl(i);if(a.change!==r||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[ka("scopes",a.scopeHash)]}}if(e==="verifications"){let a=us(i);if(a.change!==r||a.envelopeHash!==t)throw new Error("Native verification filename/change does not match its content");let o=a.acceptanceTrace.entries.flatMap(s=>s.evidenceRefs.flatMap(rE));return{canonical:a,dependencies:[a.implementationScopeRef,rk(a.reportHash),...rE(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native report evidence must be an object");let a=i;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||EM("sha256").update(Buffer.from(a.content,"utf8")).digest("hex")!==t)throw new Error("Native report evidence filename/hash does not match its content");return{canonical:a,dependencies:[]}}if(e==="receipts"){let a=tu(i);if(a.bindings.change!==r||a.receiptHash!==t)throw new Error("Native verification receipt filename/change does not match its content");return{canonical:a,dependencies:a.kind==="static-inspection"?[a.evidence.checkReceiptRef]:[]}}let n=eu(i);if(n.change!==r||n.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:n,dependencies:[]}}async function Vr(e){let t=await X.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let i=e.kind==="check-receipts"?RM:xr;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let r=await X.realpath(e.file);if(!O(e.directoryChain[0].realPath,r))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let n=process.platform==="win32"?"r":km.O_RDONLY|km.O_NOFOLLOW|km.O_NONBLOCK,a=await X.open(e.file,n).catch(o=>{throw o.code==="ELOOP"||o.code==="ENXIO"?new Error(`Native evidence entry became unsafe while opening: ${e.ref}`):o});try{let[o,s,c]=await Promise.all([a.stat(),X.lstat(e.file),X.realpath(e.file)]);if(await Lt(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==r||!Ei(Ha(t),o)||!Ei(Ha(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let g=i+1-d,y=await a.read(u,0,Math.min(u.length,g),null);if(y.bytesRead===0)break;if(d+=y.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,y.bytesRead)))}let[f,h,v]=await Promise.all([a.stat(),X.lstat(e.file),X.realpath(e.file)]);if(await Lt(e.directoryChain),!h.isFile()||h.isSymbolicLink()||v!==r||!Ei(Ha(o),f)||!Ei(Ha(o),h))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let m=Buffer.concat(l,d).toString("utf8"),p;try{p=JSON.parse(m)}catch(g){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:g})}let b=_M(e.kind,e.hash,p,e.name);if(m!==JSON.stringify(b.canonical,null,2)+`
|
|
267
|
-
`)throw new Error(`Native evidence entry is not canonically serialized: ${e.ref}`);return{ref:e.ref,kind:e.kind,change:e.name,changeRoot:e.changeRoot,file:e.file,size:d,mtimeMs:f.mtimeMs,identity:Ha(f),directoryChain:e.directoryChain,dependencies:[...new Set(b.dependencies)].sort(rt)}}finally{await a.close()}}async function nE(e){try{return await X.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function TM(e){let t=H(e.paths,e.name),i=t,r=cE(e.paths,e.name);await T(j(e.paths,r),r);let n;try{let s=await Ju(t,r);n=await X.readdir(r,{withFileTypes:!0}),await Lt(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of Wu){if(!n.some(f=>f.name===s))continue;let c=ce.join(r,s),l=await Ju(t,c),u=(await X.readdir(c,{withFileTypes:!0})).sort((f,h)=>rt(f.name,h.name)),d=new Map;for(let f of u){let h=CM.exec(f.name);if(!h)continue;let v=d.get(h[1])??[];v.push(f),d.set(h[1],v)}for(let[f,h]of[...d.entries()].sort(([v],[m])=>rt(v,m))){if(h.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${s}/${f}`);let v=h[0];if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${s}/${v.name}`);let m=ce.join(c,f),p=Nn.exec(f)?.[1];if(!p)throw new Error(`Native evidence cleanup quarantine name is invalid: ${v.name}`);let b=lE(s,p),g=ce.join(c,v.name),y=await Vr({changeRoot:i,file:g,ref:b,kind:s,hash:p,name:e.name,directoryChain:l}),E=await nE(m),k=E?null:await Vr({changeRoot:i,file:m,ref:b,kind:s,hash:p,name:e.name,directoryChain:l});a.push({ref:b,original:m,quarantine:g,document:y,action:E?"restore-original":"finish-linked-recovery",originalDocument:k})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(rt);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:Da(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${Gu(o)}`),path:zu(e.paths,e.name)}]};for(let s of a.sort((c,l)=>rt(c.ref,l.ref))){if(await Lt(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await Vr({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:Nn.exec(ce.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await Vr({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:Nn.exec(ce.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!Ei(s.originalDocument.identity,d.identity)||!Ei(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await X.rm(s.quarantine),await Lt(s.document.directoryChain);continue}if(!await nE(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await X.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!Ei(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await X.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await Vr({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:Nn.exec(ce.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await Vr({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:Nn.exec(ce.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!sE(s.document.identity,l.identity)||!Ei(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await X.rm(s.quarantine),await Lt(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:Da(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${Gu(o)}`),path:zu(e.paths,e.name)}]}}async function IM(e,t){let i=H(e,t),r=i,n=ce.join(i,"evidence");await T(j(e,n),n);let a;try{let l=await Ju(i,n);a=await X.readdir(n,{withFileTypes:!0}),await Lt(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!Wu.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(rt);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${Gu(o)}`);let s=[],c=0;for(let l of Wu){if(!a.some(h=>h.name===l))continue;let u=ce.join(n,l),d=await Ju(r,u),f=(await X.readdir(u,{withFileTypes:!0})).sort((h,v)=>rt(h.name,v.name));await Lt(d);for(let h of f){if(s.length>=Vi.maxDocuments)throw new Error(`Native evidence store exceeds ${Vi.maxDocuments} documents`);let v=Nn.exec(h.name);if(!v||!h.isFile()||h.isSymbolicLink())throw new Error(`Native evidence kind ${l} has an unknown or special entry: ${h.name}`);let m=lE(l,v[1]),p=ce.join(u,h.name);await T(j(e,p),p);let b=await Vr({changeRoot:r,file:p,ref:m,kind:l,hash:v[1],name:t,directoryChain:d});if(c+=b.size,c>Vi.maxScannedBytes)throw new Error(`Native evidence store exceeds ${Vi.maxScannedBytes} scanned bytes`);s.push(b)}await Lt(d)}return s}function aE(e,t){let i=new Set,r=[...e].sort(rt).reverse();for(;r.length>0;){let n=r.pop();if(i.has(n))continue;let a=t.get(n);if(!a)throw new Error(`Native evidence dependency is missing: ${n}`);i.add(n);for(let o of[...a.dependencies].sort(rt).reverse())i.has(o)||r.push(o)}return i}function jM(e){let t=new Map(e.map(a=>[a.ref,a])),i=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&i.set(o,(i.get(o)??0)+1);let r=[...i].filter(([,a])=>a===0).map(([a])=>a).sort(rt),n=[];for(;r.length>0;){let a=r.shift(),o=t.get(a);n.push(o);for(let s of o.dependencies){let c=i.get(s);if(c===void 0)continue;let l=c-1;i.set(s,l),l===0&&(r.push(s),r.sort(rt))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function $M(e,t,i){let r=new Map(e.map(c=>[c.ref,c]));if(r.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!r.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let n=aE(t,r),a=new Set(n);for(let c of e)i-c.mtimeMs<Vi.minimumAgeMs&&a.add(c.ref);for(let c of Wu){let l=e.filter(u=>u.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||rt(u.ref,d.ref)).slice(0,Vi.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=aE(a,r),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=Vi.minimumAgeMs).sort((c,l)=>rt(c.ref,l.ref));return{candidates:jM(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function Gu(e){let t=e.slice(0,Vi.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function Da(e){let t=Vi.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let i=e;for(;i.length>0&&Buffer.byteLength(`${i}...`,"utf8")>t;)i=i.slice(0,-1);return`${i}...`}function Sm(e,t,i,r){let n=t.candidates.map(a=>a.ref).sort(rt);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:Da(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${Gu(n)}`),path:r}}async function oE(e,t){try{await X.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await X.rename(e,t)}catch{}}async function OM(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await Lt(e.directoryChain);let i=await Vr({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:Nn.exec(ce.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),r=await X.lstat(e.file),n=await X.realpath(e.file);if(!r.isFile()||r.isSymbolicLink()||!Ei(e.identity,r)||!Ei(e.identity,i.identity)||!O(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=ce.join(ce.dirname(e.file),`.${ce.basename(e.file)}.${PM()}.gc`);await X.rename(e.file,a);try{let[o,s]=await Promise.all([X.lstat(a),X.realpath(a)]);if(await Lt(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!sE(e.identity,o)||!O(e.directoryChain[0].realPath,s))throw await oE(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await X.rm(a),await Lt(e.directoryChain)}catch(o){throw await oE(a,e.file),o}}async function HM(e){if((await we(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await X.readdir(e.transactionsDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return!1;throw r}for(let r of i){if(!r.isDirectory()||r.isSymbolicLink())return!0;try{let n=await wt(e,r.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function DM(e,t){if(t)return[t];let i;try{i=await X.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return i.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort(rt)}async function MM(e,t){let i=await mi(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[r,n,a]=await Promise.all([Mi(e,t),Is(e,t),jr(e,t)]);return r!==null||n!==null||a!==null}async function LM(e){if(await MM(e.paths,e.name))return[];let t=await mi(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await TM({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(i.pending)return i.findings;let r=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&r.push(c);let n=await IM(e.paths,e.name),a=$M(n,r,e.nowMs);if(a.candidates.length===0)return i.findings;let o=zu(e.paths,e.name);if(!e.repair)return[...i.findings,Sm(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await OM(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[Sm(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:Da(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,Sm(e.name,a,!0,o)]}async function uE(e){if(e.deferAll||await HM(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let i=async n=>{let a=[];for(let o of await DM(e.paths,e.name))try{a.push(...await LM({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:Da(`Native evidence retention refused to clean ${o}: ${s.message}`),path:zu(e.paths,o)})}return a};if(!(e.repair??!1))return i(!1);let r=await i(!1);if(r.some(n=>n.severity==="error")||!r.some(n=>n.code==="evidence-retention-candidates"||n.code==="evidence-retention-recovery-required"))return r;try{return await oe(e.paths,"prune Native evidence",()=>i(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:Da(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}import{createHash as FM,randomUUID as d6}from"crypto";import{promises as Os}from"fs";import ne from"path";var Rm=64*1024*1024,BM=256*1024,pE=16*1024*1024;async function nt(e){try{return await Os.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function VM(e){let t;try{t=await Os.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name))){if(!i.isDirectory()||i.isSymbolicLink())continue;let r=await bt(e,i.name);if(r){await Vl({paths:e,name:i.name,revision:r.capturedRevision,...r.schema==="comet.native.workspace.v3"?{binding:{isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch},...r.finish?{finish:r.finish}:{}}:{}});continue}}}async function $s(e,t){let i=[];async function r(n){let a=await gt({root:e,directory:n,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=ne.join(n,s.name);if(t.excludedFiles?.has(ne.resolve(c))){await a.verify();continue}let l=await Os.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())i.push({ref:ne.relative(e,c).split(ne.sep).join("/"),type:"directory"}),await r(c);else if(s.isFile()&&l.isFile()){let u=await ie({root:e,file:c,maxBytes:Rm,label:`Native root file ${ne.relative(e,c)}`});i.push({ref:ne.relative(e,c).split(ne.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await r(e),i.sort((n,a)=>n.ref.localeCompare(a.ref))}async function qM(e,t,i,r){await di({root:r,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await gt({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=ne.join(a,l.name);if(ne.resolve(u)===ne.resolve(i)){await s.verify();continue}let d=await Os.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=ne.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await di({root:r,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await vr({sourceRoot:e,source:u,targetRoot:r,target:f,maxBytes:Rm,label:`Native root move file ${ne.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await n(e,t)}async function Ma(e,t,i,r){let n=await $s(e,{rejectSymlinks:!0,excludedFiles:i?new Set([ne.resolve(i)]):void 0}),a=await $s(t,{rejectSymlinks:!0,excludedFiles:r?new Set([ne.resolve(r)]):void 0});if(JSON.stringify(n)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function WM(e,t){return ne.join(e.artifactRoot,`.comet-native-move-${t}`)}function zM(e,t){return ne.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function JM(e){return`${e}.removing`}function dE(e,t){return ne.join(ne.dirname(e),`.${ne.basename(e)}.${t}.rollback-removing`)}function mE(e,t,i){return ne.join(Pl(e,t).directory,`root-move-cleanup-${i}.json`)}function GM(e){return JSON.stringify(e,null,2)+`
|
|
268
|
-
`}function UM(e){return FM("sha256").update(e).digest("hex")}function KM(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let i=e,r=Object.keys(i).sort(),n=i.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof i.ref!="string"||i.ref.length===0||i.ref.includes("\\")||ne.posix.normalize(i.ref)!==i.ref||i.ref.startsWith("/")||i.ref.split("/").includes("..")||Buffer.byteLength(i.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(i.type==="directory")return{ref:i.ref,type:"directory"};if(i.type!=="file"||typeof i.size!="number"||!Number.isSafeInteger(i.size)||i.size<0||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:i.ref,type:"file",size:i.size,hash:i.hash}}function YM(e,t,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let r=e;if(JSON.stringify(Object.keys(r).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||r.schema!=="comet.native.root-move-cleanup.v1"||r.transactionId!==t||r.kind!==i||!Array.isArray(r.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=r.entries.map(KM);for(let a=0;a<n.length;a+=1){if(a>0&&n[a-1].ref.localeCompare(n[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=ne.posix.dirname(n[a].ref);if(o!=="."&&!n.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:i,entries:n}}async function XM(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=GM(t);if(Buffer.byteLength(i,"utf8")>pE)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await fe(mE(e.paths,e.id,e.kind),i,{containedRoot:e.paths.runtimeDir}),UM(i)}async function QM(e){let t=await ie({root:e.paths.runtimeDir,file:mE(e.paths,e.id,e.cleanup.kind),maxBytes:pE,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return YM(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function Pm(e){let t=await $s(e.quarantine,{rejectSymlinks:!0}),i=new Map(e.manifest.entries.map(r=>[r.ref,r]));for(let r of t){let n=i.get(r.ref);if(!n||JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${r.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function fE(e){return e.ref.split("/").length}async function ZM(e){let i=[...await Pm({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>fE(a)-fE(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),r=0;for(let n of i){let a=ne.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await Nl({root:e.projectRoot,file:a,maxBytes:Rm,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await Sh({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),r+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,r)}await Pm({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await Sh({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function vE(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function eL(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function tL(e,t,i,r){for(let a of[e,t])try{let o=await wt(a,r);if(o.kind!=="root-move")throw new Error(`Transaction ${r} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let n=ne.join(i,"runtime","transactions",r,"transaction.json");try{let a=await ie({root:i,file:n,maxBytes:BM,label:`Staged Native root-move journal ${r}`}),o=JSON.parse(a.bytes.toString("utf8"));if(o.schema!=="comet.native.transaction.v1"||o.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${r}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${r}`,{cause:a})}}async function hE(e){let t=vE(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await cr(e.projectRoot,t),t}async function js(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=vE(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await cr(e.projectRoot,i),i}async function Uu(e){let t=e.config,i=t.native.pending_root_move;if(!i||i.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let r=i.cleanup;if(r&&r.kind!==e.kind)throw new Error(`Native root move has unfinished ${r.kind} cleanup; cannot start ${e.kind}`);let n=await nt(e.target),a=await nt(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!r){if(!n&&!a)return t;if(!n&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await XM({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await $s(e.target,{rejectSymlinks:!0})});r={kind:e.kind,state:"prepared",manifestHash:s},t=await js({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})}let o=await QM({paths:e.stablePaths,id:e.id,cleanup:r});if(n=await nt(e.target),a=await nt(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(r.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await qy({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(r.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return js({projectRoot:e.projectRoot,config:t,id:e.id})}return await Pm({quarantine:e.quarantine,manifest:o,exact:r.state!=="deleting"}),r.state==="prepared"&&(r={...r,state:"quarantined"},t=await js({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),r.state==="quarantined"&&(r={...r,state:"deleting"},t=await js({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),await ZM({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),js({projectRoot:e.projectRoot,config:t,id:e.id})}async function iL(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await nt(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=JM(e.staging);t=await Uu({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await $s(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([ne.resolve(e.lockFile)])}),await qM(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await Ma(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await hE({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await nt(e.destinationPaths.nativeRoot)){if(await nt(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await Ma(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await nt(e.staging))throw new Error("Native move staging tree is missing");await Ma(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await Os.rename(e.staging,e.destinationPaths.nativeRoot)}t=await hE({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),i="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(i!=="switched")throw new Error(`Unsupported Native root-move stage: ${i}`);if(!await nt(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let r=zM(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await nt(e.sourcePaths.nativeRoot)&&await Ma(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await Uu({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:r,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await VM(e.destinationPaths);let n=await wt(e.destinationPaths,e.pending.id);await Zn(e.destinationPaths,n,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await cr(e.projectRoot,o),o}async function gE(e){let t=await we(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let r=await Ve(e.projectRoot,i.fromArtifactRoot),n=await Ve(e.projectRoot,i.toArtifactRoot),a=WM(n,i.id),o=await nt(r.nativeRoot)?r:n,s=await lr(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await tL(r,n,a,i.id)}catch(v){if(i.stage!=="copying"||!await nt(r.nativeRoot))throw v;let m=eL({id:i.id,paths:r,now:new Date});await Zy(r,m),c={journal:m,paths:r}}if(e.strategy==="continue"){let v=await iL({projectRoot:e.projectRoot,config:t,pending:i,sourcePaths:r,destinationPaths:n,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:n.nativeRoot,config:v}}if(!await nt(r.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=dE(n.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await nt(n.nativeRoot)&&await Ma(r.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await Uu({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-destination",stablePaths:r,target:n.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=dE(a,i.id);!t.native.pending_root_move?.cleanup&&await nt(a)&&await Ma(r.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await Uu({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-staging",stablePaths:r,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await wt(r,i.id);await Rl(r,d);let f={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},h={...t,native:{...f,artifact_root:i.fromArtifactRoot}};return await cr(e.projectRoot,h),{activeNativeRoot:r.nativeRoot,config:h}}finally{await ur(s)}}var La=4096,rL=4096,nL=1024;async function qr(e,t,i){try{let r=await gt({root:j(e,t),directory:t,label:"Native doctor directory",maxEntries:i});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function Yu(e,t){let i=new Map(e.map(r=>[Te.resolve(r.file),{...r,file:Te.resolve(r.file)}]));for(let{paths:r,file:n}of i.values()){let a;try{a=await Io(n)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:n}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await dh(r,n,a);if(o.status==="removed"){t.push({severity:"info",code:"stale-recovery-lock-removed",message:"Removed stale lock before explicit transaction recovery",path:n});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"?(t.push({severity:"error",code:"lock-takeover-raced",message:"Native recovery lock changed while doctor was preparing stale takeover",path:n}),!1):(t.push({severity:"error",code:a.status==="active"?"lock-active":"lock-owner-unknown",message:a.status==="active"?"Native recovery lock is still owned by a live process":"Native recovery lock owner cannot be proven stale",path:n}),!1)}}return!0}async function aL(e,t){let i=DS(e),r;try{await T(e.projectRoot,i);let n=await Hu(e);if(!n)return[];r=n}catch(n){return n.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${n.message}`,path:i}]}if(r.schema!=="comet.selection.v2"||r.workflow!=="native"||typeof r.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:i}];try{return await Br(e,r.change)?[]:(await Oe(e,r.change),[])}catch(n){if(n.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${n.message}`,path:i}]}return t?(await Ku.rm(i,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${r.change}`,path:i}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${r.change}`,path:i}]}async function oL(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await T(j(e,i),i)}catch(r){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${r.message}`,path:i})}return t}async function sL(e,t){let i=[],r=[];for(let n of await qr(e,e.transactionsDir,rL)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await wt(e,n.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:Te.join(e.transactionsDir,n.name)});continue}if(!(a.status==="committed"||a.status==="rolled-back")&&!(t.name&&a.change&&a.change!==t.name)){if(a.kind!=="archive"){r.push(a),i.push({severity:"error",code:"root-move-transaction-orphaned",message:`Root-move transaction ${a.id} is incomplete but project config has no matching pending move`});continue}if(t.repair&&t.recoveryStrategy)try{if(!await qn([e],`doctor archive recovery ${a.id}`,async()=>await Yu([{paths:e,file:Te.join(e.locksDir,"root-move.lock")},{paths:e,file:Te.join(e.locksDir,"archive.lock")}],i)?(await BS({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){r.push(a);continue}i.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){r.push(a),i.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else r.push(a),i.push({severity:"error",code:"archive-transaction-incomplete",message:t.repair?`Archive transaction ${a.id} needs an explicit recovery strategy`:`Archive transaction ${a.id} is incomplete`,repair:t.recoveryStrategy??"continue"})}}return{findings:i,unfinished:r}}async function cL(e,t,i){let r=[];for(let n of await qr(e,e.locksDir,nL)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=Te.join(e.locksDir,n.name);try{let o=await Io(a);if(o.status==="active")r.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")r.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&i.length===0){let s=await dh(e,a,o);s.status==="removed"?r.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&r.push({severity:s.diagnosis.status==="active"?"warning":"error",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing stale takeover",path:a})}else r.push({severity:i.length>0?"error":"warning",code:"lock-stale",message:i.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){r.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return r}async function lL(e,t,i=5){let r=[],n=t?await gm(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await gm(e,{maxVerifyFailures:i});if(t&&n.length===0)return[{severity:"error",code:"change-missing",message:`Native change does not exist: ${t}`}];for(let a of n){if(a.migrationRequired)continue;if(a.phase==="invalid"){r.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:Te.join(e.changesDir,a.name,_e)});continue}let o=await vm(e,a.name,{details:!0,maxVerifyFailures:i});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||r.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:Te.join(e.projectRoot,s.path)}:{}})}return r}async function uL(e,t){let i=[],r=t.name?[t.name]:(await qr(e,e.changesDir,La)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{let a=await sa(e,n);if(a.status!=="repairable")continue;if(!t.repair){i.push({severity:"error",code:"trajectory-tail-incomplete",message:`Native trajectory for ${n} has an incomplete final line ${a.line}; ${a.discardedBytes} byte(s) are outside the last complete event`,path:a.file,repair:"truncate-tail"});continue}let o=await MN(e,n);o&&i.push({severity:"info",code:"trajectory-tail-repaired",message:`Removed the incomplete Native trajectory tail for ${n} and preserved all complete events`,path:o.file})}catch(a){i.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${n}: ${a.message}`,path:Te.join(H(e,n),"trajectory.jsonl")})}return i}async function dL(e,t){let i=[],r=t.name?[t.name]:(await qr(e,e.changesDir,La)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=await To(e,n);if(a.status==="missing"){i.push({severity:"warning",code:"runtime-missing",message:`Native Runtime for ${n} is missing; continue the change to rebuild it`,path:a.path});continue}if(a.status==="invalid"){i.push({severity:"error",code:"runtime-storage-invalid",message:a.message??`Native Runtime storage for ${n} is invalid`,path:a.path});continue}if(a.layout!=="legacy")continue;let o=Zr(e,n),s=qe(e,n);if(!t.repair){i.push({severity:"warning",code:"runtime-layout-legacy",message:`Native Runtime for ${n} still uses the legacy change-local layout`,path:o,repair:"migrate"});continue}try{await qn([e],`migrate Runtime layout for ${n}`,async()=>{let c=await Xt({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await T(e.runtimeDir,s),await Ku.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await Xt({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await Ku.lstat(s),new Error(`Target Native Runtime already exists: ${s}`)}catch(u){if(u.code!=="ENOENT")throw u}await c.verify(),await l.verify(),await Ku.rename(o,s)}),i.push({severity:"info",code:"runtime-layout-migrated",message:`Moved Native Runtime for ${n} to project-local .comet storage`,path:s})}catch(c){i.push({severity:"error",code:"runtime-layout-migration-failed",message:`Native Runtime layout migration failed for ${n}: ${c.message}`,path:o})}}return i}async function fL(e,t){let i=[],r=t.name?[t.name]:(await qr(e,e.changesDir,La)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{if(!await Uh(e,n))continue;if(!t.repair){i.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${n} uses legacy external-probe or hash-only metadata`,path:la(e,n),repair:"migrate"});continue}let a=await Oe(e,n);await KN({paths:e,name:n,revision:a.revision})&&i.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${n} with process-free root identities`,path:la(e,n)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:la(e,n)})}return i}async function hL(e,t){let i=[],r=t.name?[t.name]:(await qr(e,e.changesDir,La)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=Ts(e,n);try{let o=await Is(e,n),s=await mi(e,n);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){i.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${n} requires a newer runtime`,path:Te.join(e.changesDir,n,_e)});continue}if(!t.repair){i.push({severity:"error",code:o?"schema-migration-incomplete":"schema-migration-required",message:o?`Native schema migration ${o.id} is incomplete for ${n}`:`Native change ${n} requires migration to the current schema`,path:o?a:Te.join(e.changesDir,n,_e),repair:"migrate"});continue}await iE({paths:e,name:n}),i.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${n} to the current schema`,path:Te.join(e.changesDir,n,_e)})}catch(o){if(o.code==="ENOENT")continue;i.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${n}: ${o.message}`,path:a})}}return i}async function pL(e,t){let i=[],r=t.name?[t.name]:(await qr(e,e.changesDir,La)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a;try{a=await Mi(e,n)}catch(o){if(o instanceof vs)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:Ge(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await qn([e],`doctor transition recovery ${n}`,async()=>await Yu([{paths:e,file:Te.join(e.locksDir,"root-move.lock")},{paths:e,file:Te.join(e.locksDir,`transition-${n}.lock`)}],i)?(await xk(e,n),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:Ge(e,n)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:Ge(e,n)})}continue}i.push({severity:"error",code:"transition-incomplete",message:t.repair&&t.recoveryStrategy==="rollback"?`Native phase transition ${a.id} only supports deterministic continue recovery`:`Native phase transition ${a.id} is incomplete for ${n}`,path:Ge(e,n),repair:"continue"})}}return i}async function mL(e,t){let i=[],r=t.name?[t.name]:(await qr(e,e.changesDir,La)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=Ir(e,n),o;try{o=await jr(e,n)}catch(s){if(s.code==="ENOENT")continue;i.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){i.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${n}`,path:a});continue}try{if(!await qn([e],`doctor checkpoint recovery ${n}`,async()=>await Yu([{paths:e,file:Te.join(e.locksDir,"root-move.lock")},{paths:e,file:Te.join(e.locksDir,`transition-${n}.lock`)}],i)?(await Fk(e,n),!0):!1))continue;i.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${n}`,path:a})}catch(s){i.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return i}async function Hs(e){let t=e.repair??!1,i=[],r=e.paths,n;try{n=await we(r.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:r.configFile}]}}let a=!!n?.native.pending_root_move;if(n?.native.pending_root_move){let c=n.native.pending_root_move,[l,u]=await Promise.all([Ve(r.projectRoot,c.fromArtifactRoot),Ve(r.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await Yu([{paths:l,file:Te.join(l.locksDir,"root-move.lock")},{paths:u,file:Te.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await gE({projectRoot:r.projectRoot,strategy:e.recoveryStrategy});r=await Ve(r.projectRoot,f.config.native.artifact_root),a=!1,i.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return i.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:i}}else i.push({severity:"error",code:"root-move-incomplete",message:`Native root move ${c.id} is ${c.stage}; inspect ${l.nativeRoot} and ${u.nativeRoot}`,repair:e.recoveryStrategy??"continue"})}let o=await oL(r);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await sL(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),e.projectOnly||(i.push(...await dL(r,{name:e.name,repair:t})),i.push(...await hL(r,{name:e.name,repair:t})),i.push(...await fL(r,{name:e.name,repair:t})),i.push(...await uL(r,{name:e.name,repair:t})),i.push(...await pL(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await mL(r,{name:e.name,repair:t})),i.push(...await uE({paths:r,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),i.push(...await cL(r,t,s.unfinished)),i.push(...await aL(r,t)),e.projectOnly||i.push(...await lL(r,e.name,n?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}import{randomUUID as vL}from"node:crypto";import{promises as Me}from"node:fs";import ft from"node:path";var Cm=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}};function wE(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function yE(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let i=ft.join(e.archiveDir,t);if(!O(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function Xu(e){try{return await Me.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function NE(e,t){let i=ft.normalize(ft.resolve(e)),r=ft.normalize(ft.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function gL(e,t){let i;try{i=await Me.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let r=[];for(let n of i){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=ft.join(e.archiveDir,n.name);try{let o=await Qe(ft.join(a,"comet-state.yaml"));o.name===t&&r.push({dir:a,state:o})}catch{}}if(r.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return r[0]??null}async function wL(e,t){let i=await gl(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function bn(e,t){await Me.mkdir(e.transactionsDir,{recursive:!0}),await Z(hr(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function yL(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let i=zt(e.paths.projectRoot);i.some(a=>NE(a,e.paths.projectRoot))||i.push(e.paths.projectRoot);let r=[];for(let a of i){let o=await we(a);if(!o)continue;let s=await Ve(a,o.native.artifact_root);r.some(c=>NE(c.changesDir,s.changesDir))||r.push(s)}r.length===0&&r.push(e.paths);let n=new Set;for(let a of r){let o;try{o=await Me.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let c=await Qe(ft.join(a.changesDir,s.name,"comet-state.yaml"));c.status!=="done"&&c.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.name)}catch{let c=await Gl(a,s.name).catch(()=>null);c?.state&&c.state.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function NL(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function bL(e){let t=ft.join(e.paths.specsDir,e.change.capability),i=ft.join(t,"spec.md");if(!O(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await Me.lstat(e.paths.specsDir)}catch(c){if(c.code==="ENOENT")return;throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await Me.lstat(t)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[o,s]=await Promise.all([Me.realpath(e.paths.specsDir),Me.realpath(t)]);if(!O(o,s))throw new Error("Native canonical capability path escaped");try{let c=await Me.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await Me.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await Me.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let r=ft.join(Dt(e.paths,e.state.name),e.change.source);await fe(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await Me.mkdir(t,{recursive:!0}),await fe(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function bE(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function kL(e,t){let i=Dt(e,t.name),r=[];for(let n of t.spec_changes){if(n.source===null){r.push({...n,content:null});continue}let a=await Q({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function SL(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(bE(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function xm(e){return oe(e.paths,`archive portable change ${e.name}`,async()=>{let t=NL(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await wL(e.paths,e.name),r=Dt(e.paths,e.name),n=await Xu(r),a=n?null:await gL(e.paths,e.name),o;if(n)o=await Ia(e.paths,e.name);else if(i)o=await Qe(ft.join(yE(e.paths,i.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);let s=await Dr(e.paths,e.name);if(n&&!o.archived&&i===null){let d=await $S({paths:e.paths,state:o});if(d.drifted){let f=d.reason??"Native confirmed requirements changed";throw await OS({paths:e.paths,state:o,reason:f}),new Error(`${f}; Native change returned to Shape and requires confirmation`)}}let c=yE(e.paths,i?.archive_ref??wE(o)),l=await Xu(c);if(i&&SL(i,o),n&&l)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!i&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await xs(e.paths,o.name),await Me.rm(qe(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!i){if(!o.archived)bE(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let d=await yL({paths:e.paths,state:o});if(!o.archived&&d.length>0&&t!==o.name)throw new Cm(d);i={schema:vl,id:vL(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:wE(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await kL(e.paths,o),created_at:new Date().toISOString()},await bn(e.paths,i)}if(!n&&l&&i.status==="report-aligned")i={...i,status:"moved"},await bn(e.paths,i);else if(!n&&l&&i.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${i.status}; doctor intervention is required`);let u=!1;if(i.status==="prepared"&&s&&!o.archived&&(s=(await Ss({paths:e.paths,state:s})).state,u=!0),i.status==="prepared"){for(let d=i.next_spec_index;d<i.spec_changes.length;d+=1)await bL({paths:e.paths,state:o,change:i.spec_changes[d]}),i={...i,next_spec_index:d+1},await bn(e.paths,i),await e.hooks?.afterSpecApplied?.(d);i={...i,status:"specs-applied"},await bn(e.paths,i)}if(i.status==="specs-applied"){if(s&&!o.archived&&!u&&(s=(await Ss({paths:e.paths,state:s})).state,u=!0),!o.archived){let d={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await tn({file:Et(e.paths,o.name),expectedStateVersion:o.state_version,next:d,containedRoot:e.paths.nativeRoot})}i={...i,status:"state-finalized"},await bn(e.paths,i),await e.hooks?.afterFinalState?.()}if(i.status==="state-finalized"){let d=await Xu(r)?r:c;if(await $u({file:ft.join(d,"verification.md"),state:o,...s?{supervisor:s}:{}}),await ju({file:ft.join(d,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");i={...i,status:"report-aligned"},await bn(e.paths,i),s&&!u&&(await Ss({paths:e.paths,state:s}),u=!0),await e.hooks?.afterReportAligned?.()}if(i.status==="report-aligned"){if(s&&!u&&await Ss({paths:e.paths,state:s}),await Me.mkdir(e.paths.archiveDir,{recursive:!0}),await Xu(c))throw new Error(`Native Archive target already exists: ${c}`);await Me.rename(r,c),i={...i,status:"moved"},await bn(e.paths,i),await e.hooks?.afterMove?.()}return i.status==="moved"&&(await xs(e.paths,o.name),await Me.rm(qe(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await Me.rm(hr(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:c,transactionId:i.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}function kn(e,t,i){return e.language==="zh-CN"?i:t}function EL(e,t){let i=r=>({required:!1,message:null,suggestedReply:null,agentInstruction:r});return t&&e.phase==="shape"&&e.status==="active"?{required:!0,message:kn(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:kn(e,"Reply A or B","回复 A 或 B"),agentInstruction:kn(e,"Relay the two coordination choices and wait for the user decision. Do not treat a generic confirmation as a mode selection or run --confirmed without --coordination-mode.","转述这两个推进方式并等待用户选择。不要把普通“确认”视为已选择推进方式,也不要在没有 --coordination-mode 时运行 --confirmed。")}:e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"?i(kn(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。")):e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result"?i(kn(e,"Wait only while the dispatched Verifier task is still active. If it did not start, ended without a response, or is no longer available, immediately submit the matching verifier-unavailable or verifier-execution-error input. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、结束后没有返回结果或已经丢失,立即提交匹配的 verifier-unavailable 或 verifier-execution-error 输入。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。")):e.status==="blocked"&&e.blockers.some(({resolution_action:r})=>r==="retry-verifier")?e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."}:e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable"?e.language==="zh-CN"?{required:!0,message:"由于独立验收服务暂时不可用,目前只能完成自动检查。你可以选择接受当前检查结果,或者等验收服务恢复后再重试。",suggestedReply:null,agentInstruction:"向用户转述 message,并请用户明确选择是否接受只有自动检查的结果。不要把“继续”当作默认接受。"}:{required:!0,message:"Because independent verification is temporarily unavailable, only the automatic checks could be completed. You can accept the current check results or wait and retry when verification is available.",suggestedReply:null,agentInstruction:"Relay message and ask the user to explicitly choose whether to accept automatic checks only. Do not treat “Continue” as implicit acceptance."}:i(kn(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function _m(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Qu(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function kE(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function PL(e,t,i){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...i]}}function RL(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function CL(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--confirmed","--expected-state-version",String(e.stateVersion),"--expected-action","confirm-shape"]}function Ds(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:_m({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Qu("summary","--summary"),kE(e.name,e.flag)]}}function Am(e){return[Ds({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Ds({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Zu(e,t){let i=RL(t)&&e.coordination_mode===void 0,r={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],userCommunication:EL(e,i)},n=a=>({kind:a,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...r,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:n("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...r,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Qu("summary","--summary")],commandAlternatives:[Ds({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Am({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...r,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:_m({change:e.name,stateVersion:e.state_version,action:"confirm-verifier-unavailable",flag:"--confirmed"}),requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...r,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Qu("summary","--summary")],commandAlternatives:[Ds({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Am({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...r,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Qu("summary","--summary")],commandAlternatives:Am({change:e.name,stateVersion:e.state_version}),runnerAction:n("none")}:{...r,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:n("none")};if(e.status==="blocked"){let a=e.blockers.some(({resolution_action:o})=>o==="retry-verifier");return{...r,disposition:"blocked",action:a?"retry-verifier":"none",commandArgs:a?_m({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:a?["summary"]:["repair-runtime"],inputOptions:a?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:n(a?"retry-verifier":"none")}}if(e.phase==="shape")return{...r,disposition:i?"await-user":"continue",action:"confirm-shape",commandArgs:CL({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[],"shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[PL("coordination-mode","--coordination-mode",Ty)]:[],kE("confirmed","--confirmed")],runnerAction:n("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...r,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:n("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...r,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:n("none")};if(t.allDone)return{...r,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")};let a=t.children.some(({status:s})=>s==="blocked"||s==="needs-reverify"),o=t.children.some(({status:s})=>s==="ready"||s==="active");return{...r,disposition:a&&!o?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:a&&!o?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:n("none")}}return{...r,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")}}if(e.phase==="verify"){let a=e.loop.next_action==="await-verifier-result",o=!!e.children_contract_hash,s={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...r,userCommunication:!a&&o?{...r.userCommunication,agentInstruction:`${r.userCommunication.agentInstruction} ${kn(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:r.userCommunication,disposition:"continue",action:a?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[a?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:a?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[s]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:o?[s]:[]}}],runnerAction:n(a?"await-verifier":"dispatch-verifier")}}return e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived?{...r,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],commandAlternatives:[Ds({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:n("none")}:{...r,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:n("none")}}import{randomUUID as xL}from"node:crypto";import{promises as Fa}from"node:fs";import AE from"node:path";var Tm=["evidence.md","repair.md","archive.md","checkpoint.md"],AL="verification.md";async function _L(e){try{return await Fa.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Im(e,t){let i=re(e,t),r=[hr(e,{kind:"migration",change:t}),Zr(e,t),...Tm.map(n=>AE.join(i,n))];return(await Promise.all(r.map(_L))).some(Boolean)}async function TL(e,t){let i=await gl(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function SE(e,t){await Fa.mkdir(e.transactionsDir,{recursive:!0}),await Z(hr(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function EE(e,t,i={}){let r=i.removeVerificationReport===!1?Tm:[...Tm,AL];await Promise.all([Fa.rm(qe(e,t),{recursive:!0,force:!0}),Fa.rm(Zr(e,t),{recursive:!0,force:!0}),...r.map(n=>Fa.rm(AE.join(re(e,t),n),{force:!0}))])}async function PE(e,t){await Mr(wn(e,t.name),gn({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function RE(e,t){try{let i=await bt(e,t);if(i?.schema==="comet.native.workspace.v3")return{isolation:i.isolation,change_branch:i.changeBranch,target_branch:i.targetBranch,finish:i.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function CE(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=de(e.projectRoot);if(!i.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(i.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${i.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function IL(e){let t=re(e.paths,e.state.name),i=await Q({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),r=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await Q({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return ll({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function xE(e,t){let i=await Gl(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function Ms(e){return oe(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await TL(e.paths,e.name),i=await Br(e.paths,e.name)?await Qe(Et(e.paths,e.name)):null;if(!t&&i)return await EE(e.paths,e.name,{removeVerificationReport:!1}),await PE(e.paths,i),i;let r=null,n=null;for(t||(r=await xE(e.paths,e.name),n=await RE(e.paths,e.name),CE(e.paths,n),t={schema:ml,id:xL(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await SE(e.paths,t));;){let a=$y(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await xE(e.paths,e.name),n??=await RE(e.paths,e.name),CE(e.paths,n),i=jy({state:r,acceptance:await IL({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await pl(Et(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await EE(e.paths,e.name):a.action==="commit-transaction"&&(i??=await Qe(Et(e.paths,e.name)),await PE(e.paths,i)),t={...t,status:a.nextStatus},await SE(e.paths,t)}return await Fa.rm(hr(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??Qe(Et(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as _E}from"node:fs";import TE from"node:path";function jL(e,t){let i=de(e.projectRoot);if(t.workspace.change_branch!==null){if(!i.isGitWorktree)return"The portable change requires a Git branch/worktree";if(i.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:i.isGitWorktree?t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function $L(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function OL(e,t,i){let r=new Date().toISOString(),n=e.verification===null?e:Un(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:dr(t),completed_at:r});return st({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:i?$L(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function HL(e){try{let t=await Iu(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function IE(e){return oe(e.paths,`recover portable change ${e.name}`,async()=>{let t=await Ia(e.paths,e.name);if(t.status==="done")return await Ou({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let i=jL(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=wn(e.paths,e.name),n=await HL(r),a=n.reason==="available"&&(n.local?.change!==t.name||n.local?.basedOnStateVersion!==t.state_version)?"stale":n.reason;if(a==="available"&&!e.preserveRunningExecution&&n.local?.execution!==null&&n.local?.execution?.status!=="completed"&&n.local&&(a="interrupted",n.local.execution?.status==="running"&&(n.local={...n.local,execution:{...n.local.execution,status:"interrupted"},checks:n.local.checks.map(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)},await Mr(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await Ou({paths:e.paths,state:t}),{state:t,local:n.local,action:"resume-stable-boundary",reason:a,message:"Native local execution overlay matches the portable state."};let s=a==="interrupted"?n.local?.checks.find(f=>f.status==="interrupted"&&!f.repeatable):void 0;if(s){let f=cm({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await tn({file:Et(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot}),await _E.rm(TE.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let h=gn({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await Mr(r,h,{containedRoot:e.paths.runtimeDir}),{state:t,local:h,action:"resume-stable-boundary",reason:a,message:`Native check ${s.id} was not repeatable; the change returned to Build for a new candidate.`}}let c=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",l=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",u=c||l;if(u){let f=OL(t,l?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",l);t=await tn({file:Et(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot})}let d=gn({portableState:t,projectRoot:e.paths.projectRoot,branch:de(e.paths.projectRoot).currentBranch});return await _E.mkdir(TE.dirname(wn(e.paths,t.name)),{recursive:!0}),await Mr(r,d,{containedRoot:e.paths.runtimeDir}),await Ou({paths:e.paths,state:t}),{state:t,local:d,action:u?"reverify":"resume-stable-boundary",reason:a,message:u?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}import{promises as $E}from"node:fs";import ML from"node:path";function DL(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function jE(e){let t=e.acceptance.reduce((i,r)=>({...i,[r.result]:i[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:t,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:DL(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},archived:e.archived}}function LL(e,t,i){return`native-details-v2.${e}.${t}.${i.toString(36)}`}function FL(e,t,i){if(!e)return 0;let r=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!r||Number(r[1])!==t||Number(r[2])!==i)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(r[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function BL(e,t,i){return[...e.acceptance.map(r=>({kind:"acceptance",value:r})),...e.spec_changes.map(r=>({kind:"spec-change",value:r})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(r=>({kind:"history",value:r})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(r=>({kind:"supervisor-child",value:WL(r,i)})),...t.history.map(r=>({kind:"supervisor-history",value:zL(r,i)}))]:[]]}function VL(e){return e.acceptance.reduce((t,i)=>({...t,[i.result]:t[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function OE(e,t){let i=de(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:ML.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:r}}function qL(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(i=>[i.projectRoot,i.task?.projectRoot])].filter(i=>!!i).map(i=>i.replaceAll("/","\\")).sort((i,r)=>r.length-i.length)}function ed(e,t){return e===null?null:t.reduce((i,r)=>i.replaceAll(r,"<worktree>").replaceAll(r.replaceAll("\\","/"),"<worktree>"),e)}function WL(e,t){return{...e,projectRoot:e.projectRoot?"<worktree>":null,baseCommit:e.baseCommit?"<redacted>":null,candidateCommit:e.candidateCommit?"<redacted>":null,verifiedCommit:e.verifiedCommit?"<redacted>":null,integrationCommit:e.integrationCommit?"<redacted>":null,blocker:ed(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function zL(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:ed(e.summary,t)??""}}async function Ba(e){let t=await HS(e),i=jE(t.state),r=t.state.status==="active"&&t.state.loop.stage!=="done",n=await Es({paths:e.paths,state:t.state}),a=await Dr(e.paths,e.name),o=a?{...OE(e.paths,t.state),projectRoot:"."}:OE(e.paths,t.state),s=Zu(t.state,n),c=o.bindingState==="mismatch"?{...s,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...s.runnerAction,kind:"none"}}:s,l=a?qL(e.paths,a):[],u=a?(()=>{let h=a.children.filter(({status:y})=>y==="pending"||y==="ready").length,v=a.children.filter(({status:y})=>y==="active"||y==="verified").length,m=a.children.filter(({status:y})=>y==="integrated"||y==="archived").length,p=a.children.filter(({status:y})=>y==="blocked"||y==="needs-reverify").length,b=a.children.filter(({status:y})=>y==="active"||y==="blocked"||y==="needs-reverify").slice(0,16).map(y=>({name:y.name,summary:y.summary,projectRoot:y.task?.projectRoot??y.projectRoot?"<worktree>":null,reason:ed(y.blocker,l)})),g=a.children.flatMap(({blocker:y})=>{let E=ed(y,l);return E?[E]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:a.children.length,waiting:h,working:v,integrated:m,blocked:p,active:b,agents:{working:a.children.filter(({task:y})=>y!==null).length,completed:m},risks:g,nextAction:a.finalVerification.status==="passed"?"final-delivery":a.finalVerification.status==="pending"&&m===a.children.length?"parent-verification":h>0?"dispatch-ready-child":p>0?"resolve-blocker":"continue-supervisor"}})():null,d=e.details?(()=>{let h=a?.stateVersion??0,v=BL(t.state,a,l),m=FL(e.cursor,t.state.state_version,h),p=v.slice(m,m+32),b=m+p.length<v.length?LL(t.state.state_version,h,m+p.length):null;return{items:p,nextCursor:b,supervisorStateVersion:h}})():null,f=a?{schema:a.schema,parent:a.parent,integration:{branch:a.integration.branch,targetBranch:a.integration.targetBranch},finalVerification:{status:a.finalVerification.status,summary:a.finalVerification.summary},summary:u}:null;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,...t.state.coordination_mode===void 0?{}:{coordinationMode:t.state.coordination_mode},loop:t.state.loop,acceptance:VL(t.state),unresolvedAcceptanceIds:i.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:a?[]:i.blockers,workspace:o,localExecution:{status:r?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{childSummary:n.children.reduce((h,v)=>({...h,[v.status]:(h[v.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...f?{supervisor:f}:{},continuation:c,...e.details?{details:{stateVersion:t.state.state_version,...a?{supervisorStateVersion:d.supervisorStateVersion}:{},items:d.items,nextCursor:d.nextCursor,nextPageArgs:d.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",d.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}async function HE(e){let t;try{t=await $E.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[];for(let r of t)if(!(!r.isDirectory()||r.isSymbolicLink()))try{let n=await $E.readFile(`${Dt(e,r.name)}/comet-state.yaml`,"utf8");/^schema:\s*comet\.native\.v4\s*$/mu.test(n)&&i.push(r.name)}catch(n){if(n.code!=="ENOENT")throw n}return i.sort((r,n)=>r.localeCompare(n,"en"))}import Ls from"path";import{realpathSync as KL}from"fs";var DE=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--help Show help without requiring an initialized project."],$m=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","check <change-name> Run the read-only Native verification check.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:DE,output:"Human-readable text by default; use --json for a structured command envelope.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page, or a named details/history page.","--details Include one fixed-size page of acceptance, Spec, handoff, verification, history, workspace, and report details."],output:"A compact v2 status page or one compact Loop projection with local execution availability. Use --details and --cursor to read fixed-size detail pages; parent changes expose childSummary and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--confirmed] [--coordination-mode multi-session|single-session] [--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
|
|
263
|
+
${Br(e.verification.summary)}
|
|
264
|
+
`}function JD(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let i=Number(t[1]);return Number.isSafeInteger(i)?i:null}async function Hu(e){let t;try{t=await BD.readFile(e.file,"utf8")}catch(r){if(r.code==="ENOENT")return"missing";throw r}let i=JD(t);return i===null?"invalid":i===e.stateVersion?"aligned":"stale"}async function Du(e){await he(e.file,zD(e.state,e.supervisor))}var BS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,GD="comet-state.yaml",UD="state.json",EY=Us("en");function Lt(e,t){if(!BS.test(t))throw new Error(`Invalid Native change name: ${t}`);let i=Vr.join(e.changesDir,t);if(!O(e.changesDir,i))throw new Error("Native change path escaped");return i}function Pt(e,t){return Vr.join(Lt(e,t),GD)}function Nn(e,t){return Vr.join(We(e,t),UD)}async function qr(e,t){try{let i=await _s.readFile(Pt(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(i)}catch(i){if(i.code==="ENOENT")return!1;throw i}}function KD(e){return fe(e).currentBranch}async function $a(e,t){return Ze(Pt(e,t))}async function YD(e){let t=await nn({file:Pt(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let i=Vr.join(Lt(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,i),await _s.rm(i,{force:!0})}return t}async function XD(e){let t=Lt(e.paths,e.state.name),i=Vr.join(t,"specs"),r=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await _s.readdir(i,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!BS.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(r.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=Vr.join(t,...s.split("/")),l=await _s.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=Vr.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let f=await _s.lstat(u);if(!f.isFile()||f.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(f){if(f.code!=="ENOENT")throw f}a.push({capability:o.name,operation:d,source:s})}return a.push(...r.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function QD(e){let t=Lt(e.paths,e.state.name),i=await Z({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),r=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await Z({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}return hl({briefMarkdown:i.text,specs:r})}async function VS(e){let t=await XD(e),i=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,l)=>{let u=e.state.spec_changes[l];return u!==void 0&&c.capability===u.capability&&c.source===u.source&&(c.operation===u.operation||i?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await QD({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!Oy(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await cm({changeDir:Lt(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c),validation:sm({...e.state,acceptance:n})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?lm({acceptance:n,children:o.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function qS(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let r={...Yn(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:hr(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete r.children_contract_hash;let n=await YD({paths:e.paths,previous:t,next:r});return await Fr(Nn(e.paths,t.name),yn({portableState:n,projectRoot:e.paths.projectRoot,branch:KD(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Lu(e){if(e.state.verification===null)return"not-applicable";let t=Vr.join(Lt(e.paths,e.state.name),"verification.md");return await Hu({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await Du({file:t,state:e.state}),"rebuilt")}async function WS(e){let t=await $a(e.paths,e.name),i=Nn(e.paths,e.name);try{let r=await Ou(i);return r===null?{state:t,local:null,localStatus:"missing"}:r.change!==t.name||r.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:r,localStatus:"available"}}catch(r){return r.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}var IY=16*1024;async function Mu(e){let t=await Zp(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Ul(t.selection.change),t.selection)}function zS(e){return Pu(e.projectRoot)}async function Ts(e,t){return await Wn(e.projectRoot),vS(e.projectRoot,"native",t)}var s4=16*1024*1024,Fu=class extends Error{constructor(i,r,n,a){super(`Canonical spec conflict for ${i}: expected ${r??"(missing)"}, actual ${n??"(missing)"}`);this.capability=i;this.expectedHash=r;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},Is=class extends Error{constructor(i,r=i.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${i.findingCodes.join(", ")}`){super(r);this.preflight=i;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function GS(e,t){let i=t.operations.find(r=>r.id==="archive-change");if(!i||i.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return Oa.resolve(e.nativeRoot,...i.target.split("/"))}async function US(e,t,i){let r=await Nr(e,t.id);if(r.some(p=>p.type==="archive-finalized"))return;let n=r.some(p=>p.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let p=t.operations.find(g=>g.id==="archive-change");if(!p||p.type!=="move"||!p.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let b=await ni(GS(e,t));if(b?.kind!=="directory"||b.hash!==p.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=GS(e,t),o=Oa.join(a,Te),s=await db(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=H(e,s.name),l=await $e(c);if(!l||l.runId!==s.run_id||l.currentStep!=="archive"&&!(l.currentStep===null&&l.status==="completed"))throw new Error(`Native archive Run state is missing or inconsistent for ${s.name}`);let u=l;if(l.currentStep==="archive"){let p=Um(Ni,l,new Set,xp,void 0);if(!p.action)throw new Error(p.reason??"Native archive produced no action");u=Km(Ni,p.state,{actionId:p.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},xp,void 0)}let d=L(`archive:${t.id}:${s.name}`),f=await it(c,u.trajectoryRef),h=f.filter(p=>p.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(h.length>1||h.some(p=>p.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let v=h.find(p=>p.type==="state_transitioned"),m={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(v&&t.schema==="comet.native.transaction.v2"&&(!ZD(v.data,m)||v.runId!==u.runId||v.timestamp!==t.createdAt||v!==f.at(-1)))throw new Error(`Native Archive trajectory event changed for transaction ${t.id}`);if(!n&&(s.archived||l.currentStep===null||h.length>0))throw new Error(`Native Archive finalization state changed before its irreversible marker: ${t.id}`);if(n||(t.schema==="comet.native.transaction.v2"?(await Eu(e,t,"archive-finalization-started"),await i?.afterFinalizationStarted?.(t)):await ta(e,t,"archive-finalization-started")),!s.archived){let p={...s,archived:!0};await ub(o,p)}v||(v=await Tr({changeDir:c,run:u,type:"state_transitioned",data:m,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await vn({changeDir:c,run:u,trajectoryOffset:v.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await un(c,u),await Ts(e,s.name),t.schema==="comet.native.transaction.v2"?await Eu(e,t,"archive-finalized"):await ta(e,t,"archive-finalized")}async function pm(e,t){let i=We(e,t);try{let r=await JS.lstat(i);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`Native Runtime cleanup target is not a real directory: ${i}`);return await T(e.runtimeDir,i),await JS.rm(i,{recursive:!0,force:!0}),null}catch(r){return r.code==="ENOENT"?null:`Archived change ${t}, but local Runtime cleanup failed: ${r.message}`}}async function eL(e,t,i){if(t.schema==="comet.native.transaction.v2"){if(!(await Nr(e,t.id)).some(c=>c.type==="operation-started")){let c=await Nu({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new Is(c,"Native Archive facts changed before the first transaction operation")}let o=await fS(e,t,{...i,beforeArchiveChangeMove:async c=>{await i?.beforeArchiveChangeMove?.(c);let l=await He(e,t.change),u=await yu({paths:e,state:l,now:new Date(t.createdAt)});if(l.phase!=="archive"||l.archived||l.verification_result!=="pass"||!["complete","partial"].includes(u.freshness)||u.findingCodes.length>0)throw new Error(`Native Archive verification freshness changed before moving ${t.change}: ${u.findingCodes.join(", ")||u.freshness}`)}});await US(e,o,i);let s=await Eu(e,o,"commit");return{journal:s,runtimeCleanupWarning:await pm(e,s.change)}}let r=await oN(e,t);await US(e,r,i);let n=await ta(e,r,"commit");return{journal:n,runtimeCleanupWarning:n.change?await pm(e,n.change):null}}function tL(e,t){if(t.kind!=="archive")throw new Error(`Transaction ${t.id} is not an archive`);if(t.schema==="comet.native.transaction.v2"){if(!t.change)throw new Error(`Archive transaction ${t.id} has no change`);return}if(Oa.resolve(t.projectRoot)!==Oa.resolve(e.projectRoot)||Oa.resolve(t.nativeRoot)!==Oa.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function KS(e){return se(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await dr(e.paths,"archive",`recover archive ${e.transactionId}`);try{let i=await yt(e.paths,e.transactionId),r=i.schema==="comet.native.transaction.v2"?await Xp(e.paths,e.transactionId):i;return tL(e.paths,r),r.status==="committed"?(r.change&&await pm(e.paths,r.change),r):r.status==="rolled-back"?r:e.strategy==="continue"?(await eL(e.paths,r)).journal:r.schema==="comet.native.transaction.v2"?hS(e.paths,r):_l(e.paths,r)}finally{await fr(t)}},{allowedTransactionId:e.transactionId})}import{promises as vL}from"fs";async function YS(e,t){let i=[],r=H(e,t.name),n=lr(r,Nt.stateRef),a;try{a=await $e(r)}catch(u){return[{code:"run-state-invalid",message:`Native Run state is invalid: ${u.message}`,path:n}]}if(!a)return(t.run_id!==null||t.phase!=="shape")&&i.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),i;if(t.run_id===null)return[{code:"run-state-unexpected",message:"Native change has a Run state but no run_id",path:n}];a.runId!==t.run_id&&i.push({code:"run-id-mismatch",message:`Native Run id ${a.runId} does not match change run_id ${t.run_id}`,path:n}),(a.pending||a.status==="waiting")&&i.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&i.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=lr(r,a.trajectoryRef),s=await la(e,t.name);if(s.status==="repairable")return i.push({code:"trajectory-tail-incomplete",message:`Native trajectory final line is incomplete at line ${s.line}; doctor repair can discard ${s.discardedBytes} incomplete byte(s)`,path:o}),i;if(s.status==="invalid")return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),i;let c;try{if(c=await it(r,a.trajectoryRef),c.length===0||c.some((u,d)=>!u||typeof u!="object"||u.sequence!==d+1||u.runId!==a.runId||typeof u.type!="string"||!u.data||typeof u.data!="object"||Array.isArray(u.data)))throw new Error("trajectory events are missing or inconsistent")}catch(u){return i.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),i}let l=lr(r,a.checkpointRef);try{let u=await ca(r,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&i.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):i.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){i.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return i}var iL=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function rL(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function nL(e){return e?e.map(rL).join(" "):null}function aL(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(i=>{if(i.startsWith('"')&&i.endsWith('"'))try{return JSON.parse(i)}catch{return i.slice(1,-1)}return i.startsWith("'")&&i.endsWith("'")?i.slice(1,-1):i})}function Mt(e,t,i,r={}){return{input:e,flags:t,required:r.required??!0,placeholder:i,...r.choices?{choices:r.choices}:{},...r.repeatable?{repeatable:!0}:{},...r.alternativeGroup?{alternativeGroup:r.alternativeGroup}:{}}}function oL(e){return e.map(t=>Mt(t,[],null))}function sL(e){let t=["comet","native","next",e.name,"--summary","<summary>"],i=[Mt("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),i.push(Mt("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:i};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),i.push(Mt("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),Mt("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let r=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),r.push("shared-understanding-confirmation"),i.push(Mt("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:r,inputOptions:i}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),i.push(Mt("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),Mt("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:i}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function Ke(e,t){let i=t.commandArgs===void 0?aL(t.command??null):t.commandArgs;return{schema:"comet.native.continuation.v1",skill:"comet-native",change:e.name,phase:e.phase,revision:e.revision,disposition:t.disposition,action:t.action,command:t.command===void 0?nL(i??null):t.command,commandArgs:i??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??oL(t.requiredInputs??[])}}function Bu(e){let i=(e.findings??[]).filter(d=>!ua(d.code)),r=i.find(d=>d.requiresUserDecision),n=i.find(d=>d.repairCommand!==null||iL.test(d.code)),a=i.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=i.find(d=>d.code==="repair-stagnation-stop"),s=i.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=i.find(d=>d.code==="runtime-missing"),l=[...new Set(i.map(d=>d.requiredAction))].sort();if(e.done)return Ke(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return Ke(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[Mt("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(r)return Ke(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return Ke(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return Ke(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return Ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[Mt("summary",["--summary"],"<summary>")]});if(n)return Ke(e.state,{disposition:"blocked",action:"repair",command:n.repairCommand,requiredInputs:l});if(e.evidenceRetreat){let d=["comet","native","next",e.state.name,"--summary","<summary>"];return Ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[Mt("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return Ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(i.length>0)return e.state.phase==="archive"?Ke(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?Ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):Ke(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:l});if(e.state.phase==="archive"){if(e.archiveReady&&e.archivePreflightHash){if(!/^[a-f0-9]{64}$/u.test(e.archivePreflightHash))throw new Error("Native Archive continuation preflight must be a SHA-256 hash");let d=["comet","native","archive",e.state.name,"--expect-preflight",e.archivePreflightHash];return e.archiveConfirmation==="required"?(d.push("--confirmed"),Ke(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[Mt("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):Ke(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return Ke(e.state,{disposition:e.archiveReady?"continue":"blocked",action:e.archiveReady?"archive":"none",commandArgs:e.archiveReady?["comet","native","archive",e.state.name,"--dry-run"]:null,requiredInputs:e.archiveReady?[]:["archive-readiness"]})}let u=sL(e.state);return Ke(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}import js from"path";var XS=8,cL={"runtime-missing":{severity:"warning",requiredAction:"rebuild-native-runtime",retry:"next",repair:"none"},"runtime-layout-legacy":{severity:"warning",requiredAction:"migrate-native-runtime-layout",retry:"status",repair:"doctor"},"runtime-storage-invalid":{severity:"error",requiredAction:"repair-native-runtime-storage",retry:"status",repair:"doctor"},"brief-blocking-question":{severity:"error",requiredAction:"answer-blocking-question",retry:"next",repair:"none"},"shape-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"approval-confirmation-required":{severity:"error",requiredAction:"confirm-shared-understanding",retry:"next",repair:"none"},"transition-incomplete":{severity:"error",requiredAction:"recover-transition",retry:"status",repair:"doctor"},"trajectory-tail-incomplete":{severity:"error",requiredAction:"repair-trajectory-tail",retry:"status",repair:"doctor"},"checkpoint-progress-invalid":{severity:"error",requiredAction:"manually-isolate-invalid-checkpoint",retry:"none",repair:"none"},"checkpoint-progress-incomplete":{severity:"error",requiredAction:"recover-progress-checkpoint",retry:"status",repair:"doctor"},"checkpoint-manifest-invalid":{severity:"error",requiredAction:"record-checkpoint-again",retry:"status",repair:"none"},"verification-scope-partial":{severity:"error",requiredAction:"confirm-partial-verification-scope",retry:"next",repair:"none"},"verification-implementation-stale":{severity:"error",requiredAction:"return-to-build-and-refresh-implementation-scope",retry:"next",repair:"none"},"verification-receipt-binding-mismatch":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-stale":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"verification-receipt-invalid":{severity:"error",requiredAction:"refresh-verification-receipts",retry:"next",repair:"none"},"native-change-conflict":{severity:"error",requiredAction:"resolve-native-change-conflict",retry:"status",repair:"none"},"native-change-overlap":{severity:"error",requiredAction:"inspect-native-change-overlap",retry:"status",repair:"none"},"contract-changed-after-approval":{severity:"error",requiredAction:"re-confirm-contract",retry:"next",repair:"none"},"baseline-snapshot-incomplete":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"baseline-snapshot-missing":{severity:"error",requiredAction:"resolve-native-baseline",retry:"none",repair:"none"},"workspace-inspection-unavailable":{severity:"info",requiredAction:"migrate-workspace-identity",retry:"status",repair:"doctor"},"workspace-binding-root-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-binding-invalid":{severity:"error",requiredAction:"repair-workspace-binding",retry:"status",repair:"none"},"workspace-branch-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-kind-changed":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"workspace-vcs-unavailable":{severity:"error",requiredAction:"return-to-bound-working-directory",retry:"status",repair:"none"},"repair-stagnation-warning":{severity:"warning",requiredAction:"change-repair-approach",retry:"next",repair:"none"},"repair-stagnation-stop":{severity:"error",requiredAction:"try-new-repair-hypothesis-with-status-override",retry:"none",repair:"none"},"repair-iteration-limit":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"},"repair-override-exhausted":{severity:"error",requiredAction:"choose-repair-continuation",retry:"none",repair:"none"}};function lL(e){let t=cL[e];return t||(/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid)|transition-invalid)/u.test(e)?{severity:"error",requiredAction:"isolate-or-restore-native-runtime-from-a-trusted-copy",retry:"none",repair:"none"}:e.startsWith("brief-")?{severity:"error",requiredAction:"complete-brief",retry:"next",repair:"none"}:e.startsWith("spec-")?{severity:"error",requiredAction:"resolve-spec-state",retry:"next",repair:"none"}:e.startsWith("verification-")?{severity:"error",requiredAction:"complete-verification-evidence",retry:"next",repair:"none"}:e.startsWith("build-")?{severity:"error",requiredAction:"record-build-evidence",retry:"next",repair:"none"}:ua(e)?{severity:e==="workspace-inspection-unavailable"?"info":"warning",requiredAction:"inspect-workspace-advisory",retry:"status",repair:"none"}:{severity:"error",requiredAction:"resolve-finding",retry:"status",repair:"none"})}function uL(e,t,i){if(!i.path)return null;let r;if(js.isAbsolute(i.path)?r=js.resolve(i.path):/^(?:brief-|verification-|spec-source)/u.test(i.code)?r=js.resolve(ne(e,t.name),...i.path.split(/[\\/]/u)):r=js.resolve(e.projectRoot,...i.path.split(/[\\/]/u)),!O(e.projectRoot,r))return null;let n=js.relative(e.projectRoot,r).replaceAll("\\","/");return n===""?".":n}function dL(e,t,i){return e==="next"?`comet native next ${t.name} --summary "<summary>"${i==="contract-changed-after-approval"||i==="shape-confirmation-required"||i==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function mm(e){return e.findings.map(t=>{let i=lL(t.code);return{code:t.code,message:t.message,severity:i.severity,path:uL(e.paths,e.state,t),requiredAction:i.requiredAction,retryCommand:dL(i.retry,e.state,t.code),repairCommand:i.repair==="doctor"?`comet native doctor ${e.state.name} --repair${t.code.startsWith("transition-")?" --strategy continue":""}`:null,requiresUserDecision:t.code==="brief-blocking-question"||t.code==="shape-confirmation-required"||t.code==="approval-confirmation-required"||t.code==="contract-changed-after-approval"||t.code==="verification-scope-partial"||t.code==="repair-iteration-limit"||t.code==="repair-override-exhausted"}}).sort((t,i)=>{let r={error:0,warning:1,info:2};return r[t.severity]-r[i.severity]||t.code.localeCompare(i.code)||(t.path??"").localeCompare(i.path??"")||t.message.localeCompare(i.message)})}function vm(e){let t=[...new Set(e.map(i=>i.code))];return{total:e.length,errors:e.filter(i=>i.severity==="error").length,warnings:e.filter(i=>i.severity==="warning").length,info:e.filter(i=>i.severity==="info").length,requiresUserDecision:e.some(i=>i.requiresUserDecision),codes:t.slice(0,XS),truncated:t.length>XS}}var QS=240,ZS=8,Vu=50;function eE(e){let t=Array.from(e);return t.length<=QS?e:`${t.slice(0,QS-1).join("")}…`}function fL(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function hL(e){let t=[...new Set(e.map(fL))],i={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,ZS),reasonCount:e.length,codesTruncated:t.length>ZS};return{inspection:i,inspectionDetails:{...i,reasons:e.slice(0,Vu),reasonsTruncated:e.length>Vu}}}async function tE(e){let t=null;try{let s=await Or(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:$r(e.paths,e.state.name)})}catch(s){t={code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}. Automatic repair is unavailable; inspect and move the invalid checkpoint journal aside before retrying`,path:$r(e.paths,e.state.name)}}let i=await qk({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),r=t?[t.code,...i.reasons]:i.reasons,n=hL(r);if(!i.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:jr.maxArtifacts};let a={id:i.checkpoint.id,createdAt:i.checkpoint.createdAt,phase:i.checkpoint.phase,stateRevision:i.checkpoint.stateRevision,summary:eE(i.checkpoint.summary),nextAction:eE(i.checkpoint.nextAction),artifactCount:i.checkpoint.artifactCount},o=i.manifest?{...a,summary:i.checkpoint.summary,nextAction:i.checkpoint.nextAction,manifestHash:i.checkpoint.manifestHash,manifestRef:i.checkpoint.manifestRef,artifacts:i.manifest.artifacts,totalBytes:i.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...i.findings]:i.findings,maxCheckpointArtifacts:jr.maxArtifacts}}async function pL(e,t){let i=H(e,t.name),r=await $e(i);if(!r||!t.run_id||r.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await ca(i,r.checkpointRef);if(!n||n.runId!==r.runId||n.stateVersion!==r.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await it(i,r.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:r.runId}}async function mL(e,t){let i=await pL(e,t);return{committed:i,latest:yk(i),history:wk(i)}}async function iE(e,t,i){if(t.phase!=="build"||t.verification_result!=="fail")return null;let r=await mL(e,t),n=r.latest;if(!n)return null;let a=r.history.filter(c=>c.kind==="failure"),o=a.length>=i,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:r.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:i,remainingVerifyFailures:Math.max(0,i-a.length)}}var gL=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Ha=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function gm(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function wL(e){return(await Mu(e))?.change??null}function yL(e,t,i=!1,r){return Bu({state:e,archiveReady:t,evidenceRetreat:i}).command}async function NL(e,t){let i=ne(e,t.name),r=[...(await tp(i,t.brief)).findings,...(await vb(e,t)).findings,...await YS(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await sa(e,t.name);if(n===null)r.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await Dl(e,n);a.complete||r.push({code:"baseline-snapshot-incomplete",message:`Native baseline is incomplete within the project-owned scope (${a.omittedCount} omitted entries); resolve the omissions before advancing`})}}catch(n){r.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await Ca({changeDir:i,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&r.push({code:"contract-changed-after-approval",message:t.approval===null||t.approved_contract_hash===null||t.approved_contract_hash===void 0?"Native approval is not bound to a contract hash; re-confirm the current contract":"Native contract changed after approval; re-confirm the current contract"})}catch(n){r.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await Mi(e,t.name)&&r.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){r.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?r.push(...(await ip(i,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&r.push({code:"verification-report-missing",message:"Native change has no verification report"}),r}async function wm(e,t,i){let r=await wL(e)===t,n=await jo(e,t),a=await QN(e,t),o;try{let w=await vi(e,t);if(w.status==="migration-required"&&w.state)return{name:t,phase:w.state.phase,revision:"revision"in w.state?w.state.revision:null,approval:w.state.approval,verificationResult:w.state.verification_result,specChanges:w.state.spec_changes.length,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["migration-required"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,migrationRequired:!0,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message};if(w.status!=="current"||!w.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["runtime-incompatible"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,schema:w.schema,minimumRuntimeVersion:w.minimumRuntimeVersion,error:w.message??`Native change ${t} is incompatible`};o=w.state}catch(w){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:r,nextCommand:null,archiveReady:!1,inspection:{freshness:"stale",codes:["change-invalid"],reasonCount:1,codesTruncated:!1},findingSummary:{total:0,errors:0,warnings:0,info:0,requiresUserDecision:!1,codes:[],truncated:!1},detailsCommand:`comet native status ${t} --details`,checkpoint:null,continuation:null,workspace:a,runtime:n,error:w.message}}if(n.status!=="available"){let w={code:n.status==="missing"?"runtime-missing":"runtime-storage-invalid",message:n.status==="missing"?`Native Runtime is missing; continue ${o.name} to rebuild local execution state`:n.message??"Native Runtime storage is invalid",path:n.path},P=mm({paths:e,state:o,findings:[w]}),F=Bu({state:o,findings:P});return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:F.command,archiveReady:!1,inspection:{freshness:"stale",codes:[w.code],reasonCount:1,codesTruncated:!1},findingSummary:vm(P),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:F,workspace:a,runtime:n,...i?.details?{findings:P}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:w.message}:{}}}let s=await tE({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await iE(e,o,i?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let w=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:w,message:`Native repair is stopped at failure signature: ${c.signatureHash}`})}}catch{l.push({code:"trajectory-invalid",message:"Native repair history could not be reconstructed safely"})}let u;if(i?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let w=await Ca({changeDir:ne(e,o.name),briefRef:o.brief,specChanges:o.spec_changes}),P=new Map;if(o.phase==="build"&&o.verification_result==="fail"&&o.verification_evidence){let Fe=await Pa(e,o.name,o.verification_evidence);for(let ue of Fe.acceptanceTrace.entries)P.set(ue.acceptanceId,ue.status==="failed"?"failed":ue.status==="missing"?"missing":"satisfied")}let F=xy({criteria:w.contract.acceptance,acceptanceHash:w.contract.acceptanceHash,verificationStatuses:P,failedCheckIds:c?.failedCheckIds??[],...i.acceptanceCursor?{cursor:i.acceptanceCursor}:{}}),$=F.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",F.nextCursor,"--project-root",e.projectRoot]:null;u={...F,...$?{nextPageCommand:gm($),nextPageArgs:$}:{}}}catch(w){if(i.acceptanceCursor)throw w;u=void 0}let d=[];if(i?.includeConflictFindings!==!1)try{let w=await cu(e,o.name,{tolerateInvalidSiblings:!0});d.push(...w.findingCodes.map(P=>({code:P,message:`Native change overlap is visible in the current root: ${P}`})))}catch{d.push({code:"native-conflict-inspection-invalid",message:"Native change overlap could not be recomputed safely"})}let f=[];try{let w=await kt(e,o.name);if(w)if(w.schema==="comet.native.workspace.v3"){let P=await fa({paths:e,identity:w});P.state==="drifted"&&P.code&&f.push({code:P.code,message:P.message??"Native workspace binding is no longer valid"})}else{let P=await Qo({paths:e,identity:w});f.push(...P.findingCodes.map(F=>({code:F,message:`Native workspace advisory changed: ${F} (${P.driftComponents.join(", ")||"no-component"})`})))}}catch{f.push({code:"workspace-binding-invalid",message:"Native workspace binding could not be read or validated safely"})}let h=[],v=!1;if(o.phase==="verify"){let w=await Qk({paths:e,state:o});v=w.freshness!=="fresh",h.push(...w.findingCodes.map(P=>({code:P,message:`Native Verify implementation scope is not current: ${P}`})))}let m=null,p=[];if(o.phase==="archive")try{m=await Nu({paths:e,name:o.name}),p.push(...m.findingCodes.map(w=>({code:w,message:`Native Archive is blocked: ${w}`})))}catch{p.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let b=[...await NL(e,o),...s.findings,...d,...f,...h,...l,...p].filter((w,P,F)=>F.findIndex($=>$.code===w.code&&$.path===w.path)===P),g=mm({paths:e,state:o,findings:b}),y=g.filter(w=>!ua(w.code)),E=o.phase==="archive"&&m?.ready===!0&&y.length===0,k=v||o.phase==="archive"&&(m?.findingCodes??[]).some(w=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(w)),S=g.some(w=>w.code==="trajectory-tail-incomplete"||w.code==="trajectory-invalid"||w.requiredAction==="return-to-bound-working-directory"||w.requiredAction==="repair-workspace-binding"),R=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",N=g.find(w=>w.severity==="error");return{name:o.name,phase:o.phase,revision:o.revision,approval:o.approval,verificationResult:o.verification_result,specChanges:o.spec_changes.length,selected:r,nextCommand:S||R?null:yL(o,E,k,i?.clarificationMode),archiveReady:E,inspection:s.inspection,findingSummary:vm(g),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Bu({state:o,findings:g,archiveReady:E,evidenceRetreat:k,clarificationMode:i?.clarificationMode}),workspace:a,runtime:n,repair:c,...i?.details?{...u?{acceptancePage:u}:{},findings:g.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:Vu,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:g.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...N?{error:N.message}:{}}}async function bL(e){let t;try{t=await Qt({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[],r=await vL.opendir(e.changesDir);try{for await(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink())&&(i.push(n.name),i.length>Ha.maxChanges))throw new Error(`Native status exceeds ${Ha.maxChanges} visible changes`)}finally{await r.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),i.sort()}function qu(e,t){let i=t.toString(36),r=D("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${i}.${r}`}function kL(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=gL.exec(e.cursor);if(!t)throw new Error("Native status cursor is invalid");if(t[1]!==e.namesHash)throw new Error("Native status cursor is stale");let i=Number.parseInt(t[2],36);if(!Number.isSafeInteger(i)||i<=0||i>=e.total||i.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let r=D("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:i});if(t[3]!==r)throw new Error("Native status cursor integrity check failed");return i}async function SL(e,t){let i=await bL(e),r=D("comet.native.status-names.v1",i),n=kL({namesHash:r,total:i.length,cursor:t?.cursor}),a=await Promise.all(i.slice(n,n+Ha.maxItems).map(u=>wm(e,u,{includeConflictFindings:!1,clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures}))),o=[];for(let u of a){let d=[...o,u],f=n+d.length,h={schema:"comet.native.status-page.v1",total:i.length,offset:n,items:d,nextCursor:f<i.length?qu(r,f):null,nextPageCommand:f<i.length?gm(["comet","native","status","--cursor",qu(r,f)]):null,nextPageArgs:f<i.length?["comet","native","status","--cursor",qu(r,f)]:null,limits:{...Ha}};if(Buffer.byteLength(JSON.stringify(h),"utf8")>Ha.maxSerializedBytes){if(o.length===0)throw new Error("Native status item exceeds its page serialization budget");break}o.push(u)}let s=n+o.length,c=s<i.length?qu(r,s):null,l=c?["comet","native","status","--cursor",c]:null;return{schema:"comet.native.status-page.v1",total:i.length,offset:n,items:o,nextCursor:c,nextPageCommand:l?gm(l):null,nextPageArgs:l,limits:{...Ha}}}async function ym(e,t){return(await SL(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}import{createHash as VL,randomUUID as qL}from"node:crypto";import{constants as Em,promises as Q}from"node:fs";import le from"node:path";var Ju=Rn(Qr(),1);import{randomUUID as EL}from"crypto";import{promises as sE}from"fs";import bm from"path";import{isDeepStrictEqual as km}from"util";var bn=/^[a-f0-9]{64}$/u,PL=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),RL=new Set(["sourceHash","targetHash","nextJournal"]),CL=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),rE=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),xL=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function Wu(e,t,i){let r=Object.keys(e).find(n=>!t.has(n));if(r)throw new Error(`${i} contains unknown field: ${r}`)}function nE(e){return JSON.stringify(e,null,2)+`
|
|
265
|
+
`}function Sm(e){return e.schema===be?Kl(e):dn(e)}function Nm(e,t){return{...e,schema:be,minimum_runtime_version:2,revision:t}}function AL(e){return{...e,schema:Ti,minimum_runtime_version:2,revision:1,previousState:Nm(e.previousState,1),nextState:Nm(e.nextState,2)}}function zu(e,t){let i=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:Ne,minimum_runtime_version:3,verification_protocol:"legacy-v1",revision:e.revision+(i&&t?.incrementRetreatRevision?1:0),phase:i?"build":e.phase,verification_result:i?"pending":e.verification_result,verification_report:i?null:e.verification_report,approved_contract_hash:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:i?!1:e.archived}}function _L(e){if(e.nextState.phase==="archive")throw new Error("Native v2 Archive transition must be superseded by schema migration");let t=e.previousState.phase!=="shape"&&e.nextState.phase==="build"&&e.eventData.verificationResult===null,i=t?L(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:pr,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:i,previousState:zu(e.previousState),nextState:{...zu(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:i},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:Ni.definition.metadata.version,skillHash:gs}:e.nextRun}}function aE(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Da(e,t){return JSON.stringify(Kl(e))===JSON.stringify(Kl(t))}function oE(e,t){return JSON.stringify(dn(e))===JSON.stringify(dn(t))}function Vi(e,t){return km(e,t)}function TL(e,t,i,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Schema migration transition supersede plan is invalid");let n=e;if(Wu(n,CL,"Schema migration transition supersede plan"),typeof n.sourceHash!="string"||!bn.test(n.sourceHash))throw new Error("Schema migration transition supersede source hash is invalid");if(typeof n.transitionId!="string"||n.transitionId.length===0)throw new Error("Schema migration superseded transition id is invalid");if(typeof n.evidenceHash!="string"||!bn.test(n.evidenceHash))throw new Error("Schema migration transition supersede evidence hash is invalid");let a=Er(n.previousRun),o=Er(n.nextRun);if(a.runId!==o.runId||i.run_id!==o.runId||i.phase!=="build"&&i.phase!=="verify"||o.currentStep!==i.phase||o.pending!==null||o.status!=="running"||i.verification_result!=="pending"||i.verification_report!==null||i.implementation_scope!==null||i.verification_evidence!==null||i.partial_allowance!==null)throw new Error("Schema migration transition supersede Run does not match target state");let s=a.currentStep==="verify"&&i.phase==="build"||a.currentStep==="archive"&&i.phase==="build",c=a.currentStep===i.phase?a:s?{...a,currentStep:i.phase,iteration:a.iteration+1,pending:null,status:"running"}:null;if(!c||!Vi(c,o))throw new Error("Schema migration transition supersede Run retreat is invalid");if(!n.eventData||typeof n.eventData!="object"||Array.isArray(n.eventData))throw new Error("Schema migration transition supersede event is invalid");let l=n.eventData,u=Object.keys(l);if(u.length!==rE.size||u.some(f=>!rE.has(f))||l.fromSchema!==be||l.toSchema!==Ne||!["build","verify","archive"].includes(l.previousPhase)||l.nextPhase!==i.phase||l.reason!==(i.phase==="build"?"implementation-scope-required":"verification-evidence-required")||l.supersededTransitionId!==n.transitionId)throw new Error("Schema migration transition supersede event semantics are invalid");if(i.name!==t)throw new Error("Schema migration transition supersede change mismatch");let d=L(JSON.stringify({operation:"supersede-v2-evidence-transition",change:t,transitionId:n.transitionId,migrationId:r,previousPhase:l.previousPhase,nextPhase:l.nextPhase,reason:l.reason,previousIteration:a.iteration,nextRevision:i.revision}));if(n.evidenceHash!==d)throw new Error("Schema migration transition supersede evidence hash mismatch");return{sourceHash:n.sourceHash,transitionId:n.transitionId,previousRun:a,nextRun:o,evidenceHash:n.evidenceHash,eventData:l}}function $s(e,t){return bm.join(H(e,t),"schema-migration.json")}function IL(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");Wu(e,PL,"Native schema migration journal");let i=e;if(i.schema!=="comet.native.schema-migration.v1")throw new Error("Unsupported Native schema migration journal");if(i.change!==t)throw new Error("Schema migration change mismatch");let r=i.fromSchema===et&&i.toSchema===be,n=i.fromSchema===be&&i.toSchema===Ne;if(!r&&!n)throw new Error("Schema migration route is unsupported");if(typeof i.id!="string"||i.id.length===0)throw new Error("Schema migration id is invalid");if(typeof i.sourceHash!="string"||!bn.test(i.sourceHash)||typeof i.targetHash!="string"||!bn.test(i.targetHash))throw new Error("Schema migration hash is invalid");if(typeof i.createdAt!="string"||Number.isNaN(Date.parse(i.createdAt)))throw new Error("Schema migration timestamp is invalid");let a=r?di(i.nextState):lt(i.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(L((0,Ju.stringify)(Sm(a)))!==i.targetHash)throw new Error("Schema migration state target hash does not match its document");let o;if(i.transition!==void 0){if(!i.transition||typeof i.transition!="object")throw new Error("Schema migration transition target is invalid");Wu(i.transition,RL,"Schema migration transition target");let l=i.transition;if(typeof l.sourceHash!="string"||!bn.test(l.sourceHash)||typeof l.targetHash!="string"||!bn.test(l.targetHash))throw new Error("Schema migration transition hash is invalid");let u=r?Hp(l.nextJournal,t):Op(l.nextJournal,t);if(L(JSON.stringify(l.nextJournal,null,2)+`
|
|
266
|
+
`)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(r&&a.schema===be?Da(a,u.previousState)||Da(a,u.nextState):a.schema===Ne&&(oE(a,u.previousState)||oE(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(r&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(i.transitionSupersede!==void 0){if(!n||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==Ne)throw new Error("Schema migration transition supersede target schema is invalid");s=TL(i.transitionSupersede,t,a,i.id)}let c;if(i.runRetreat!==void 0){if(!n||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!i.runRetreat||typeof i.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");Wu(i.runRetreat,xL,"Schema migration Run retreat");let l=i.runRetreat,u,d;try{u=Er(l.previousRun),d=Er(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!bn.test(l.evidenceHash)||!l.eventData||typeof l.eventData!="object"||Array.isArray(l.eventData))throw new Error("Schema migration Run retreat is invalid");if(a.schema!==Ne||a.phase!=="build"||a.run_id!==d.runId||u.runId!==d.runId||u.currentStep!=="verify"&&u.currentStep!=="archive"||d.currentStep!=="build"||d.iteration!==u.iteration+1)throw new Error("Schema migration Run retreat does not match target state");c={previousRun:u,nextRun:d,evidenceHash:l.evidenceHash,eventData:l.eventData}}if(o&&c||s&&c)throw new Error("Schema migration has conflicting recovery plans");return{schema:"comet.native.schema-migration.v1",id:i.id,change:t,fromSchema:i.fromSchema,toSchema:i.toSchema,sourceHash:i.sourceHash,targetHash:i.targetHash,createdAt:i.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function Os(e,t){let i=$s(e,t),r=j(e,i);await T(r,i);try{let n=await Sl({root:r,file:i,maxBytes:524288,label:"Native schema migration journal"});return IL(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function jL(e,t,i){let r=await sa(e,t),n=r?await Dl(e,r):await Ll(e,{now:new Date(i),origin:"legacy-migration"});if(!n.complete){let a=Bh(n),o=n.omitted.reduce((c,l)=>(c[l.reason]=(c[l.reason]??0)+1,c),{}),s=n.omissionOverflow?.count??0;throw s>0&&(o.overflow=s),new ha(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}r===null&&await Wh(e,t,n)}async function cE(e){try{return await Zt(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function $L(e,t){let i=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:i.nextRun.runId,data:{...i.eventData,migrationId:e.id,evidenceHash:i.evidenceHash}}}async function lE(e,t){let i=t.transitionSupersede,r=H(e,t.change),n=await it(r,i.nextRun.trajectoryRef),a=n.map((s,c)=>({event:s,index:c})).filter(({event:s})=>s.data.migrationId===t.id);if(a.length>1)throw new Error(`Native schema migration event ${t.id} is duplicated`);let o=a[0];if(o&&!km(o.event,$L(t,o.index+1)))throw new Error(`Native schema migration event ${t.id} changed`);return{trajectoryLength:n.length,sequence:o?.event.sequence??null}}async function OL(e,t,i){if(!t.transitionSupersede)return;let r=Ue(e,t.change),n=await cE(r);if(n===t.transitionSupersede.sourceHash)return;if(n!==null)throw new Error(`Native superseded transition source changed for ${t.change}: expected ${t.transitionSupersede.sourceHash}, actual ${n}`);let a=H(e,t.change),o=await $e(a),s=await lE(e,t),c=await ca(a,t.transitionSupersede.nextRun.checkpointRef);if(!i||!o||!Vi(o,t.transitionSupersede.nextRun)||s.sequence===null||!c||c.runId!==t.transitionSupersede.nextRun.runId||c.stateVersion!==t.transitionSupersede.nextRun.iteration||c.trajectoryOffset!==s.sequence||c.contextHash!==null||c.artifactsHash!==L(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function HL(e,t,i){let r=t.transitionSupersede;if(!r)return;let n=H(e,t.change),a=await $e(n);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Vi(a,r.nextRun)){if(!Vi(a,r.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await un(n,r.nextRun),await i?.afterRunStateWritten?.(t)}if(!Vi(await $e(n),r.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await lE(e,t);if(o.sequence===null){let l=await Tr({changeDir:n,run:r.nextRun,type:"state_migrated",data:{...r.eventData,migrationId:t.id,evidenceHash:r.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await i?.afterTrajectoryWritten?.(t),await vn({changeDir:n,run:r.nextRun,trajectoryOffset:o.sequence,evidenceHash:r.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t);let s=Ue(e,t.change),c=await cE(s);if(c!==null){if(c!==r.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await sE.rm(s),await i?.afterTransitionSuperseded?.(t)}}async function DL(e,t,i){if(!t.runRetreat)return;let r=H(e,t.change),n=await $e(r);if(!n)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!Vi(n,t.runRetreat.nextRun)){if(!Vi(n,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await un(r,t.runRetreat.nextRun),await i?.afterRunStateWritten?.(t)}let a=await it(r,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await Tr({changeDir:r,run:t.runRetreat.nextRun,type:"state_migrated",data:{...t.runRetreat.eventData,migrationId:t.id,evidenceHash:t.runRetreat.evidenceHash},now:new Date(t.createdAt)}),a=[...a,o]),await i?.afterTrajectoryWritten?.(t),await vn({changeDir:r,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await i?.afterCheckpointWritten?.(t)}async function LL(e,t,i){let r=await Os(e,t);if(!r)return null;if(await ma(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=bm.join(ne(e,t),Te),a=await Zt(n);if(await OL(e,r,a===r.targetHash),await jL(e,t,r.createdAt),a!==r.targetHash){if(a!==r.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${r.sourceHash}, actual ${a}`);await he(n,(0,Ju.stringify)(Sm(r.nextState))),await i?.afterStateWritten?.(r)}if(r.transition){let o=Ue(e,t),s=await Zt(o);if(s!==r.transition.targetHash){if(s!==r.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${r.transition.sourceHash}, actual ${s}`);await ee(o,r.transition.nextJournal),await i?.afterTransitionWritten?.(r)}}return await HL(e,r,i),await DL(e,r,i),await sE.rm($s(e,t),{force:!0}),r.nextState}async function ML(e){let t=H(e.paths,e.state.name),i=await $e(t);if(!i||i.runId!==e.state.run_id||i.currentStep!==e.state.phase||i.currentStep!=="verify"&&i.currentStep!=="archive"||i.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let r={...i,currentStep:"build",iteration:i.iteration+1,pending:null,status:"running"},n=L(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:i,nextRun:r,evidenceHash:n,eventData:{fromSchema:be,toSchema:Ne,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function FL(e){let{journal:t,state:i}=e;if(!(t.previousState.phase==="build"&&t.nextState.phase==="verify"||t.previousState.phase==="verify"&&(t.nextState.phase==="build"||t.nextState.phase==="archive")))throw new Error("Only a pending v2 evidence-bearing transition can be superseded");let n=Da(i,t.previousState),a=Da(i,t.nextState);if(!n&&!a)throw new Error(`Native change ${i.name} does not match its v2 evidence transition`);let o=H(e.paths,i.name),s=await $e(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${i.name}`);let c=t.previousRun!==null&&Vi(s,t.previousRun),l=Vi(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${i.name}`);let d=(await it(o,t.nextRun.trajectoryRef)).map((b,g)=>({event:b,index:g})).filter(({event:b})=>b.data.transitionId===t.id);if(d.length>1)throw new Error(`Native v2 evidence transition ${t.id} has duplicate trajectory events`);let f=d[0];if(f){let b={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!km(f.event,b)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let h={...zu(i),revision:i.revision+(i.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},v=s,m=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,p=L(JSON.stringify({operation:"supersede-v2-evidence-transition",change:i.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:h.revision}));return{nextState:h,plan:{sourceHash:await Zt(Ue(e.paths,i.name)),transitionId:t.id,previousRun:v,nextRun:m,evidenceHash:p,eventData:{fromSchema:be,toSchema:Ne,previousPhase:i.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function BL(e){let t,i,r,n;if(e.state.schema===et){if(t=Nm(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==an)throw new Error("Native v1 change has a transition from another schema generation");let s=AL(e.pendingTransition.journal);if(aE(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(aE(e.state,e.pendingTransition.journal.nextState))t=s.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v1 transition journal`);let c=Ue(e.paths,e.name);i={sourceHash:await Zt(c),targetHash:L(nE(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==Ti)throw new Error("Native v2 change has a transition from another schema generation");let s=e.pendingTransition.journal;if(s.previousState.phase==="build"&&s.nextState.phase==="verify"||s.previousState.phase==="verify"&&(s.nextState.phase==="build"||s.nextState.phase==="archive")){let l=await FL({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,r=l.plan}else{let l=_L(s);if(Da(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(Da(e.state,e.pendingTransition.journal.nextState))t=l.nextState;else throw new Error(`Native change ${e.name} does not match either state in its v2 transition journal`);let u=Ue(e.paths,e.name);i={sourceHash:await Zt(u),targetHash:L(nE(l)),nextJournal:l}}}else t=zu(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await ML({paths:e.paths,state:e.state,migrationId:e.id}));let a=bm.join(ne(e.paths,e.name),Te),o=(0,Ju.stringify)(Sm(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===et?be:Ne,sourceHash:await Zt(a),targetHash:L(o),createdAt:e.now.toISOString(),nextState:t,...i?{transition:i}:{},...r?{transitionSupersede:r}:{},...n?{runRetreat:n}:{}}}async function uE(e){return se(e.paths,`migrate schema for ${e.name}`,()=>gn(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let i=await LL(e.paths,e.name,e.hooks);if(i?.schema===Ne)return i;let r=await vi(e.paths,e.name);if(r.status==="current"&&r.state)return r.state;if(r.status!=="migration-required"||!r.state)throw new Error(r.message??`Native change ${e.name} cannot be migrated`);if(await ma(e.paths,e.name))throw new Error(`Native change ${e.name} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=r.state;if(n.schema!==et&&n.schema!==be)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await Dp(e.paths,e.name);if(a?.status==="current")throw new Error(`Native change ${e.name} has a current-schema pending transition; recover it before schema migration`);let o=await BL({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??EL()}),s=$s(e.paths,e.name),c=j(e.paths,s);await T(c,s),await ee(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}var qi=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),WL=512*1024,kn=/^([a-f0-9]{64})\.json$/u,zL=/^\.([a-f0-9]{64}\.json)\.([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.gc$/u,JL=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,Gu=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function Rm(e,t){return z({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Pi(e,t){return Rm(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function mE(e,t){return Rm(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function La(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function nt(e,t){return e<t?-1:e>t?1:0}function GL(e,t){let i=le.relative(e.projectRoot,t);if(i.length===0||le.isAbsolute(i)||i===".."||i.startsWith(`..${le.sep}`))throw new Error("Native evidence retention finding path is outside the project");return i.split(le.sep).join("/")}function vE(e,t){return le.join(H(e,t),"evidence")}function Uu(e,t){return GL(e,vE(e,t))}async function Ku(e,t){let i=le.resolve(e),r=le.resolve(t);if(!O(i,r))throw new Error("Native evidence retention path escapes its managed change");let n=le.relative(i,r).split(le.sep).filter(Boolean),a=[],o=i;for(let s of["",...n]){s&&(o=le.join(o,s));let c=await Q.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await Q.realpath(o);if(a.length>0&&!O(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...La(c)})}return a}async function Ft(e){for(let t of e){let i=await Q.lstat(t.path);if(!i.isDirectory()||i.isSymbolicLink()||!Rm(t,i)||await Q.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function gE(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:Ea(e,t)}function dE(e){return e!==null&&JL.test(e)?[e]:[]}function UL(e,t,i,r){if(e==="snapshots")return{canonical:wa(i,t),dependencies:[]};if(e==="scopes"){let a=ya(i);if(a.scopeHash!==t)throw new Error("Native scope filename does not match its hash");return{canonical:a,dependencies:[a.baselineProjectionRef,a.currentProjectionRef]}}if(e==="allowances"){let a=ru(i);if(a.change!==r||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[Ea("scopes",a.scopeHash)]}}if(e==="verifications"){let a=fs(i);if(a.change!==r||a.envelopeHash!==t)throw new Error("Native verification filename/change does not match its content");let o=a.acceptanceTrace.entries.flatMap(s=>s.evidenceRefs.flatMap(dE));return{canonical:a,dependencies:[a.implementationScopeRef,ck(a.reportHash),...dE(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Native report evidence must be an object");let a=i;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||VL("sha256").update(Buffer.from(a.content,"utf8")).digest("hex")!==t)throw new Error("Native report evidence filename/hash does not match its content");return{canonical:a,dependencies:[]}}if(e==="receipts"){let a=au(i);if(a.bindings.change!==r||a.receiptHash!==t)throw new Error("Native verification receipt filename/change does not match its content");return{canonical:a,dependencies:a.kind==="static-inspection"?[a.evidence.checkReceiptRef]:[]}}let n=nu(i);if(n.change!==r||n.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:n,dependencies:[]}}async function Wr(e){let t=await Q.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let i=e.kind==="check-receipts"?WL:_r;if(t.size>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let r=await Q.realpath(e.file);if(!O(e.directoryChain[0].realPath,r))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let n=process.platform==="win32"?"r":Em.O_RDONLY|Em.O_NOFOLLOW|Em.O_NONBLOCK,a=await Q.open(e.file,n).catch(o=>{throw o.code==="ELOOP"||o.code==="ENXIO"?new Error(`Native evidence entry became unsafe while opening: ${e.ref}`):o});try{let[o,s,c]=await Promise.all([a.stat(),Q.lstat(e.file),Q.realpath(e.file)]);if(await Ft(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==r||!Pi(La(t),o)||!Pi(La(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let g=i+1-d,y=await a.read(u,0,Math.min(u.length,g),null);if(y.bytesRead===0)break;if(d+=y.bytesRead,d>i)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,y.bytesRead)))}let[f,h,v]=await Promise.all([a.stat(),Q.lstat(e.file),Q.realpath(e.file)]);if(await Ft(e.directoryChain),!h.isFile()||h.isSymbolicLink()||v!==r||!Pi(La(o),f)||!Pi(La(o),h))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let m=Buffer.concat(l,d).toString("utf8"),p;try{p=JSON.parse(m)}catch(g){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:g})}let b=UL(e.kind,e.hash,p,e.name);if(m!==JSON.stringify(b.canonical,null,2)+`
|
|
267
|
+
`)throw new Error(`Native evidence entry is not canonically serialized: ${e.ref}`);return{ref:e.ref,kind:e.kind,change:e.name,changeRoot:e.changeRoot,file:e.file,size:d,mtimeMs:f.mtimeMs,identity:La(f),directoryChain:e.directoryChain,dependencies:[...new Set(b.dependencies)].sort(nt)}}finally{await a.close()}}async function fE(e){try{return await Q.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function KL(e){let t=H(e.paths,e.name),i=t,r=vE(e.paths,e.name);await T(j(e.paths,r),r);let n;try{let s=await Ku(t,r);n=await Q.readdir(r,{withFileTypes:!0}),await Ft(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of Gu){if(!n.some(f=>f.name===s))continue;let c=le.join(r,s),l=await Ku(t,c),u=(await Q.readdir(c,{withFileTypes:!0})).sort((f,h)=>nt(f.name,h.name)),d=new Map;for(let f of u){let h=zL.exec(f.name);if(!h)continue;let v=d.get(h[1])??[];v.push(f),d.set(h[1],v)}for(let[f,h]of[...d.entries()].sort(([v],[m])=>nt(v,m))){if(h.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${s}/${f}`);let v=h[0];if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${s}/${v.name}`);let m=le.join(c,f),p=kn.exec(f)?.[1];if(!p)throw new Error(`Native evidence cleanup quarantine name is invalid: ${v.name}`);let b=gE(s,p),g=le.join(c,v.name),y=await Wr({changeRoot:i,file:g,ref:b,kind:s,hash:p,name:e.name,directoryChain:l}),E=await fE(m),k=E?null:await Wr({changeRoot:i,file:m,ref:b,kind:s,hash:p,name:e.name,directoryChain:l});a.push({ref:b,original:m,quarantine:g,document:y,action:E?"restore-original":"finish-linked-recovery",originalDocument:k})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(nt);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:Ma(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${Yu(o)}`),path:Uu(e.paths,e.name)}]};for(let s of a.sort((c,l)=>nt(c.ref,l.ref))){if(await Ft(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await Wr({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:kn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await Wr({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:kn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!Pi(s.originalDocument.identity,d.identity)||!Pi(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await Q.rm(s.quarantine),await Ft(s.document.directoryChain);continue}if(!await fE(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await Q.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!Pi(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await Q.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await Wr({changeRoot:i,file:s.original,ref:s.ref,kind:s.document.kind,hash:kn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await Wr({changeRoot:i,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:kn.exec(le.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!mE(s.document.identity,l.identity)||!Pi(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await Q.rm(s.quarantine),await Ft(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:Ma(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${Yu(o)}`),path:Uu(e.paths,e.name)}]}}async function YL(e,t){let i=H(e,t),r=i,n=le.join(i,"evidence");await T(j(e,n),n);let a;try{let l=await Ku(i,n);a=await Q.readdir(n,{withFileTypes:!0}),await Ft(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!Gu.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(nt);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${Yu(o)}`);let s=[],c=0;for(let l of Gu){if(!a.some(h=>h.name===l))continue;let u=le.join(n,l),d=await Ku(r,u),f=(await Q.readdir(u,{withFileTypes:!0})).sort((h,v)=>nt(h.name,v.name));await Ft(d);for(let h of f){if(s.length>=qi.maxDocuments)throw new Error(`Native evidence store exceeds ${qi.maxDocuments} documents`);let v=kn.exec(h.name);if(!v||!h.isFile()||h.isSymbolicLink())throw new Error(`Native evidence kind ${l} has an unknown or special entry: ${h.name}`);let m=gE(l,v[1]),p=le.join(u,h.name);await T(j(e,p),p);let b=await Wr({changeRoot:r,file:p,ref:m,kind:l,hash:v[1],name:t,directoryChain:d});if(c+=b.size,c>qi.maxScannedBytes)throw new Error(`Native evidence store exceeds ${qi.maxScannedBytes} scanned bytes`);s.push(b)}await Ft(d)}return s}function hE(e,t){let i=new Set,r=[...e].sort(nt).reverse();for(;r.length>0;){let n=r.pop();if(i.has(n))continue;let a=t.get(n);if(!a)throw new Error(`Native evidence dependency is missing: ${n}`);i.add(n);for(let o of[...a.dependencies].sort(nt).reverse())i.has(o)||r.push(o)}return i}function XL(e){let t=new Map(e.map(a=>[a.ref,a])),i=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&i.set(o,(i.get(o)??0)+1);let r=[...i].filter(([,a])=>a===0).map(([a])=>a).sort(nt),n=[];for(;r.length>0;){let a=r.shift(),o=t.get(a);n.push(o);for(let s of o.dependencies){let c=i.get(s);if(c===void 0)continue;let l=c-1;i.set(s,l),l===0&&(r.push(s),r.sort(nt))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function QL(e,t,i){let r=new Map(e.map(c=>[c.ref,c]));if(r.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!r.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let n=hE(t,r),a=new Set(n);for(let c of e)i-c.mtimeMs<qi.minimumAgeMs&&a.add(c.ref);for(let c of Gu){let l=e.filter(u=>u.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||nt(u.ref,d.ref)).slice(0,qi.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=hE(a,r),s=e.filter(c=>!o.has(c.ref)&&i-c.mtimeMs>=qi.minimumAgeMs).sort((c,l)=>nt(c.ref,l.ref));return{candidates:XL(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function Yu(e){let t=e.slice(0,qi.maxReportedRefs),i=e.length-t.length;return`${t.join(", ")}${i>0?`, ... (${i} more)`:""}`}function Ma(e){let t=qi.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let i=e;for(;i.length>0&&Buffer.byteLength(`${i}...`,"utf8")>t;)i=i.slice(0,-1);return`${i}...`}function Pm(e,t,i,r){let n=t.candidates.map(a=>a.ref).sort(nt);return{severity:"info",code:i?"evidence-retention-cleaned":"evidence-retention-candidates",message:Ma(`${i?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${Yu(n)}`),path:r}}async function pE(e,t){try{await Q.lstat(t);return}catch(i){if(i.code!=="ENOENT")return}try{await Q.rename(e,t)}catch{}}async function ZL(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await Ft(e.directoryChain);let i=await Wr({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:kn.exec(le.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),r=await Q.lstat(e.file),n=await Q.realpath(e.file);if(!r.isFile()||r.isSymbolicLink()||!Pi(e.identity,r)||!Pi(e.identity,i.identity)||!O(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=le.join(le.dirname(e.file),`.${le.basename(e.file)}.${qL()}.gc`);await Q.rename(e.file,a);try{let[o,s]=await Promise.all([Q.lstat(a),Q.realpath(a)]);if(await Ft(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!mE(e.identity,o)||!O(e.directoryChain[0].realPath,s))throw await pE(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await Q.rm(a),await Ft(e.directoryChain)}catch(o){throw await pE(a,e.file),o}}async function eM(e){if((await ye(e.projectRoot))?.native.pending_root_move)return!0;let i;try{i=await Q.readdir(e.transactionsDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return!1;throw r}for(let r of i){if(!r.isDirectory()||r.isSymbolicLink())return!0;try{let n=await yt(e,r.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function tM(e,t){if(t)return[t];let i;try{i=await Q.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return i.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort(nt)}async function iM(e,t){let i=await vi(e,t);if(i.status!=="current"||!i.state||i.state.archived)return!0;let[r,n,a]=await Promise.all([Mi(e,t),Os(e,t),Or(e,t)]);return r!==null||n!==null||a!==null}async function rM(e){if(await iM(e.paths,e.name))return[];let t=await vi(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let i=await KL({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(i.pending)return i.findings;let r=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&r.push(c);let n=await YL(e.paths,e.name),a=QL(n,r,e.nowMs);if(a.candidates.length===0)return i.findings;let o=Uu(e.paths,e.name);if(!e.repair)return[...i.findings,Pm(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await ZL(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...i.findings,...s.length>0?[Pm(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:Ma(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...i.findings,Pm(e.name,a,!0,o)]}async function wE(e){if(e.deferAll||await eM(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let i=async n=>{let a=[];for(let o of await tM(e.paths,e.name))try{a.push(...await rM({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:Ma(`Native evidence retention refused to clean ${o}: ${s.message}`),path:Uu(e.paths,o)})}return a};if(!(e.repair??!1))return i(!1);let r=await i(!1);if(r.some(n=>n.severity==="error")||!r.some(n=>n.code==="evidence-retention-candidates"||n.code==="evidence-retention-recovery-required"))return r;try{return await se(e.paths,"prune Native evidence",()=>i(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:Ma(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}import{createHash as nM,randomUUID as F6}from"crypto";import{promises as Ls}from"fs";import ae from"path";var xm=64*1024*1024,aM=256*1024,kE=16*1024*1024;async function at(e){try{return await Ls.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function oM(e){let t;try{t=await Ls.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return;throw i}for(let i of t.sort((r,n)=>r.name.localeCompare(n.name))){if(!i.isDirectory()||i.isSymbolicLink())continue;let r=await kt(e,i.name);if(r){await Jl({paths:e,name:i.name,revision:r.capturedRevision,...r.schema==="comet.native.workspace.v3"?{binding:{isolation:r.isolation,changeBranch:r.changeBranch,targetBranch:r.targetBranch},...r.finish?{finish:r.finish}:{}}:{}});continue}}}async function Ds(e,t){let i=[];async function r(n){let a=await wt({root:e,directory:n,label:"Native root tree"}),o=a.entries;o.sort((s,c)=>s.name.localeCompare(c.name));for(let s of o){await a.verify();let c=ae.join(n,s.name);if(t.excludedFiles?.has(ae.resolve(c))){await a.verify();continue}let l=await Ls.lstat(c);if(s.isSymbolicLink()||l.isSymbolicLink()){if(t.rejectSymlinks)throw new Error(`Native root contains a symlink: ${c}`);await a.verify();continue}if(s.isDirectory()&&l.isDirectory())i.push({ref:ae.relative(e,c).split(ae.sep).join("/"),type:"directory"}),await r(c);else if(s.isFile()&&l.isFile()){let u=await re({root:e,file:c,maxBytes:xm,label:`Native root file ${ae.relative(e,c)}`});i.push({ref:ae.relative(e,c).split(ae.sep).join("/"),type:"file",size:u.size,hash:u.hash})}else throw new Error(`Native root contains an unsupported file type: ${c}`);await a.verify()}}return await r(e),i.sort((n,a)=>n.ref.localeCompare(a.ref))}async function sM(e,t,i,r){await fi({root:r,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await wt({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=ae.join(a,l.name);if(ae.resolve(u)===ae.resolve(i)){await s.verify();continue}let d=await Ls.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=ae.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await fi({root:r,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await wr({sourceRoot:e,source:u,targetRoot:r,target:f,maxBytes:xm,label:`Native root move file ${ae.relative(e,u)}`,exclusive:!0,expectedTargetHash:null});else throw new Error(`Native root contains an unsupported file type: ${u}`);await s.verify()}}await n(e,t)}async function Fa(e,t,i,r){let n=await Ds(e,{rejectSymlinks:!0,excludedFiles:i?new Set([ae.resolve(i)]):void 0}),a=await Ds(t,{rejectSymlinks:!0,excludedFiles:r?new Set([ae.resolve(r)]):void 0});if(JSON.stringify(n)!==JSON.stringify(a))throw new Error(`Native root copies differ; preserve both trees for manual recovery: ${e} and ${t}`)}function cM(e,t){return ae.join(e.artifactRoot,`.comet-native-move-${t}`)}function lM(e,t){return ae.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function uM(e){return`${e}.removing`}function yE(e,t){return ae.join(ae.dirname(e),`.${ae.basename(e)}.${t}.rollback-removing`)}function SE(e,t,i){return ae.join(Al(e,t).directory,`root-move-cleanup-${i}.json`)}function dM(e){return JSON.stringify(e,null,2)+`
|
|
268
|
+
`}function fM(e){return nM("sha256").update(e).digest("hex")}function hM(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Native root-move cleanup manifest entry ${t} must be an object`);let i=e,r=Object.keys(i).sort(),n=i.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(r)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof i.ref!="string"||i.ref.length===0||i.ref.includes("\\")||ae.posix.normalize(i.ref)!==i.ref||i.ref.startsWith("/")||i.ref.split("/").includes("..")||Buffer.byteLength(i.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(i.type==="directory")return{ref:i.ref,type:"directory"};if(i.type!=="file"||typeof i.size!="number"||!Number.isSafeInteger(i.size)||i.size<0||typeof i.hash!="string"||!/^[a-f0-9]{64}$/u.test(i.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:i.ref,type:"file",size:i.size,hash:i.hash}}function pM(e,t,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let r=e;if(JSON.stringify(Object.keys(r).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||r.schema!=="comet.native.root-move-cleanup.v1"||r.transactionId!==t||r.kind!==i||!Array.isArray(r.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=r.entries.map(hM);for(let a=0;a<n.length;a+=1){if(a>0&&n[a-1].ref.localeCompare(n[a].ref)>=0)throw new Error("Native root-move cleanup manifest refs must be unique and sorted");let o=ae.posix.dirname(n[a].ref);if(o!=="."&&!n.some(s=>s.ref===o&&s.type==="directory"))throw new Error(`Native root-move cleanup manifest parent is missing: ${o}`)}return{schema:"comet.native.root-move-cleanup.v1",transactionId:t,kind:i,entries:n}}async function mM(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},i=dM(t);if(Buffer.byteLength(i,"utf8")>kE)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await he(SE(e.paths,e.id,e.kind),i,{containedRoot:e.paths.runtimeDir}),fM(i)}async function vM(e){let t=await re({root:e.paths.runtimeDir,file:SE(e.paths,e.id,e.cleanup.kind),maxBytes:kE,label:`Native root-move cleanup manifest ${e.cleanup.kind}`});if(t.hash!==e.cleanup.manifestHash)throw new Error("Native root-move cleanup manifest hash changed");return pM(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function Cm(e){let t=await Ds(e.quarantine,{rejectSymlinks:!0}),i=new Map(e.manifest.entries.map(r=>[r.ref,r]));for(let r of t){let n=i.get(r.ref);if(!n||JSON.stringify(n)!==JSON.stringify(r))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${r.ref}`)}if(e.exact&&t.length!==e.manifest.entries.length)throw new Error("Native root-move cleanup quarantine is incomplete before deletion");return t}function NE(e){return e.ref.split("/").length}async function gM(e){let i=[...await Cm({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>NE(a)-NE(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),r=0;for(let n of i){let a=ae.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await El({root:e.projectRoot,file:a,maxBytes:xm,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await Ph({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),r+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,r)}await Cm({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await Ph({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function EE(e,t,i=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:i,pending_root_move:t}}}function wM(e){return{schema:"comet.native.transaction.v1",id:e.id,kind:"root-move",status:"prepared",projectRoot:e.paths.projectRoot,nativeRoot:e.paths.nativeRoot,createdAt:e.now.toISOString(),operations:[]}}async function yM(e,t,i,r){for(let a of[e,t])try{let o=await yt(a,r);if(o.kind!=="root-move")throw new Error(`Transaction ${r} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let n=ae.join(i,"runtime","transactions",r,"transaction.json");try{let a=await re({root:i,file:n,maxBytes:aM,label:`Staged Native root-move journal ${r}`}),o=JSON.parse(a.bytes.toString("utf8"));if(o.schema!=="comet.native.transaction.v1"||o.kind!=="root-move")throw new Error(`Invalid staged root-move journal: ${r}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${r}`,{cause:a})}}async function bE(e){let t=EE(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await ur(e.projectRoot,t),t}async function Hs(e){let t=e.config.native.pending_root_move;if(!t||t.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=EE(e.config,{id:t.id,fromArtifactRoot:t.fromArtifactRoot,toArtifactRoot:t.toArtifactRoot,stage:t.stage,...e.cleanup?{cleanup:e.cleanup}:{}},e.config.native.artifact_root);return await ur(e.projectRoot,i),i}async function Xu(e){let t=e.config,i=t.native.pending_root_move;if(!i||i.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let r=i.cleanup;if(r&&r.kind!==e.kind)throw new Error(`Native root move has unfinished ${r.kind} cleanup; cannot start ${e.kind}`);let n=await at(e.target),a=await at(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!r){if(!n&&!a)return t;if(!n&&a)throw new Error(`Native root-move cleanup quarantine is not transaction-bound: ${e.kind}`);let s=await mM({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await Ds(e.target,{rejectSymlinks:!0})});r={kind:e.kind,state:"prepared",manifestHash:s},t=await Hs({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})}let o=await vM({paths:e.stablePaths,id:e.id,cleanup:r});if(n=await at(e.target),a=await at(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(r.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await Uy({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(r.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return Hs({projectRoot:e.projectRoot,config:t,id:e.id})}return await Cm({quarantine:e.quarantine,manifest:o,exact:r.state!=="deleting"}),r.state==="prepared"&&(r={...r,state:"quarantined"},t=await Hs({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),r.state==="quarantined"&&(r={...r,state:"deleting"},t=await Hs({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:r})),await gM({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),Hs({projectRoot:e.projectRoot,config:t,id:e.id})}async function NM(e){let t=e.config,i=t.native.pending_root_move.stage;if(i==="copying"){if(!await at(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=uM(e.staging);t=await Xu({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"restart-staging",stablePaths:e.sourcePaths,target:e.staging,quarantine:s,label:"Native root move stale staging removal",hooks:e.hooks}),await Ds(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([ae.resolve(e.lockFile)])}),await sM(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await Fa(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await bE({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),i="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(i==="ready"){if(await at(e.destinationPaths.nativeRoot)){if(await at(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await Fa(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await at(e.staging))throw new Error("Native move staging tree is missing");await Fa(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await Ls.rename(e.staging,e.destinationPaths.nativeRoot)}t=await bE({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),i="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(i!=="switched")throw new Error(`Unsupported Native root-move stage: ${i}`);if(!await at(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let r=lM(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await at(e.sourcePaths.nativeRoot)&&await Fa(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await Xu({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:r,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await oM(e.destinationPaths);let n=await yt(e.destinationPaths,e.pending.id);await ta(e.destinationPaths,n,"commit");let a={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},o={...t,native:{...a,artifact_root:e.pending.toArtifactRoot}};return await ur(e.projectRoot,o),o}async function PE(e){let t=await ye(e.projectRoot),i=t?.native.pending_root_move;if(!t||!i)throw new Error("No pending Native root move was found");let r=await qe(e.projectRoot,i.fromArtifactRoot),n=await qe(e.projectRoot,i.toArtifactRoot),a=cM(n,i.id),o=await at(r.nativeRoot)?r:n,s=await dr(o,"root-move",`recover root ${i.id}`);try{let c;try{c=await yM(r,n,a,i.id)}catch(v){if(i.stage!=="copying"||!await at(r.nativeRoot))throw v;let m=wM({id:i.id,paths:r,now:new Date});await nN(r,m),c={journal:m,paths:r}}if(e.strategy==="continue"){let v=await NM({projectRoot:e.projectRoot,config:t,pending:i,sourcePaths:r,destinationPaths:n,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:n.nativeRoot,config:v}}if(!await at(r.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=yE(n.nativeRoot,i.id);!t.native.pending_root_move?.cleanup&&await at(n.nativeRoot)&&await Fa(r.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await Xu({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-destination",stablePaths:r,target:n.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=yE(a,i.id);!t.native.pending_root_move?.cleanup&&await at(a)&&await Fa(r.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await Xu({projectRoot:e.projectRoot,config:t,id:i.id,kind:"rollback-staging",stablePaths:r,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await yt(r,i.id);await _l(r,d);let f={artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,snapshot:t.native.snapshot},h={...t,native:{...f,artifact_root:i.fromArtifactRoot}};return await ur(e.projectRoot,h),{activeNativeRoot:r.nativeRoot,config:h}}finally{await fr(s)}}var Ba=4096,bM=4096,kM=1024;async function zr(e,t,i){try{let r=await wt({root:j(e,t),directory:t,label:"Native doctor directory",maxEntries:i});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function Zu(e,t){let i=new Map(e.map(r=>[Ie.resolve(r.file),{...r,file:Ie.resolve(r.file)}]));for(let{paths:r,file:n}of i.values()){let a;try{a=await $o(n)}catch(o){return t.push({severity:"error",code:"lock-invalid",message:`Native recovery lock is invalid: ${o.message}`,path:n}),!1}if(a.status!=="missing"){if(a.status==="stale"){let o=await hh(r,n,a);if(o.status==="removed"){t.push({severity:"info",code:"stale-recovery-lock-removed",message:"Removed stale lock before explicit transaction recovery",path:n});continue}if(o.status==="missing")continue;a=o.diagnosis}return a.status==="stale"?(t.push({severity:"error",code:"lock-takeover-raced",message:"Native recovery lock changed while doctor was preparing stale takeover",path:n}),!1):(t.push({severity:"error",code:a.status==="active"?"lock-active":"lock-owner-unknown",message:a.status==="active"?"Native recovery lock is still owned by a live process":"Native recovery lock owner cannot be proven stale",path:n}),!1)}}return!0}async function SM(e,t){let i=zS(e),r;try{await T(e.projectRoot,i);let n=await Mu(e);if(!n)return[];r=n}catch(n){return n.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${n.message}`,path:i}]}if(r.schema!=="comet.selection.v2"||r.workflow!=="native"||typeof r.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:i}];try{return await qr(e,r.change)?[]:(await He(e,r.change),[])}catch(n){if(n.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${n.message}`,path:i}]}return t?(await Qu.rm(i,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${r.change}`,path:i}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${r.change}`,path:i}]}async function EM(e){let t=[];for(let i of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await T(j(e,i),i)}catch(r){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${r.message}`,path:i})}return t}async function PM(e,t){let i=[],r=[];for(let n of await zr(e,e.transactionsDir,bM)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await yt(e,n.name)}catch(o){i.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:Ie.join(e.transactionsDir,n.name)});continue}if(!(a.status==="committed"||a.status==="rolled-back")&&!(t.name&&a.change&&a.change!==t.name)){if(a.kind!=="archive"){r.push(a),i.push({severity:"error",code:"root-move-transaction-orphaned",message:`Root-move transaction ${a.id} is incomplete but project config has no matching pending move`});continue}if(t.repair&&t.recoveryStrategy)try{if(!await zn([e],`doctor archive recovery ${a.id}`,async()=>await Zu([{paths:e,file:Ie.join(e.locksDir,"root-move.lock")},{paths:e,file:Ie.join(e.locksDir,"archive.lock")}],i)?(await KS({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){r.push(a);continue}i.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){r.push(a),i.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else r.push(a),i.push({severity:"error",code:"archive-transaction-incomplete",message:t.repair?`Archive transaction ${a.id} needs an explicit recovery strategy`:`Archive transaction ${a.id} is incomplete`,repair:t.recoveryStrategy??"continue"})}}return{findings:i,unfinished:r}}async function RM(e,t,i){let r=[];for(let n of await zr(e,e.locksDir,kM)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=Ie.join(e.locksDir,n.name);try{let o=await $o(a);if(o.status==="active")r.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")r.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&i.length===0){let s=await hh(e,a,o);s.status==="removed"?r.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&r.push({severity:s.diagnosis.status==="active"?"warning":"error",code:"lock-takeover-raced",message:"Native lock changed while doctor was preparing stale takeover",path:a})}else r.push({severity:i.length>0?"error":"warning",code:"lock-stale",message:i.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){r.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return r}async function CM(e,t,i=5){let r=[],n=t?await ym(e,{maxVerifyFailures:i}).then(a=>a.filter(o=>o.name===t)):await ym(e,{maxVerifyFailures:i});if(t&&n.length===0)return[{severity:"error",code:"change-missing",message:`Native change does not exist: ${t}`}];for(let a of n){if(a.migrationRequired)continue;if(a.phase==="invalid"){r.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:Ie.join(e.changesDir,a.name,Te)});continue}let o=await wm(e,a.name,{details:!0,maxVerifyFailures:i});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||r.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:Ie.join(e.projectRoot,s.path)}:{}})}return r}async function xM(e,t){let i=[],r=t.name?[t.name]:(await zr(e,e.changesDir,Ba)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{let a=await la(e,n);if(a.status!=="repairable")continue;if(!t.repair){i.push({severity:"error",code:"trajectory-tail-incomplete",message:`Native trajectory for ${n} has an incomplete final line ${a.line}; ${a.discardedBytes} byte(s) are outside the last complete event`,path:a.file,repair:"truncate-tail"});continue}let o=await qN(e,n);o&&i.push({severity:"info",code:"trajectory-tail-repaired",message:`Removed the incomplete Native trajectory tail for ${n} and preserved all complete events`,path:o.file})}catch(a){i.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${n}: ${a.message}`,path:Ie.join(H(e,n),"trajectory.jsonl")})}return i}async function AM(e,t){let i=[],r=t.name?[t.name]:(await zr(e,e.changesDir,Ba)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=await jo(e,n);if(a.status==="missing"){i.push({severity:"warning",code:"runtime-missing",message:`Native Runtime for ${n} is missing; continue the change to rebuild it`,path:a.path});continue}if(a.status==="invalid"){i.push({severity:"error",code:"runtime-storage-invalid",message:a.message??`Native Runtime storage for ${n} is invalid`,path:a.path});continue}if(a.layout!=="legacy")continue;let o=tn(e,n),s=We(e,n);if(!t.repair){i.push({severity:"warning",code:"runtime-layout-legacy",message:`Native Runtime for ${n} still uses the legacy change-local layout`,path:o,repair:"migrate"});continue}try{await zn([e],`migrate Runtime layout for ${n}`,async()=>{let c=await Qt({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await T(e.runtimeDir,s),await Qu.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await Qt({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await Qu.lstat(s),new Error(`Target Native Runtime already exists: ${s}`)}catch(u){if(u.code!=="ENOENT")throw u}await c.verify(),await l.verify(),await Qu.rename(o,s)}),i.push({severity:"info",code:"runtime-layout-migrated",message:`Moved Native Runtime for ${n} to project-local .comet storage`,path:s})}catch(c){i.push({severity:"error",code:"runtime-layout-migration-failed",message:`Native Runtime layout migration failed for ${n}: ${c.message}`,path:o})}}return i}async function _M(e,t){let i=[],r=t.name?[t.name]:(await zr(e,e.changesDir,Ba)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r)try{if(!await Yh(e,n))continue;if(!t.repair){i.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${n} uses legacy external-probe or hash-only metadata`,path:da(e,n),repair:"migrate"});continue}let a=await He(e,n);await eb({paths:e,name:n,revision:a.revision})&&i.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${n} with process-free root identities`,path:da(e,n)})}catch(a){i.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:da(e,n)})}return i}async function TM(e,t){let i=[],r=t.name?[t.name]:(await zr(e,e.changesDir,Ba)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=$s(e,n);try{let o=await Os(e,n),s=await vi(e,n);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){i.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${n} requires a newer runtime`,path:Ie.join(e.changesDir,n,Te)});continue}if(!t.repair){i.push({severity:"error",code:o?"schema-migration-incomplete":"schema-migration-required",message:o?`Native schema migration ${o.id} is incomplete for ${n}`:`Native change ${n} requires migration to the current schema`,path:o?a:Ie.join(e.changesDir,n,Te),repair:"migrate"});continue}await uE({paths:e,name:n}),i.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${n} to the current schema`,path:Ie.join(e.changesDir,n,Te)})}catch(o){if(o.code==="ENOENT")continue;i.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${n}: ${o.message}`,path:a})}}return i}async function IM(e,t){let i=[],r=t.name?[t.name]:(await zr(e,e.changesDir,Ba)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a;try{a=await Mi(e,n)}catch(o){if(o instanceof ws)continue;i.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:Ue(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await zn([e],`doctor transition recovery ${n}`,async()=>await Zu([{paths:e,file:Ie.join(e.locksDir,"root-move.lock")},{paths:e,file:Ie.join(e.locksDir,`transition-${n}.lock`)}],i)?(await jk(e,n),!0):!1))continue;i.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:Ue(e,n)})}catch(o){i.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:Ue(e,n)})}continue}i.push({severity:"error",code:"transition-incomplete",message:t.repair&&t.recoveryStrategy==="rollback"?`Native phase transition ${a.id} only supports deterministic continue recovery`:`Native phase transition ${a.id} is incomplete for ${n}`,path:Ue(e,n),repair:"continue"})}}return i}async function jM(e,t){let i=[],r=t.name?[t.name]:(await zr(e,e.changesDir,Ba)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of r){let a=$r(e,n),o;try{o=await Or(e,n)}catch(s){if(s.code==="ENOENT")continue;i.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){i.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${n}`,path:a});continue}try{if(!await zn([e],`doctor checkpoint recovery ${n}`,async()=>await Zu([{paths:e,file:Ie.join(e.locksDir,"root-move.lock")},{paths:e,file:Ie.join(e.locksDir,`transition-${n}.lock`)}],i)?(await zk(e,n),!0):!1))continue;i.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${n}`,path:a})}catch(s){i.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return i}async function Ms(e){let t=e.repair??!1,i=[],r=e.paths,n;try{n=await ye(r.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:r.configFile}]}}let a=!!n?.native.pending_root_move;if(n?.native.pending_root_move){let c=n.native.pending_root_move,[l,u]=await Promise.all([qe(r.projectRoot,c.fromArtifactRoot),qe(r.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await Zu([{paths:l,file:Ie.join(l.locksDir,"root-move.lock")},{paths:u,file:Ie.join(u.locksDir,"root-move.lock")}],i))return{healthy:!1,findings:i};let f=await PE({projectRoot:r.projectRoot,strategy:e.recoveryStrategy});r=await qe(r.projectRoot,f.config.native.artifact_root),a=!1,i.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return i.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:i}}else i.push({severity:"error",code:"root-move-incomplete",message:`Native root move ${c.id} is ${c.stage}; inspect ${l.nativeRoot} and ${u.nativeRoot}`,repair:e.recoveryStrategy??"continue"})}let o=await EM(r);if(i.push(...o),o.length>0)return{healthy:!1,findings:i};let s=await PM(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return i.push(...s.findings),e.projectOnly||(i.push(...await AM(r,{name:e.name,repair:t})),i.push(...await TM(r,{name:e.name,repair:t})),i.push(...await _M(r,{name:e.name,repair:t})),i.push(...await xM(r,{name:e.name,repair:t})),i.push(...await IM(r,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),i.push(...await jM(r,{name:e.name,repair:t})),i.push(...await wE({paths:r,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),i.push(...await RM(r,t,s.unfinished)),i.push(...await SM(r,t)),e.projectOnly||i.push(...await CM(r,e.name,n?.native.max_verify_failures??5)),{healthy:i.every(c=>c.severity==="info"),findings:i}}import{randomUUID as $M}from"node:crypto";import{promises as Me}from"node:fs";import ht from"node:path";var Am=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}};function RE(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function CE(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let i=ht.join(e.archiveDir,t);if(!O(e.archiveDir,i))throw new Error("Native Archive path escaped");return i}async function ed(e){try{return await Me.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function xE(e,t){let i=ht.normalize(ht.resolve(e)),r=ht.normalize(ht.resolve(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}async function OM(e,t){let i;try{i=await Me.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let r=[];for(let n of i){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=ht.join(e.archiveDir,n.name);try{let o=await Ze(ht.join(a,"comet-state.yaml"));o.name===t&&r.push({dir:a,state:o})}catch{}}if(r.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return r[0]??null}async function HM(e,t){let i=await bl(e,{kind:"archive",change:t});return i?.kind==="archive"?i.journal:null}async function Sn(e,t){await Me.mkdir(e.transactionsDir,{recursive:!0}),await ee(mr(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function DM(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let i=Jt(e.paths.projectRoot);i.some(a=>xE(a,e.paths.projectRoot))||i.push(e.paths.projectRoot);let r=[];for(let a of i){let o=await ye(a);if(!o)continue;let s=await qe(a,o.native.artifact_root);r.some(c=>xE(c.changesDir,s.changesDir))||r.push(s)}r.length===0&&r.push(e.paths);let n=new Set;for(let a of r){let o;try{o=await Me.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let c=await Ze(ht.join(a.changesDir,s.name,"comet-state.yaml"));c.status!=="done"&&c.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.name)}catch{let c=await Xl(a,s.name).catch(()=>null);c?.state&&c.state.spec_changes.some(({capability:l})=>t.has(l))&&n.add(c.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function LM(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function MM(e){let t=ht.join(e.paths.specsDir,e.change.capability),i=ht.join(t,"spec.md");if(!O(e.paths.specsDir,i))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await Me.lstat(e.paths.specsDir)}catch(c){if(c.code==="ENOENT")return;throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await Me.lstat(t)}catch(c){if(c.code==="ENOENT")return;throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[o,s]=await Promise.all([Me.realpath(e.paths.specsDir),Me.realpath(t)]);if(!O(o,s))throw new Error("Native canonical capability path escaped");try{let c=await Me.lstat(i);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await Me.unlink(i)}catch(c){if(c.code!=="ENOENT")throw c}await Me.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let r=ht.join(Lt(e.paths,e.state.name),e.change.source);await he(r,e.change.content,{containedRoot:e.paths.nativeRoot}),await Me.mkdir(t,{recursive:!0}),await he(i,e.change.content,{containedRoot:e.paths.nativeRoot})}function AE(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function FM(e,t){let i=Lt(e,t.name),r=[];for(let n of t.spec_changes){if(n.source===null){r.push({...n,content:null});continue}let a=await Z({root:i,ref:n.source,maxBytes:null,includeHash:!1});r.push({...n,content:a.text})}return r}function BM(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(AE(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function _m(e){return se(e.paths,`archive portable change ${e.name}`,async()=>{let t=LM(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let i=await HM(e.paths,e.name),r=Lt(e.paths,e.name),n=await ed(r),a=n?null:await OM(e.paths,e.name),o;if(n)o=await $a(e.paths,e.name);else if(i)o=await Ze(ht.join(CE(e.paths,i.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);let s=await Mr(e.paths,e.name);if(n&&!o.archived&&i===null){let d=await VS({paths:e.paths,state:o});if(d.drifted){let f=d.reason??"Native confirmed requirements changed";throw await qS({paths:e.paths,state:o,reason:f}),new Error(`${f}; Native change returned to Shape and requires confirmation`)}}let c=CE(e.paths,i?.archive_ref??RE(o)),l=await ed(c);if(i&&BM(i,o),n&&l)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!i&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await Ts(e.paths,o.name),await Me.rm(We(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!i){if(!o.archived)AE(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let d=await DM({paths:e.paths,state:o});if(!o.archived&&d.length>0&&t!==o.name)throw new Am(d);i={schema:Nl,id:$M(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:RE(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await FM(e.paths,o),created_at:new Date().toISOString()},await Sn(e.paths,i)}if(!n&&l&&i.status==="report-aligned")i={...i,status:"moved"},await Sn(e.paths,i);else if(!n&&l&&i.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${i.status}; doctor intervention is required`);let u=!1;if(i.status==="prepared"&&s&&!o.archived&&(s=(await Ps({paths:e.paths,state:s})).state,u=!0),i.status==="prepared"){for(let d=i.next_spec_index;d<i.spec_changes.length;d+=1)await MM({paths:e.paths,state:o,change:i.spec_changes[d]}),i={...i,next_spec_index:d+1},await Sn(e.paths,i),await e.hooks?.afterSpecApplied?.(d);i={...i,status:"specs-applied"},await Sn(e.paths,i)}if(i.status==="specs-applied"){if(s&&!o.archived&&!u&&(s=(await Ps({paths:e.paths,state:s})).state,u=!0),!o.archived){let d={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await nn({file:Pt(e.paths,o.name),expectedStateVersion:o.state_version,next:d,containedRoot:e.paths.nativeRoot})}i={...i,status:"state-finalized"},await Sn(e.paths,i),await e.hooks?.afterFinalState?.()}if(i.status==="state-finalized"){let d=await ed(r)?r:c;if(await Du({file:ht.join(d,"verification.md"),state:o,...s?{supervisor:s}:{}}),await Hu({file:ht.join(d,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");i={...i,status:"report-aligned"},await Sn(e.paths,i),s&&!u&&(await Ps({paths:e.paths,state:s}),u=!0),await e.hooks?.afterReportAligned?.()}if(i.status==="report-aligned"){if(s&&!u&&await Ps({paths:e.paths,state:s}),await Me.mkdir(e.paths.archiveDir,{recursive:!0}),await ed(c))throw new Error(`Native Archive target already exists: ${c}`);await Me.rename(r,c),i={...i,status:"moved"},await Sn(e.paths,i),await e.hooks?.afterMove?.()}return i.status==="moved"&&(await Ts(e.paths,o.name),await Me.rm(We(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await Me.rm(mr(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:c,transactionId:i.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}function En(e,t,i){return e.language==="zh-CN"?i:t}function VM(e,t){let i=r=>({required:!1,message:null,suggestedReply:null,agentInstruction:r});if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:En(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:En(e,"Reply A or B","回复 A 或 B"),agentInstruction:En(e,"Relay the two coordination choices and wait for the user decision. Do not treat a generic confirmation as a mode selection or run --confirmed without --coordination-mode.","转述这两个推进方式并等待用户选择。不要把普通“确认”视为已选择推进方式,也不要在没有 --coordination-mode 时运行 --confirmed。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready")return i(En(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return i(En(e,"Wait only while the dispatched Verifier task is still active. If it did not start, ended without a response, or is no longer available, immediately submit the matching verifier-unavailable or verifier-execution-error input. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、结束后没有返回结果或已经丢失,立即提交匹配的 verifier-unavailable 或 verifier-execution-error 输入。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:r})=>r==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"由于独立验收服务暂时不可用,目前只能完成自动检查。你可以选择接受当前检查结果,或者等验收服务恢复后再重试。",suggestedReply:null,agentInstruction:"向用户转述 message,并请用户明确选择是否接受只有自动检查的结果。不要把“继续”当作默认接受。"}:{required:!0,message:"Because independent verification is temporarily unavailable, only the automatic checks could be completed. You can accept the current check results or wait and retry when verification is available.",suggestedReply:null,agentInstruction:"Relay message and ask the user to explicitly choose whether to accept automatic checks only. Do not treat “Continue” as implicit acceptance."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return i(En(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function Im(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function td(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function _E(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function qM(e,t,i){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...i]}}function WM(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function zM(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--confirmed","--expected-state-version",String(e.stateVersion),"--expected-action","confirm-shape"]}function Fs(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Im({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[td("summary","--summary"),_E(e.name,e.flag)]}}function Tm(e){return[Fs({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Fs({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function id(e,t){let i=WM(t)&&e.coordination_mode===void 0,r={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],userCommunication:VM(e,i)},n=a=>({kind:a,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...r,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:n("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...r,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[td("summary","--summary")],commandAlternatives:[Fs({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Tm({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...r,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:Im({change:e.name,stateVersion:e.state_version,action:"confirm-verifier-unavailable",flag:"--confirmed"}),requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...r,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[td("summary","--summary")],commandAlternatives:[Fs({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Tm({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...r,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[td("summary","--summary")],commandAlternatives:Tm({change:e.name,stateVersion:e.state_version}),runnerAction:n("none")}:{...r,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:n("none")};if(e.status==="blocked"){let a=e.blockers.some(({resolution_action:o})=>o==="retry-verifier");return{...r,disposition:"blocked",action:a?"retry-verifier":"none",commandArgs:a?Im({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:a?["summary"]:["repair-runtime"],inputOptions:a?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:n(a?"retry-verifier":"none")}}if(e.phase==="shape")return{...r,disposition:i?"await-user":"continue",action:"confirm-shape",commandArgs:zM({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[],"shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[qM("coordination-mode","--coordination-mode",Hy)]:[],_E("confirmed","--confirmed")],runnerAction:n("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...r,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:n("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...r,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:n("none")};if(t.allDone)return{...r,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")};let a=t.children.some(({status:s})=>s==="blocked"||s==="needs-reverify"),o=t.children.some(({status:s})=>s==="ready"||s==="active");return{...r,disposition:a&&!o?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:a&&!o?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:n("none")}}return{...r,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")}}if(e.phase==="verify"){let a=e.loop.next_action==="await-verifier-result",o=!!e.children_contract_hash,s={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...r,userCommunication:!a&&o?{...r.userCommunication,agentInstruction:`${r.userCommunication.agentInstruction} ${En(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:r.userCommunication,disposition:"continue",action:a?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[a?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:a?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[s]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:o?[s]:[]}}],runnerAction:n(a?"await-verifier":"dispatch-verifier")}}return e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived?{...r,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],commandAlternatives:[Fs({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:n("none")}:{...r,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:n("none")}}import{randomUUID as JM}from"node:crypto";import{promises as Va}from"node:fs";import DE from"node:path";var jm=["evidence.md","repair.md","archive.md","checkpoint.md"],GM="verification.md";async function UM(e){try{return await Va.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function $m(e,t){let i=ne(e,t),r=[mr(e,{kind:"migration",change:t}),tn(e,t),...jm.map(n=>DE.join(i,n))];return(await Promise.all(r.map(UM))).some(Boolean)}async function KM(e,t){let i=await bl(e,{kind:"migration",change:t});return i?.kind==="migration"?i.journal:null}async function TE(e,t){await Va.mkdir(e.transactionsDir,{recursive:!0}),await ee(mr(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function IE(e,t,i={}){let r=i.removeVerificationReport===!1?jm:[...jm,GM];await Promise.all([Va.rm(We(e,t),{recursive:!0,force:!0}),Va.rm(tn(e,t),{recursive:!0,force:!0}),...r.map(n=>Va.rm(DE.join(ne(e,t),n),{force:!0}))])}async function jE(e,t){await Fr(Nn(e,t.name),yn({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function $E(e,t){try{let i=await kt(e,t);if(i?.schema==="comet.native.workspace.v3")return{isolation:i.isolation,change_branch:i.changeBranch,target_branch:i.targetBranch,finish:i.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function OE(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let i=fe(e.projectRoot);if(!i.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(i.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${i.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!i.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function YM(e){let t=ne(e.paths,e.state.name),i=await Z({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),r=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await Z({root:t,ref:n.source,maxBytes:null,includeHash:!1});r.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return hl({briefMarkdown:i.text,specs:r})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function HE(e,t){let i=await Xl(e,t);if(!i.state)throw new Error(`Native legacy change ${t} is unreadable`);return i.state}async function Bs(e){return se(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await KM(e.paths,e.name),i=await qr(e.paths,e.name)?await Ze(Pt(e.paths,e.name)):null;if(!t&&i)return await IE(e.paths,e.name,{removeVerificationReport:!1}),await jE(e.paths,i),i;let r=null,n=null;for(t||(r=await HE(e.paths,e.name),n=await $E(e.paths,e.name),OE(e.paths,n),t={schema:yl,id:JM(),change:r.name,fromSchema:r.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await TE(e.paths,t));;){let a=My(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?i||(r??=await HE(e.paths,e.name),n??=await $E(e.paths,e.name),OE(e.paths,n),i=Ly({state:r,acceptance:await YM({paths:e.paths,state:r}),workspace:n,migratedAt:e.now}),await wl(Pt(e.paths,e.name),i,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await IE(e.paths,e.name):a.action==="commit-transaction"&&(i??=await Ze(Pt(e.paths,e.name)),await jE(e.paths,i)),t={...t,status:a.nextStatus},await TE(e.paths,t)}return await Va.rm(mr(e.paths,{kind:"migration",change:e.name}),{force:!0}),i??Ze(Pt(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as LE}from"node:fs";import ME from"node:path";function XM(e,t){let i=fe(e.projectRoot);if(t.workspace.change_branch!==null){if(!i.isGitWorktree)return"The portable change requires a Git branch/worktree";if(i.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:i.isGitWorktree?t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function QM(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function ZM(e,t,i){let r=new Date().toISOString(),n=e.verification===null?e:Yn(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:hr(t),completed_at:r});return ct({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:i?QM(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function eF(e){try{let t=await Ou(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function FE(e){return se(e.paths,`recover portable change ${e.name}`,async()=>{let t=await $a(e.paths,e.name);if(t.status==="done")return await Lu({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let i=XM(e.paths,t);if(i)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:i};let r=Nn(e.paths,e.name),n=await eF(r),a=n.reason==="available"&&(n.local?.change!==t.name||n.local?.basedOnStateVersion!==t.state_version)?"stale":n.reason;if(a==="available"&&!e.preserveRunningExecution&&n.local?.execution!==null&&n.local?.execution?.status!=="completed"&&n.local&&(a="interrupted",n.local.execution?.status==="running"&&(n.local={...n.local,execution:{...n.local.execution,status:"interrupted"},checks:n.local.checks.map(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)},await Fr(r,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await Lu({paths:e.paths,state:t}),{state:t,local:n.local,action:"resume-stable-boundary",reason:a,message:"Native local execution overlay matches the portable state."};let s=a==="interrupted"?n.local?.checks.find(f=>f.status==="interrupted"&&!f.repeatable):void 0;if(s){let f=um({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await nn({file:Pt(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot}),await LE.rm(ME.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let h=yn({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await Fr(r,h,{containedRoot:e.paths.runtimeDir}),{state:t,local:h,action:"resume-stable-boundary",reason:a,message:`Native check ${s.id} was not repeatable; the change returned to Build for a new candidate.`}}let c=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",l=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",u=c||l;if(u){let f=ZM(t,l?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",l);t=await nn({file:Pt(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot})}let d=yn({portableState:t,projectRoot:e.paths.projectRoot,branch:fe(e.paths.projectRoot).currentBranch});return await LE.mkdir(ME.dirname(Nn(e.paths,t.name)),{recursive:!0}),await Fr(r,d,{containedRoot:e.paths.runtimeDir}),await Lu({paths:e.paths,state:t}),{state:t,local:d,action:u?"reverify":"resume-stable-boundary",reason:a,message:u?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}import{promises as VE}from"node:fs";import iF from"node:path";function tF(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function BE(e){let t=e.acceptance.reduce((i,r)=>({...i,[r.result]:i[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:t,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:tF(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},archived:e.archived}}function rF(e,t,i){return`native-details-v2.${e}.${t}.${i.toString(36)}`}function nF(e,t,i){if(!e)return 0;let r=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!r||Number(r[1])!==t||Number(r[2])!==i)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(r[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function aF(e,t,i){return[...e.acceptance.map(r=>({kind:"acceptance",value:r})),...e.spec_changes.map(r=>({kind:"spec-change",value:r})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(r=>({kind:"history",value:r})),{kind:"history-overflow",value:e.history_overflow},{kind:"workspace",value:e.workspace},...e.verification_report?[{kind:"verification-report",value:e.verification_report}]:[],...t?[{kind:"supervisor-integration",value:{...t.integration,worktree:"<worktree>",targetCommit:"<redacted>",headCommit:"<redacted>"}},{kind:"supervisor-final-verification",value:t.finalVerification},...t.children.map(r=>({kind:"supervisor-child",value:cF(r,i)})),...t.history.map(r=>({kind:"supervisor-history",value:lF(r,i)}))]:[]]}function oF(e){return e.acceptance.reduce((t,i)=>({...t,[i.result]:t[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function qE(e,t){let i=fe(e.projectRoot),r=null;return t.workspace.change_branch!==null&&(i.isGitWorktree?i.currentBranch!==t.workspace.change_branch&&(r=`Expected branch ${t.workspace.change_branch}, current branch is ${i.currentBranch??"(detached)"}.`):r="The Native change requires a registered Git worktree."),r===null&&t.workspace.isolation==="worktree"&&!i.isSecondaryWorktree&&(r="The Native change requires its linked worktree."),{projectRoot:iF.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:r===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:r}}function sF(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(i=>[i.projectRoot,i.task?.projectRoot])].filter(i=>!!i).map(i=>i.replaceAll("/","\\")).sort((i,r)=>r.length-i.length)}function rd(e,t){return e===null?null:t.reduce((i,r)=>i.replaceAll(r,"<worktree>").replaceAll(r.replaceAll("\\","/"),"<worktree>"),e)}function cF(e,t){return{...e,projectRoot:e.projectRoot?"<worktree>":null,baseCommit:e.baseCommit?"<redacted>":null,candidateCommit:e.candidateCommit?"<redacted>":null,verifiedCommit:e.verifiedCommit?"<redacted>":null,integrationCommit:e.integrationCommit?"<redacted>":null,blocker:rd(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function lF(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:rd(e.summary,t)??""}}async function qa(e){let t=await WS(e),i=BE(t.state),r=t.state.status==="active"&&t.state.loop.stage!=="done",n=await Cs({paths:e.paths,state:t.state}),a=await Mr(e.paths,e.name),o=a?{...qE(e.paths,t.state),projectRoot:"."}:qE(e.paths,t.state),s=id(t.state,n),c=o.bindingState==="mismatch"?{...s,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...s.runnerAction,kind:"none"}}:s,l=a?sF(e.paths,a):[],u=a?(()=>{let h=a.children.filter(({status:y})=>y==="pending"||y==="ready").length,v=a.children.filter(({status:y})=>y==="active"||y==="verified").length,m=a.children.filter(({status:y})=>y==="integrated"||y==="archived").length,p=a.children.filter(({status:y})=>y==="blocked"||y==="needs-reverify").length,b=a.children.filter(({status:y})=>y==="active"||y==="blocked"||y==="needs-reverify").slice(0,16).map(y=>({name:y.name,summary:y.summary,projectRoot:y.task?.projectRoot??y.projectRoot?"<worktree>":null,reason:rd(y.blocker,l)})),g=a.children.flatMap(({blocker:y})=>{let E=rd(y,l);return E?[E]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:a.children.length,waiting:h,working:v,integrated:m,blocked:p,active:b,agents:{working:a.children.filter(({task:y})=>y!==null).length,completed:m},risks:g,nextAction:a.finalVerification.status==="passed"?"final-delivery":a.finalVerification.status==="pending"&&m===a.children.length?"parent-verification":h>0?"dispatch-ready-child":p>0?"resolve-blocker":"continue-supervisor"}})():null,d=e.details?(()=>{let h=a?.stateVersion??0,v=aF(t.state,a,l),m=nF(e.cursor,t.state.state_version,h),p=v.slice(m,m+32),b=m+p.length<v.length?rF(t.state.state_version,h,m+p.length):null;return{items:p,nextCursor:b,supervisorStateVersion:h}})():null,f=a?{schema:a.schema,parent:a.parent,integration:{branch:a.integration.branch,targetBranch:a.integration.targetBranch},finalVerification:{status:a.finalVerification.status,summary:a.finalVerification.summary},summary:u}:null;return{schema:"comet.native.status.v2",name:t.state.name,phase:t.state.phase,status:t.state.status,stateVersion:t.state.state_version,...t.state.coordination_mode===void 0?{}:{coordinationMode:t.state.coordination_mode},loop:t.state.loop,acceptance:oF(t.state),unresolvedAcceptanceIds:i.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:a?[]:i.blockers,workspace:o,localExecution:{status:r?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{childSummary:n.children.reduce((h,v)=>({...h,[v.status]:(h[v.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...f?{supervisor:f}:{},continuation:c,...e.details?{details:{stateVersion:t.state.state_version,...a?{supervisorStateVersion:d.supervisorStateVersion}:{},items:d.items,nextCursor:d.nextCursor,nextPageArgs:d.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",d.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}async function WE(e){let t;try{t=await VE.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}let i=[];for(let r of t)if(!(!r.isDirectory()||r.isSymbolicLink()))try{let n=await VE.readFile(`${Lt(e,r.name)}/comet-state.yaml`,"utf8");/^schema:\s*comet\.native\.v4\s*$/mu.test(n)&&i.push(r.name)}catch(n){if(n.code!=="ENOENT")throw n}return i.sort((r,n)=>r.localeCompare(n,"en"))}import Vs from"path";import{realpathSync as EF}from"fs";var Wi={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function zE(e){return e?e.command?`${Wi.next} ${e.command}`:e.ask_user?`${Wi.next} ${e.ask_user}`:null:null}function JE(e,t){let i=[e.summary],r=zE(e.next);return r&&i.push(r),e.user_message&&i.push("",Wi.relay,e.user_message),t!==void 0&&i.push("",Wi.details,JSON.stringify(t,null,2)),`${i.join(`
|
|
269
|
+
`)}
|
|
270
|
+
`}function GE(e,t,i){let r=[e.summary],n=zE(e.next);return n&&r.push(n),e.user_message&&r.push("",Wi.relay,e.user_message),r.push("",`${Wi.detail} ${t}`),i!==void 0&&r.push("",Wi.details,JSON.stringify(i,null,2)),r.join(`
|
|
271
|
+
`)}function J(e,t,i){return e==="zh-CN"?i:t}var Om={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function UE(e,t){return typeof e=="string"&&Om[e]?J(t,Om[e].en,Om[e].zh):typeof e=="string"?e:""}function Hm(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&typeof t.passed=="number"&&typeof t.failed=="number"&&typeof t.blocked=="number"&&typeof t.pending=="number"}function uF(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let i of e){if(!i||typeof i!="object")return null;let r=i.result;if(r!=="passed"&&r!=="failed"&&r!=="blocked"&&r!=="pending")return null;t[r]+=1}return t}function KE(e,t){let i=[];e.failed>0&&i.push(J(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&i.push(J(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&i.push(J(t,`${e.pending} pending`,`${e.pending} 项待验`));let r=J(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return i.length>0?`${r} (${i.join(", ")})`:r}function YE(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let i=t.userCommunication;return!!(i&&typeof i=="object"&&typeof i.required=="boolean"&&(i.message===null||typeof i.message=="string")&&typeof i.agentInstruction=="string")}function Dm(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function dF(e,t,i){return e==="done"?J(i,"complete","已完成"):e==="await-user"?J(i,"waiting for a user decision","等待用户决定"):e==="blocked"?J(i,"paused: needs attention","已暂停,需要处理"):t?J(i,"waiting for a user decision","等待用户决定"):J(i,"ready to continue","可继续推进")}function fF(e,t,i){let r=Dm(e),n=[];i&&n.push(i);let a=J(r,`Change ${e.change}`,`需求 ${e.change}`),o=UE(e.phase,r),s=dF(e.disposition,e.userCommunication.required,r);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(KE(t,r));let c=e.userCommunication,l=XE(e,r);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function XE(e,t){let i=e.userCommunication;if(e.disposition==="await-user"&&i.required)return{ask_user:J(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:J(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:J(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function hF(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function pF(e,t){let i=typeof e.name=="string"?e.name:"(unnamed)",r=UE(e.phase,t),n=e.status==="await-user"?J(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?J(t,"paused","已暂停"):e.status==="done"?J(t,"complete","已完成"):J(t,"in progress","进行中"),a=Hm(e.acceptance)?`${J(t,", ",",")}${KE(e.acceptance,t)}`:"";return` ${i} · ${r||String(e.phase??"?")} · ${n}${a}`}function mF(e){for(let t of e){let i=t.continuation;if(i?.userCommunication&&typeof i.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(i.userCommunication.agentInstruction))return"zh-CN"}return"en"}function vF(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.healthy!="boolean"?!1:t.findings===void 0||Array.isArray(t.findings)}function gF(e){if(e.healthy){let r=e.repaired?J("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):J("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=wF(e.continuation);return n?{summary:r,next:n}:{summary:r}}let i=Array.isArray(e.findings)?e.findings.length:0;return{summary:J("en",i>0?`Diagnostics found ${i} problem${i===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",i>0?`诊断发现 ${i} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:J("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function wF(e){return YE(e)?XE(e,Dm(e)):void 0}function QE(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(vF(t))return gF(t);if(hF(t)){let r=mF(t.items);return{summary:[t.total===t.items.length?J(r,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):J(r,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>pF(a,r))].join(`
|
|
272
|
+
`)}}let i=t.continuation;if(YE(i))return fF(i,yF(t),NF(t,Dm(i)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let r=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:J(r,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function yF(e){if(Hm(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t;if(Hm(i.acceptance))return i.acceptance;if(Array.isArray(i.acceptance))return uF(i.acceptance)}return null}function NF(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return J(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let i=e.migration;return i&&typeof i=="object"&&i.completed===!0?J(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function ZE(e){let i=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:J("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof i.change=="string"?{next:{command:`comet native status ${i.change} --json`}}:{}};case"baseline-incomplete":return{summary:J("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:J("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:J("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:J("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:J("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:J("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:J("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:J("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}var eP=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--verbose Append the raw machine projection after the human/agent text.","--help Show help without requiring an initialized project."],Mm=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","check <change-name> Run the read-only Native verification check.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:eP,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page, or a named details/history page.","--details Include one fixed-size page of acceptance, Spec, handoff, verification, history, workspace, and report details."],output:"A compact v2 status page or one compact Loop projection with local execution availability. Use --details and --cursor to read fixed-size detail pages; parent changes expose childSummary and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--confirmed] [--coordination-mode multi-session|single-session] [--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
|
|
269
273
|
comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm Shape or an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Required when confirming a multi-child Supervisor Shape.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a blocked Verifier execution when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--max-parallel <n> Supervisor task concurrency cap; defaults to 2, use 1 for serial fallback.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits, review. review fields: status=passed, summary, reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."," Supervisor task fields: supervisor-builder-result (child, runId, candidateCommit), supervisor-builder-failure (child, runId, reason), supervisor-verifier-result (child, runId, verdict, verification data), supervisor-reconnect (child, runId), supervisor-cancel (child, runId, reason), or supervisor-integrate (child, checks)."],output:'A compact portable state summary, explicit skill-coordinated label, Runtime-owned check results, scoped verifierDispatch, bounded request-check response, continuation.runnerAction, machine-readable continuation.inputOptions, and continuation.userCommunication with a user-ready message and Agent relay guidance. Read acceptance text and other long fields from paged status --details output. Human-readable verification statuses include "Host independently verified", "Checks completed, but your confirmation is required", "Full verification was unavailable; only automatic checks completed", and "You accepted the incomplete verification result". This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.',examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
|
|
270
|
-
comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness plus continuation, or the completed Archive transaction and workspace finish result; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function
|
|
274
|
+
comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness plus continuation, or the completed Archive transaction and workspace finish result; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function Lm(e,t){return`${e}:
|
|
271
275
|
${t.map(i=>` ${i}`).join(`
|
|
272
|
-
`)}`}function
|
|
273
|
-
${i.output}`),i.examples&&r.push("",
|
|
276
|
+
`)}`}function bF(e){let t=e.filter(r=>r!=="--help");if(t.length===0)return"";let i=t.slice(0,2).join(" ");return Mm[i]||t.length>1&&Mm[t[0]]?.subcommands?i:t[0]}function kF(e=[]){let t=bF(e),i=Mm[t];if(!i)throw new Error(`Unknown Native help topic: ${t}`);let r=[`Usage: ${i.usage}`,"",i.purpose];i.subcommands&&r.push("",Lm("Commands",i.subcommands));let n=t===""?i.options:[...i.options??[],...eP];return n&&n.length>0&&r.push("",Lm("Options",n)),r.push("",`Output:
|
|
277
|
+
${i.output}`),i.examples&&r.push("",Lm("Examples",i.examples)),t===""&&r.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${r.join(`
|
|
274
278
|
`)}
|
|
275
|
-
`}}var
|
|
276
|
-
`}}function
|
|
277
|
-
`}:e.error?{exitCode:e.exitCode,stderr:
|
|
278
|
-
|
|
279
|
+
`}}var SF=kF().usage;var F8=10*1024*1024,Bt=class extends Error{};function qs(e,t){let i=e.flatMap((r,n)=>r===t?[n]:[]);if(i.length>1)throw new Bt(`${t} may only be provided once`);return i.length===0?!1:(e.splice(i[0],1),!0)}function nd(e,t){let i=e.flatMap((a,o)=>a===t?[o]:[]);if(i.length>1)throw new Bt(`${t} may only be provided once`);if(i.length===0)return;let r=i[0],n=e[r+1];if(n===void 0||n.startsWith("--"))throw new Bt(`${t} requires a value`);return e.splice(r,2),n}function iP(e){if(e.length>0)throw new Bt(`Unexpected argument: ${e[0]}`)}function Fm(e,t){let i=Vs.normalize(tP(e)),r=Vs.normalize(tP(t));return process.platform==="win32"?i.toLowerCase()===r.toLowerCase():i===r}function tP(e){let t=Vs.resolve(e);try{return EF.native(t)}catch{return t}}function PF(e){let t=Vs.resolve(e),i=fe(process.cwd());if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return t;let r=fe(t);return!r.isGitWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null||!Fm(i.primaryWorktreeRoot,r.primaryWorktreeRoot)||Fm(i.currentWorktreeRoot,r.currentWorktreeRoot)?t:Fm(process.cwd(),i.currentWorktreeRoot)?Vs.resolve(process.cwd()):i.currentWorktreeRoot}async function rP(e){return e?PF(e):ch(process.cwd())}async function nP(e){let t=await ye(e);return qe(e,t?.native.artifact_root??"docs")}function aP(e){return JSON.stringify(e,null,2)+`
|
|
280
|
+
`}function zi(e,t,i){return{command:e,exitCode:0,data:t,text:i??aP(t)}}function RF(e,t){if(t instanceof Bt)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Fu)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof Is)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof es)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof ts)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof Cu)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof ha)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof Hr)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof bs)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let i=t.code;if(i&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(i))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let r=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:r?73:65,error:{code:r?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function oP(e,t){let i=RF(e,t),r=i.error;if(!r)return i;let n=ZE({code:r.code,message:r.message,data:i.data});return n?{...i,envelope:n}:i}function sP(e,t,i=!1){let r=e.envelope??QE(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...r===void 0?{}:{summary:r.summary,...r.next===void 0?{}:{next:r.next},...r.user_message===void 0?{}:{user_message:r.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
|
|
281
|
+
`}:e.error?{exitCode:e.exitCode,stderr:r?GE(r,e.error.message,i?e.data:void 0):e.error.message}:r?{exitCode:e.exitCode,stdout:JE(r,i?e.data:void 0)}:i&&e.text!==void 0&&e.data!==void 0&&e.text!==aP(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
282
|
+
${Wi.details}
|
|
283
|
+
${JSON.stringify(e.data,null,2)}
|
|
284
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}async function Ws(e,t){let i=await Cs({paths:e,state:t});return id(t,i)}async function CF(e){let t;try{t=await uP.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return t.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort((i,r)=>i.localeCompare(r,"en"))}function xF(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function cP(e,t){let i;try{i=await uP.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return null;throw a}let r=new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${xF(t)}$`,"u"),n=i.find(a=>a.isDirectory()&&!a.isSymbolicLink()&&r.test(a.name));return n?{severity:"error",code:"portable-active-archive-conflict",message:`Native change ${t} exists in both active and Archive storage`,path:od.join(e.archiveDir,n.name)}:null}function AF(e){let t=new Map;for(let i of e){let r=[i.severity,i.code,i.message,i.path??""].join("\0");t.set(r,i)}return[...t.values()]}function ad(e){return{command:"doctor",exitCode:65,data:e,error:{code:"invalid-data",message:"Native project needs attention"}}}function lP(e,t){return{severity:"error",code:"portable-migration-incomplete",message:`Native portable migration is incomplete for ${t}`,path:od.join(e.changesDir,t,"comet-state.yaml"),repair:"migrate"}}async function _F(e,t){let i=[],r=[];for(let n of await Wy(e)){let a=sn(n);if(t&&a.change!==t)continue;let o=od.join(e.transactionsDir,n);try{let s=await Mo(e,n);if(!s)continue;i.push(s),r.push(s.kind==="archive"?{severity:"error",code:"portable-archive-transaction-incomplete",message:`Native portable Archive transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"continue"}:{severity:"error",code:"portable-migration-incomplete",message:s.journal.status==="committed"?`Native portable migration cleanup is incomplete for ${s.change}`:`Native portable migration transaction ${s.journal.id} is incomplete for ${s.change}`,path:s.file,repair:"migrate"})}catch(s){r.push({severity:"error",code:"portable-transaction-invalid",message:`Native portable transaction ${n} is invalid: ${s.message}`,path:o})}}return{transactions:i,findings:r}}async function Bm(e,t){let i=qs(e,"--repair"),r=nd(e,"--strategy");if(r!==void 0&&r!=="continue"&&r!=="rollback")throw new Bt("--strategy must be continue or rollback");let n=e[0]?.startsWith("--")?void 0:e.shift();iP(e);let a=await nP(t),o=await _F(a,n);if(n&&o.findings.length>0){if(r)throw new Bt("--strategy is only available to the legacy transaction doctor");let d=await qr(a,n)?await qa({paths:a,name:n,details:!0}):void 0;if(i&&o.transactions.length===1&&o.findings.length===1){if(o.transactions[0].kind==="archive"){let v=await _m({paths:a,name:n});return zi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,archive:{recovered:!0,transactionId:v.transactionId},state:v.state,continuation:await Ws(a,v.state)})}let h=await Bs({paths:a,name:n});return zi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:h.schema,stateVersion:h.state_version},state:h,continuation:await Ws(a,h)})}return ad({healthy:!1,workflow:"native-portable",change:n,repaired:!1,...d?{result:d,continuation:d.continuation}:{},findings:o.findings})}if(n&&await qr(a,n)){if(r)throw new Bt("--strategy is only available to the legacy transaction doctor");let[u,d]=await Promise.all([cP(a,n),$m(a,n)]);if(u){let h=await qa({paths:a,name:n,details:!0});return ad({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:h,findings:[u],continuation:h.continuation})}if(d&&!i){let h=await qa({paths:a,name:n,details:!0});return ad({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:h,findings:[lP(a,n)],continuation:h.continuation})}if(i){if(d){let v=await Bs({paths:a,name:n});return zi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:v.schema,stateVersion:v.state_version},state:v,continuation:await Ws(a,v)})}let h=await FE({paths:a,name:n});return zi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,result:h,continuation:await Ws(a,h.state)})}let f=await qa({paths:a,name:n,details:!0});return zi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!1,result:f,continuation:f.continuation})}if(n){if(i){let u=await Bs({paths:a,name:n});return zi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{from:"legacy",to:u.schema,stateVersion:u.state_version},state:u,continuation:await Ws(a,u)})}return{command:"doctor",exitCode:65,data:{healthy:!1,change:n,migrationRequired:!0,repairCommand:`comet native doctor ${n} --repair`},error:{code:"invalid-data",message:`Native active change ${n} requires migration to portable Runtime`}}}let s=await WE(a),c=o;if(s.length>0||c.findings.length>0){if(r)throw new Bt("--strategy is only available to the legacy transaction doctor");if(i){let k=await Ms({paths:a,repair:!0,projectOnly:!0}),S=[];for(let w of c.transactions)w.kind==="archive"?await _m({paths:a,name:w.change}):await Bs({paths:a,name:w.change}),S.push({kind:w.kind,change:w.change,transactionId:w.journal.id});let R=await Bm([],t),N=R.data&&typeof R.data=="object"&&!Array.isArray(R.data)?R.data:{};return{...R,data:{...N,repaired:!0,repairedPortableTransactions:S,repairFindings:k.findings}}}let u=await CF(a),d=new Set(s),f=new Set(c.transactions.filter(k=>k.kind==="migration").map(({change:k})=>k)),h=u.filter(k=>!d.has(k)),[v,m,p,b,g]=await Promise.all([Promise.all(s.map(k=>qa({paths:a,name:k}))),Promise.all(s.map(k=>cP(a,k))),Promise.all(s.map(k=>$m(a,k))),Promise.all(h.map(k=>Ms({paths:a,name:k}))),Ms({paths:a,projectOnly:!0})]),y=AF([...m.filter(k=>k!==null),...s.flatMap((k,S)=>p[S]&&!f.has(k)?[lP(a,k)]:[]),...c.findings,...h.map(k=>({severity:"error",code:"portable-migration-required",message:`Native active change ${k} requires migration to portable Runtime`,path:od.join(a.changesDir,k,"comet-state.yaml"),repair:"migrate"})),...b.flatMap(({findings:k})=>k),...g.findings]),E={healthy:y.every(k=>k.severity==="info"),workflow:h.length>0?"native-mixed":"native-portable",changes:v,legacyChanges:h,findings:y};return E.healthy?zi("doctor",E):ad(E)}let l=await Ms({paths:a,...n?{name:n}:{},repair:i,...r?{recoveryStrategy:r}:{}});return l.healthy?zi("doctor",l):{command:"doctor",exitCode:65,data:l,error:{code:"invalid-data",message:"Native project needs attention"}}}async function dP(e,t,i=process.argv.slice(2)){let r=i.indexOf("--"),n=r<0?[...i]:i.slice(0,r),a=r<0?[]:i.slice(r),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{qs(n,"--json"),qs(n,"--verbose"),c=nd(n,"--project-root");let d=[...n,...a],f=await rP(c);l=await t(d,f)}catch(d){l=oP(e,d)}let u=sP(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
|
|
279
285
|
`)?"":`
|
|
280
|
-
`)),
|
|
286
|
+
`)),u.exitCode}process.exitCode=await dP("doctor",Bm);
|