@rpamis/comet 0.4.0-rc.6 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +332 -333
- package/assets/manifest.json +1 -1
- package/assets/skills/comet/scripts/comet-archive.mjs +56 -51
- package/assets/skills/comet/scripts/comet-entry-runtime.mjs +22 -20
- package/assets/skills/comet/scripts/comet-guard.mjs +93 -88
- package/assets/skills/comet/scripts/comet-handoff.mjs +111 -106
- package/assets/skills/comet/scripts/comet-hook-guard.mjs +54 -49
- package/assets/skills/comet/scripts/comet-hook-router.mjs +106 -106
- package/assets/skills/comet/scripts/comet-intent.mjs +12 -7
- package/assets/skills/comet/scripts/comet-resume-probe.mjs +50 -45
- package/assets/skills/comet/scripts/comet-runtime.mjs +180 -175
- package/assets/skills/comet/scripts/comet-state.mjs +80 -75
- package/assets/skills/comet/scripts/comet-yaml-validate.mjs +57 -52
- package/assets/skills/comet-classic/reference/scripts.md +1 -1
- package/assets/skills/comet-native/SKILL.md +3 -3
- package/assets/skills/comet-native/scripts/comet-native-archive.mjs +31 -31
- package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +51 -51
- package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +3 -3
- package/assets/skills/comet-native/scripts/comet-native-init.mjs +37 -37
- package/assets/skills/comet-native/scripts/comet-native-new.mjs +33 -33
- package/assets/skills/comet-native/scripts/comet-native-next.mjs +43 -43
- package/assets/skills/comet-native/scripts/comet-native-root.mjs +3 -3
- package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +71 -71
- package/assets/skills/comet-native/scripts/comet-native-select.mjs +36 -36
- package/assets/skills/comet-native/scripts/comet-native-show.mjs +27 -27
- package/assets/skills/comet-native/scripts/comet-native-spec.mjs +23 -23
- package/assets/skills/comet-native/scripts/comet-native-status.mjs +39 -39
- package/assets/skills-zh/comet-classic/reference/scripts.md +1 -1
- package/assets/skills-zh/comet-native/SKILL.md +3 -3
- package/bin/fast-runtime-router.js +1 -1
- package/dist/app/cli/index.js +7 -1
- package/dist/app/cli/index.js.map +1 -1
- package/dist/app/commands/classic.js +4 -0
- package/dist/app/commands/classic.js.map +1 -1
- package/dist/app/commands/doctor.d.ts +1 -1
- package/dist/app/commands/doctor.d.ts.map +1 -1
- package/dist/app/commands/doctor.js +2 -1
- package/dist/app/commands/doctor.js.map +1 -1
- package/dist/app/commands/eval.js +2 -2
- package/dist/app/commands/eval.js.map +1 -1
- package/dist/app/commands/init.d.ts.map +1 -1
- package/dist/app/commands/init.js +16 -5
- package/dist/app/commands/init.js.map +1 -1
- package/dist/app/commands/personal-memory.d.ts.map +1 -1
- package/dist/app/commands/personal-memory.js +5 -0
- package/dist/app/commands/personal-memory.js.map +1 -1
- package/dist/app/commands/project-knowledge.d.ts.map +1 -1
- package/dist/app/commands/project-knowledge.js +26 -2
- package/dist/app/commands/project-knowledge.js.map +1 -1
- package/dist/app/commands/status.d.ts.map +1 -1
- package/dist/app/commands/status.js +17 -10
- package/dist/app/commands/status.js.map +1 -1
- package/dist/app/commands/uninstall.d.ts.map +1 -1
- package/dist/app/commands/uninstall.js +5 -1
- package/dist/app/commands/uninstall.js.map +1 -1
- package/dist/app/commands/update.d.ts.map +1 -1
- package/dist/app/commands/update.js +10 -4
- package/dist/app/commands/update.js.map +1 -1
- package/dist/domains/agent-learning/context-director.d.ts.map +1 -1
- package/dist/domains/agent-learning/context-director.js +14 -10
- package/dist/domains/agent-learning/context-director.js.map +1 -1
- package/dist/domains/comet-classic/classic-archive.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-archive.js +3 -0
- package/dist/domains/comet-classic/classic-archive.js.map +1 -1
- package/dist/domains/comet-classic/classic-cli-help.d.ts +3 -0
- package/dist/domains/comet-classic/classic-cli-help.d.ts.map +1 -0
- package/dist/domains/comet-classic/classic-cli-help.js +40 -0
- package/dist/domains/comet-classic/classic-cli-help.js.map +1 -0
- package/dist/domains/comet-classic/classic-cli.d.ts +1 -0
- package/dist/domains/comet-classic/classic-cli.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-cli.js +5 -0
- package/dist/domains/comet-classic/classic-cli.js.map +1 -1
- package/dist/domains/comet-classic/classic-guard.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-guard.js +12 -2
- package/dist/domains/comet-classic/classic-guard.js.map +1 -1
- package/dist/domains/comet-classic/classic-handoff.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-handoff.js +11 -10
- package/dist/domains/comet-classic/classic-handoff.js.map +1 -1
- package/dist/domains/comet-classic/classic-script-entry.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-script-entry.js +4 -1
- package/dist/domains/comet-classic/classic-script-entry.js.map +1 -1
- package/dist/domains/comet-classic/classic-state-command.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-state-command.js +37 -18
- package/dist/domains/comet-classic/classic-state-command.js.map +1 -1
- package/dist/domains/comet-classic/classic-validate-command.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-validate-command.js +2 -0
- package/dist/domains/comet-classic/classic-validate-command.js.map +1 -1
- package/dist/domains/comet-classic/classic-workspace.d.ts +1 -0
- package/dist/domains/comet-classic/classic-workspace.d.ts.map +1 -1
- package/dist/domains/comet-classic/classic-workspace.js +2 -1
- package/dist/domains/comet-classic/classic-workspace.js.map +1 -1
- package/dist/domains/comet-entry/entry-runtime.d.ts.map +1 -1
- package/dist/domains/comet-entry/entry-runtime.js +13 -3
- package/dist/domains/comet-entry/entry-runtime.js.map +1 -1
- package/dist/domains/comet-memory/plugin.js +4 -9
- package/dist/domains/comet-memory/plugin.js.map +1 -1
- package/dist/domains/comet-memory/repository.d.ts +3 -0
- package/dist/domains/comet-memory/repository.d.ts.map +1 -1
- package/dist/domains/comet-memory/repository.js +117 -25
- package/dist/domains/comet-memory/repository.js.map +1 -1
- package/dist/domains/comet-memory/review-contract.d.ts.map +1 -1
- package/dist/domains/comet-memory/review-contract.js +4 -2
- package/dist/domains/comet-memory/review-contract.js.map +1 -1
- package/dist/domains/comet-native/native-check-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-check-command.js +5 -1
- package/dist/domains/comet-native/native-check-command.js.map +1 -1
- package/dist/domains/comet-native/native-cli-help.d.ts.map +1 -1
- package/dist/domains/comet-native/native-cli-help.js +7 -2
- package/dist/domains/comet-native/native-cli-help.js.map +1 -1
- package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
- package/dist/domains/comet-native/native-next-command.js +22 -1
- package/dist/domains/comet-native/native-next-command.js.map +1 -1
- package/dist/domains/comet-native/native-output-language.d.ts.map +1 -1
- package/dist/domains/comet-native/native-output-language.js +3 -1
- package/dist/domains/comet-native/native-output-language.js.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
- package/dist/domains/comet-native/native-portable-continuation.js +11 -0
- package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
- package/dist/domains/comet-plugin/integration.d.ts.map +1 -1
- package/dist/domains/comet-plugin/integration.js +14 -8
- package/dist/domains/comet-plugin/integration.js.map +1 -1
- package/dist/domains/comet-plugin/plugin-runtime.d.ts +2 -2
- package/dist/domains/comet-plugin/plugin-runtime.d.ts.map +1 -1
- package/dist/domains/comet-plugin/plugin-runtime.js +89 -77
- package/dist/domains/comet-plugin/plugin-runtime.js.map +1 -1
- package/dist/domains/comet-plugin/types.d.ts +2 -0
- package/dist/domains/comet-plugin/types.d.ts.map +1 -1
- package/dist/domains/dashboard/server.d.ts.map +1 -1
- package/dist/domains/dashboard/server.js +20 -0
- package/dist/domains/dashboard/server.js.map +1 -1
- package/dist/domains/dashboard/web/index.html +14 -14
- package/dist/domains/integrations/openspec.d.ts.map +1 -1
- package/dist/domains/integrations/openspec.js +4 -3
- package/dist/domains/integrations/openspec.js.map +1 -1
- package/dist/domains/integrations/superpowers.js +2 -2
- package/dist/domains/integrations/superpowers.js.map +1 -1
- package/dist/domains/project-knowledge/corpus.d.ts.map +1 -1
- package/dist/domains/project-knowledge/corpus.js +5 -2
- package/dist/domains/project-knowledge/corpus.js.map +1 -1
- package/dist/domains/skill/languages.d.ts +3 -1
- package/dist/domains/skill/languages.d.ts.map +1 -1
- package/dist/domains/skill/languages.js +26 -1
- package/dist/domains/skill/languages.js.map +1 -1
- package/dist/domains/skill/uninstall.d.ts.map +1 -1
- package/dist/domains/skill/uninstall.js +16 -0
- package/dist/domains/skill/uninstall.js.map +1 -1
- package/dist/platform/process/git-environment.d.ts +3 -0
- package/dist/platform/process/git-environment.d.ts.map +1 -0
- package/dist/platform/process/git-environment.js +26 -0
- package/dist/platform/process/git-environment.js.map +1 -0
- package/eval/langsmith/tests/tasks/test_tasks.py +6 -0
- package/eval/local/tests/scaffold/test_langsmith_conftest.py +10 -0
- package/package.json +2 -2
|
@@ -3,8 +3,8 @@ import { createRequire as __cometCreateRequire } from 'module';
|
|
|
3
3
|
const require = __cometCreateRequire(import.meta.url);
|
|
4
4
|
var sC=Object.create;var gf=Object.defineProperty;var cC=Object.getOwnPropertyDescriptor;var lC=Object.getOwnPropertyNames;var uC=Object.getPrototypeOf,dC=Object.prototype.hasOwnProperty;var qc=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var A=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var C=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},cg=(e,t)=>{for(var r in t)gf(e,r,{get:t[r],enumerable:!0})},fC=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of lC(t))!dC.call(e,n)&&n!==r&&gf(e,n,{get:()=>t[n],enumerable:!(i=cC(t,n))||i.enumerable});return e};var da=(e,t,r)=>(r=e!=null?sC(uC(e)):{},fC(t||!e||!e.__esModule?gf(r,"default",{value:e,enumerable:!0}):r,e));function vC(e,t){return Nf[e][t]}function kf(e,t){return pg[e][t]??mg[e][t]}function Wc(e){return vg.get(e.trim().toLocaleLowerCase("en-US"))??null}function gg(e){return bf.get(e.trim().toLocaleLowerCase("en-US"))??null}function zc(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${vC(e,r)}
|
|
5
5
|
`).join(`
|
|
6
|
-
`)}function mt(e,t,r){return e==="zh-CN"?r:t}var Nf,pg,mg,vg,bf,Nn=A(()=>{"use strict";Nf={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:"验证预期"}},pg={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:"结论"}},mg={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:"结论"}},vg=new Map,bf=new Map;for(let e of Object.keys(Nf)){for(let[t,r]of Object.entries(Nf[e]))vg.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(pg[e]))bf.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(mg[e]))bf.set(r.toLocaleLowerCase("en-US"),t)}});var U=C(Fe=>{"use strict";var Sf=Symbol.for("yaml.alias"),wg=Symbol.for("yaml.document"),Jc=Symbol.for("yaml.map"),yg=Symbol.for("yaml.pair"),Ef=Symbol.for("yaml.scalar"),Gc=Symbol.for("yaml.seq"),
|
|
7
|
-
`)}};$o.defaultYaml={explicit:!1,version:"1.2"};$o.defaultTags={"!!":"tag:yaml.org,2002:"};Cg.Directives=$o});var Yc=C(Oo=>{"use strict";var xg=U(),CC=jo();function xC(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function Ag(e){let t=new Set;return CC.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function _g(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function AC(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Ag(e));let o=_g(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(xg.isScalar(o.node)||xg.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:i}}Oo.anchorIsValid=xC;Oo.anchorNames=Ag;Oo.createNodeAnchors=AC;Oo.findNewAnchor=_g});var Cf=C(Ig=>{"use strict";function Ho(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=Ho(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=Ho(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=Ho(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=Ho(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}Ig.applyReviver=Ho});var pi=C(jg=>{"use strict";var _C=U();function Tg(e,t,r){if(Array.isArray(e))return e.map((i,n)=>Tg(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!_C.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}jg.toJS=Tg});var Xc=C(Og=>{"use strict";var IC=Cf(),$g=U(),TC=pi(),xf=class{constructor(t){Object.defineProperty(this,$g.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!$g.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=TC.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?IC.applyReviver(a,{"":s},"",s):s}};Og.NodeBase=xf});var Do=C(Hg=>{"use strict";var jC=Yc(),$C=jo(),pa=U(),OC=Xc(),HC=pi(),Af=class extends OC.NodeBase{constructor(t){super(pa.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],$C.visit(t,{Node:(a,o)=>{(pa.isAlias(o)||pa.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(HC.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=Qc(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(jC.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 Qc(e,t,r){if(pa.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(pa.isCollection(t)){let i=0;for(let n of t.items){let a=Qc(e,n,r);a>i&&(i=a)}return i}else if(pa.isPair(t)){let i=Qc(e,t.key,r),n=Qc(e,t.value,r);return Math.max(i,n)}return 1}Hg.Alias=Af});var xe=C(_f=>{"use strict";var DC=U(),LC=Xc(),MC=pi(),FC=e=>!e||typeof e!="function"&&typeof e!="object",mi=class extends LC.NodeBase{constructor(t){super(DC.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:MC.toJS(this.value,t,r)}toString(){return String(this.value)}};mi.BLOCK_FOLDED="BLOCK_FOLDED";mi.BLOCK_LITERAL="BLOCK_LITERAL";mi.PLAIN="PLAIN";mi.QUOTE_DOUBLE="QUOTE_DOUBLE";mi.QUOTE_SINGLE="QUOTE_SINGLE";_f.Scalar=mi;_f.isScalarValue=FC});var Lo=C(Lg=>{"use strict";var BC=Do(),bn=U(),Dg=xe(),VC="tag:yaml.org,2002:";function qC(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function WC(e,t,r){if(bn.isDocument(e)&&(e=e.contents),bn.isNode(e))return e;if(bn.isPair(e)){let d=r.schema[bn.MAP].createNode?.(r.schema,null,r);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new BC.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=VC+t.slice(2));let l=qC(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Dg.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[bn.MAP]:Symbol.iterator in Object(e)?o[bn.SEQ]:o[bn.MAP]}a&&(a(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new Dg.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}Lg.createNode=WC});var el=C(Zc=>{"use strict";var zC=Lo(),
|
|
6
|
+
`)}function mt(e,t,r){return e==="zh-CN"?r:t}var Nf,pg,mg,vg,bf,Nn=A(()=>{"use strict";Nf={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:"验证预期"}},pg={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:"结论"}},mg={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:"结论"}},vg=new Map,bf=new Map;for(let e of Object.keys(Nf)){for(let[t,r]of Object.entries(Nf[e]))vg.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(pg[e]))bf.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(mg[e]))bf.set(r.toLocaleLowerCase("en-US"),t)}});var U=C(Fe=>{"use strict";var Sf=Symbol.for("yaml.alias"),wg=Symbol.for("yaml.document"),Jc=Symbol.for("yaml.map"),yg=Symbol.for("yaml.pair"),Ef=Symbol.for("yaml.scalar"),Gc=Symbol.for("yaml.seq"),Vr=Symbol.for("yaml.node.type"),gC=e=>!!e&&typeof e=="object"&&e[Vr]===Sf,wC=e=>!!e&&typeof e=="object"&&e[Vr]===wg,yC=e=>!!e&&typeof e=="object"&&e[Vr]===Jc,NC=e=>!!e&&typeof e=="object"&&e[Vr]===yg,Ng=e=>!!e&&typeof e=="object"&&e[Vr]===Ef,bC=e=>!!e&&typeof e=="object"&&e[Vr]===Gc;function bg(e){if(e&&typeof e=="object")switch(e[Vr]){case Jc:case Gc:return!0}return!1}function kC(e){if(e&&typeof e=="object")switch(e[Vr]){case Sf:case Jc:case Ef:case Gc:return!0}return!1}var SC=e=>(Ng(e)||bg(e))&&!!e.anchor;Fe.ALIAS=Sf;Fe.DOC=wg;Fe.MAP=Jc;Fe.NODE_TYPE=Vr;Fe.PAIR=yg;Fe.SCALAR=Ef;Fe.SEQ=Gc;Fe.hasAnchor=SC;Fe.isAlias=gC;Fe.isCollection=bg;Fe.isDocument=wC;Fe.isMap=yC;Fe.isNode=kC;Fe.isPair=NC;Fe.isScalar=Ng;Fe.isSeq=bC});var jo=C(Pf=>{"use strict";var $e=U(),vt=Symbol("break visit"),kg=Symbol("skip children"),br=Symbol("remove node");function Uc(e,t){let r=Sg(t);$e.isDocument(e)?fa(null,e.contents,r,Object.freeze([e]))===br&&(e.contents=null):fa(null,e,r,Object.freeze([]))}Uc.BREAK=vt;Uc.SKIP=kg;Uc.REMOVE=br;function fa(e,t,r,i){let n=Eg(e,t,r,i);if($e.isNode(n)||$e.isPair(n))return Pg(e,i,n),fa(e,n,r,i);if(typeof n!="symbol"){if($e.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=fa(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===vt)return vt;o===br&&(t.items.splice(a,1),a-=1)}}}else if($e.isPair(t)){i=Object.freeze(i.concat(t));let a=fa("key",t.key,r,i);if(a===vt)return vt;a===br&&(t.key=null);let o=fa("value",t.value,r,i);if(o===vt)return vt;o===br&&(t.value=null)}}return n}async function Kc(e,t){let r=Sg(t);$e.isDocument(e)?await ha(null,e.contents,r,Object.freeze([e]))===br&&(e.contents=null):await ha(null,e,r,Object.freeze([]))}Kc.BREAK=vt;Kc.SKIP=kg;Kc.REMOVE=br;async function ha(e,t,r,i){let n=await Eg(e,t,r,i);if($e.isNode(n)||$e.isPair(n))return Pg(e,i,n),ha(e,n,r,i);if(typeof n!="symbol"){if($e.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await ha(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===vt)return vt;o===br&&(t.items.splice(a,1),a-=1)}}}else if($e.isPair(t)){i=Object.freeze(i.concat(t));let a=await ha("key",t.key,r,i);if(a===vt)return vt;a===br&&(t.key=null);let o=await ha("value",t.value,r,i);if(o===vt)return vt;o===br&&(t.value=null)}}return n}function Sg(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 Eg(e,t,r,i){if(typeof r=="function")return r(e,t,i);if($e.isMap(t))return r.Map?.(e,t,i);if($e.isSeq(t))return r.Seq?.(e,t,i);if($e.isPair(t))return r.Pair?.(e,t,i);if($e.isScalar(t))return r.Scalar?.(e,t,i);if($e.isAlias(t))return r.Alias?.(e,t,i)}function Pg(e,t,r){let i=t[t.length-1];if($e.isCollection(i))i.items[e]=r;else if($e.isPair(i))e==="key"?i.key=r:i.value=r;else if($e.isDocument(i))i.contents=r;else{let n=$e.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Pf.visit=Uc;Pf.visitAsync=Kc});var Rf=C(Cg=>{"use strict";var Rg=U(),EC=jo(),PC={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},RC=e=>e.replace(/[!,[\]{}]/g,t=>PC[t]),$o=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+RC(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&Rg.isNode(t.contents)){let a={};EC.visit(t.contents,(o,s)=>{Rg.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
|
|
7
|
+
`)}};$o.defaultYaml={explicit:!1,version:"1.2"};$o.defaultTags={"!!":"tag:yaml.org,2002:"};Cg.Directives=$o});var Yc=C(Oo=>{"use strict";var xg=U(),CC=jo();function xC(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function Ag(e){let t=new Set;return CC.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function _g(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function AC(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Ag(e));let o=_g(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(xg.isScalar(o.node)||xg.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:i}}Oo.anchorIsValid=xC;Oo.anchorNames=Ag;Oo.createNodeAnchors=AC;Oo.findNewAnchor=_g});var Cf=C(Ig=>{"use strict";function Ho(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=Ho(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=Ho(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=Ho(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=Ho(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}Ig.applyReviver=Ho});var pi=C(jg=>{"use strict";var _C=U();function Tg(e,t,r){if(Array.isArray(e))return e.map((i,n)=>Tg(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!_C.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}jg.toJS=Tg});var Xc=C(Og=>{"use strict";var IC=Cf(),$g=U(),TC=pi(),xf=class{constructor(t){Object.defineProperty(this,$g.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!$g.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=TC.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?IC.applyReviver(a,{"":s},"",s):s}};Og.NodeBase=xf});var Do=C(Hg=>{"use strict";var jC=Yc(),$C=jo(),pa=U(),OC=Xc(),HC=pi(),Af=class extends OC.NodeBase{constructor(t){super(pa.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],$C.visit(t,{Node:(a,o)=>{(pa.isAlias(o)||pa.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(HC.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=Qc(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(jC.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 Qc(e,t,r){if(pa.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(pa.isCollection(t)){let i=0;for(let n of t.items){let a=Qc(e,n,r);a>i&&(i=a)}return i}else if(pa.isPair(t)){let i=Qc(e,t.key,r),n=Qc(e,t.value,r);return Math.max(i,n)}return 1}Hg.Alias=Af});var xe=C(_f=>{"use strict";var DC=U(),LC=Xc(),MC=pi(),FC=e=>!e||typeof e!="function"&&typeof e!="object",mi=class extends LC.NodeBase{constructor(t){super(DC.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:MC.toJS(this.value,t,r)}toString(){return String(this.value)}};mi.BLOCK_FOLDED="BLOCK_FOLDED";mi.BLOCK_LITERAL="BLOCK_LITERAL";mi.PLAIN="PLAIN";mi.QUOTE_DOUBLE="QUOTE_DOUBLE";mi.QUOTE_SINGLE="QUOTE_SINGLE";_f.Scalar=mi;_f.isScalarValue=FC});var Lo=C(Lg=>{"use strict";var BC=Do(),bn=U(),Dg=xe(),VC="tag:yaml.org,2002:";function qC(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function WC(e,t,r){if(bn.isDocument(e)&&(e=e.contents),bn.isNode(e))return e;if(bn.isPair(e)){let d=r.schema[bn.MAP].createNode?.(r.schema,null,r);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new BC.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=VC+t.slice(2));let l=qC(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Dg.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[bn.MAP]:Symbol.iterator in Object(e)?o[bn.SEQ]:o[bn.MAP]}a&&(a(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new Dg.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}Lg.createNode=WC});var el=C(Zc=>{"use strict";var zC=Lo(),kr=U(),JC=Xc();function If(e,t,r){let i=r;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return zC.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Mg=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Tf=class extends JC.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>kr.isNode(i)||kr.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(Mg(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(kr.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,If(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(kr.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&kr.isScalar(a)?a.value:a:kr.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!kr.isPair(r))return!1;let i=r.value;return i==null||t&&kr.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return kr.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(kr.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,If(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};Zc.Collection=Tf;Zc.collectionFromPath=If;Zc.isEmptyPath=Mg});var Mo=C(tl=>{"use strict";var GC=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function jf(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var UC=(e,t,r)=>e.endsWith(`
|
|
8
8
|
`)?jf(r,t):r.includes(`
|
|
9
9
|
`)?`
|
|
10
10
|
`+jf(r,t):(e.endsWith(" ")?"":" ")+r;tl.indentComment=jf;tl.lineComment=UC;tl.stringifyComment=GC});var Bg=C(Fo=>{"use strict";var KC="flow",$f="block",rl="quoted";function YC(e,t,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],u={},d=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):d=n-i);let f,h,m=!1,p=-1,v=-1,g=-1;r===$f&&(p=Fg(e,p,t.length),p!==-1&&(d=p+c));for(let E;E=e[p+=1];){if(r===rl&&E==="\\"){switch(v=p,e[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}g=p}if(E===`
|
|
@@ -13,7 +13,7 @@ var sC=Object.create;var gf=Object.defineProperty;var cC=Object.getOwnPropertyDe
|
|
|
13
13
|
`&&w!==" "&&(f=p)}if(p>=d)if(f)l.push(f),d=f+c,f=void 0;else if(r===rl){for(;h===" "||h===" ";)h=E,E=e[p+=1],m=!0;let w=p>g+1?p-2:v-1;if(u[w])return e;l.push(w),u[w]=!0,d=w+c,f=void 0}else m=!0}h=E}if(m&&s&&s(),l.length===0)return e;o&&o();let N=e.slice(0,l[0]);for(let E=0;E<l.length;++E){let w=l[E],S=l[E+1]||e.length;w===0?N=`
|
|
14
14
|
${t}${e.slice(0,S)}`:(r===rl&&u[w]&&(N+=`${e[w]}\\`),N+=`
|
|
15
15
|
${t}${e.slice(w+1,S)}`)}return N}function Fg(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
16
|
-
`);i=t,n=t+1,a=e[n]}return i}Fo.FOLD_BLOCK=$f;Fo.FOLD_FLOW=KC;Fo.FOLD_QUOTED=rl;Fo.foldFlowLines=YC});var Vo=C(Vg=>{"use strict";var
|
|
16
|
+
`);i=t,n=t+1,a=e[n]}return i}Fo.FOLD_BLOCK=$f;Fo.FOLD_FLOW=KC;Fo.FOLD_QUOTED=rl;Fo.foldFlowLines=YC});var Vo=C(Vg=>{"use strict";var rr=xe(),vi=Bg(),nl=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),al=e=>/^(%|---|\.\.\.)/m.test(e);function XC(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
|
|
17
17
|
`){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function Bo(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(al(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let u=r.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+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
|
|
18
18
|
|
|
19
19
|
`;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
|
|
@@ -22,28 +22,28 @@ ${t}${e.slice(w+1,S)}`)}return N}function Fg(e,t,r){let i=t,n=t+1,a=e[n];for(;a=
|
|
|
22
22
|
${r}`)+"'";return t.implicitKey?i:vi.foldFlowLines(i,r,vi.FOLD_FLOW,nl(t,!1))}function ma(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=Bo;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=Of:a&&!n?i=Bo:i=r?Of:Bo}return i(e,t)}var Hf;try{Hf=new RegExp(`(^|(?<!
|
|
23
23
|
))
|
|
24
24
|
+(?!
|
|
25
|
-
|$)`,"g")}catch{Hf=/\n+(?!\n|$)/g}function il({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return ma(r,i);let l=i.indent||(i.forceBlockIndent||al(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===
|
|
25
|
+
|$)`,"g")}catch{Hf=/\n+(?!\n|$)/g}function il({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return ma(r,i);let l=i.indent||(i.forceBlockIndent||al(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===rr.Scalar.BLOCK_FOLDED?!1:t===rr.Scalar.BLOCK_LITERAL?!0:!XC(r,c,l.length);if(!r)return u?`|
|
|
26
26
|
`:`>
|
|
27
27
|
`;let d,f;for(f=r.length;f>0;--f){let S=r[f-1];if(S!==`
|
|
28
28
|
`&&S!==" "&&S!==" ")break}let h=r.substring(f),m=h.indexOf(`
|
|
29
29
|
`);m===-1?d="-":r===h||m!==h.length-1?(d="+",a&&a()):d="",h&&(r=r.slice(0,-h.length),h[h.length-1]===`
|
|
30
30
|
`&&(h=h.slice(0,-1)),h=h.replace(Hf,`$&${l}`));let p=!1,v,g=-1;for(v=0;v<r.length;++v){let S=r[v];if(S===" ")p=!0;else if(S===`
|
|
31
31
|
`)g=v;else break}let N=r.substring(0,g<v?g+1:v);N&&(r=r.substring(N.length),N=N.replace(/\n+/g,`$&${l}`));let w=(p?l?"2":"1":"")+d;if(e&&(w+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let S=r.replace(/\n+/g,`
|
|
32
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),k=!1,R=nl(i,!0);o!=="folded"&&t!==
|
|
32
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),k=!1,R=nl(i,!0);o!=="folded"&&t!==rr.Scalar.BLOCK_FOLDED&&(R.onOverflow=()=>{k=!0});let b=vi.foldFlowLines(`${N}${S}${h}`,l,vi.FOLD_BLOCK,R);if(!k)return`>${w}
|
|
33
33
|
${l}${b}`}return r=r.replace(/\n+/g,`$&${l}`),`|${w}
|
|
34
34
|
${l}${N}${r}${h}`}function QC(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
|
|
35
35
|
`)||u&&/[[\]{},]/.test(a))return ma(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
|
|
36
|
-
`)?ma(a,t):il(e,t,r,i);if(!s&&!u&&n!==
|
|
36
|
+
`)?ma(a,t):il(e,t,r,i);if(!s&&!u&&n!==rr.Scalar.PLAIN&&a.includes(`
|
|
37
37
|
`))return il(e,t,r,i);if(al(a)){if(c==="")return t.forceBlockIndent=!0,il(e,t,r,i);if(s&&c===l)return ma(a,t)}let d=a.replace(/\n+/g,`$&
|
|
38
|
-
${c}`);if(o){let f=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(d),{compat:h,tags:m}=t.doc.schema;if(m.some(f)||h?.some(f))return ma(a,t)}return s?d:vi.foldFlowLines(d,c,vi.FOLD_FLOW,nl(t,!1))}function ZC(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==
|
|
39
|
-
${t.indent}${s}`:s}Df.createStringifyContext=ix;Df.stringify=ox});var Jg=C(zg=>{"use strict";var
|
|
40
|
-
${s}:`):(v=`${v}:`,f&&(v+=Wo.lineComment(v,r.indent,l(f))));let g,N,E;
|
|
38
|
+
${c}`);if(o){let f=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(d),{compat:h,tags:m}=t.doc.schema;if(m.some(f)||h?.some(f))return ma(a,t)}return s?d:vi.foldFlowLines(d,c,vi.FOLD_FLOW,nl(t,!1))}function ZC(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==rr.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=rr.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case rr.Scalar.BLOCK_FOLDED:case rr.Scalar.BLOCK_LITERAL:return n||a?ma(o.value,t):il(o,t,r,i);case rr.Scalar.QUOTE_DOUBLE:return Bo(o.value,t);case rr.Scalar.QUOTE_SINGLE:return Of(o.value,t);case rr.Scalar.PLAIN:return QC(o,t,r,i);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}Vg.stringifyString=ZC});var qo=C(Df=>{"use strict";var ex=Yc(),gi=U(),tx=Mo(),rx=Vo();function ix(e,t){let r=Object.assign({blockQuote:!0,commentString:tx.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function nx(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let r,i;if(gi.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function ax(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(gi.isScalar(e)||gi.isCollection(e))&&e.anchor;a&&ex.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function ox(e,t,r,i){if(gi.isPair(e))return e.toString(t,r,i);if(gi.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=gi.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=nx(t.doc.schema.tags,a));let o=ax(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):gi.isScalar(a)?rx.stringifyString(a,t,r,i):a.toString(t,r,i);return o?gi.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
|
|
39
|
+
${t.indent}${s}`:s}Df.createStringifyContext=ix;Df.stringify=ox});var Jg=C(zg=>{"use strict";var qr=U(),qg=xe(),Wg=qo(),Wo=Mo();function sx({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=r,f=qr.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(qr.isCollection(e)||!qr.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&&!r.inFlow||qr.isCollection(e)||(qr.isScalar(e)?e.type===qg.Scalar.BLOCK_FOLDED||e.type===qg.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!h&&(d||!a),indent:s+c});let m=!1,p=!1,v=Wg.stringify(e,r,()=>m=!0,()=>p=!0);if(!h&&!r.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(r.inFlow){if(a||t==null)return m&&i&&i(),v===""?"?":h?`? ${v}`:v}else if(a&&!d||t==null&&h)return v=`? ${v}`,f&&!m?v+=Wo.lineComment(v,r.indent,l(f)):p&&n&&n(),v;m&&(f=null),h?(f&&(v+=Wo.lineComment(v,r.indent,l(f))),v=`? ${v}
|
|
40
|
+
${s}:`):(v=`${v}:`,f&&(v+=Wo.lineComment(v,r.indent,l(f))));let g,N,E;qr.isNode(t)?(g=!!t.spaceBefore,N=t.commentBefore,E=t.comment):(g=!1,N=null,E=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!h&&!f&&qr.isScalar(t)&&(r.indentAtStart=v.length+1),p=!1,!u&&c.length>=2&&!r.inFlow&&!h&&qr.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let w=!1,S=Wg.stringify(t,r,()=>w=!0,()=>p=!0),k=" ";if(f||g||N){if(k=g?`
|
|
41
41
|
`:"",N){let R=l(N);k+=`
|
|
42
42
|
${Wo.indentComment(R,r.indent)}`}S===""&&!r.inFlow?k===`
|
|
43
43
|
`&&E&&(k=`
|
|
44
44
|
|
|
45
45
|
`):k+=`
|
|
46
|
-
${r.indent}`}else if(!h&&
|
|
46
|
+
${r.indent}`}else if(!h&&qr.isCollection(t)){let R=S[0],b=S.indexOf(`
|
|
47
47
|
`),y=b!==-1,P=r.inFlow??t.flow??t.items.length===0;if(y||!P){let L=!1;if(y&&(R==="&"||R==="!")){let H=S.indexOf(" ");R==="&"&&H!==-1&&H<b&&S[H+1]==="!"&&(H=S.indexOf(" ",H+1)),(H===-1||b<H)&&(L=!0)}L||(k=`
|
|
48
48
|
${r.indent}`)}}else(S===""||S[0]===`
|
|
49
49
|
`)&&(k="");return v+=k+S,r.inFlow?w&&i&&i():E&&!w?v+=Wo.lineComment(v,r.indent,l(E)):p&&n&&n(),v}zg.stringifyPair=sx});var Mf=C(Lf=>{"use strict";var Gg=qc("process");function cx(e,...t){e==="debug"&&console.log(...t)}function lx(e,t){(e==="debug"||e==="warn")&&(typeof Gg.emitWarning=="function"?Gg.emitWarning(t):console.warn(t))}Lf.debug=cx;Lf.warn=lx});var ul=C(ll=>{"use strict";var cl=U(),Ug=xe(),ol="<<",sl={identify:e=>e===ol||typeof e=="symbol"&&e.description===ol,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Ug.Scalar(Symbol(ol)),{addToJSMap:Kg}),stringify:()=>ol},ux=(e,t)=>(sl.identify(t)||cl.isScalar(t)&&(!t.type||t.type===Ug.Scalar.PLAIN)&&sl.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===sl.tag&&r.default);function Kg(e,t,r){let i=Yg(e,r);if(cl.isSeq(i))for(let n of i.items)Ff(e,t,n);else if(Array.isArray(i))for(let n of i)Ff(e,t,n);else Ff(e,t,i)}function Ff(e,t,r){let i=Yg(e,r);if(!cl.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function Yg(e,t){return e&&cl.isAlias(t)?t.resolve(e.doc,e):t}ll.addMergeToJSMap=Kg;ll.isMergeKey=ux;ll.merge=sl});var Vf=C(Zg=>{"use strict";var dx=Mf(),Xg=ul(),fx=qo(),Qg=U(),Bf=pi();function hx(e,t,{key:r,value:i}){if(Qg.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(Xg.isMergeKey(e,r))Xg.addMergeToJSMap(e,t,i);else{let n=Bf.toJS(r,"",e);if(t instanceof Map)t.set(n,Bf.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=px(r,n,e),o=Bf.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function px(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(Qg.isNode(e)&&r?.doc){let i=fx.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),dx.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}Zg.addPairToJSMap=hx});var wi=C(qf=>{"use strict";var ew=Lo(),mx=Jg(),vx=Vf(),dl=U();function gx(e,t,r){let i=ew.createNode(e,void 0,r),n=ew.createNode(t,void 0,r);return new fl(i,n)}var fl=class e{constructor(t,r=null){Object.defineProperty(this,dl.NODE_TYPE,{value:dl.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return dl.isNode(r)&&(r=r.clone(t)),dl.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return vx.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?mx.stringifyPair(this,t,r,i):JSON.stringify(this)}};qf.Pair=fl;qf.createPair=gx});var Wf=C(rw=>{"use strict";var kn=U(),tw=qo(),hl=Mo();function wx(e,t,r){return(t.inFlow??e.flow?Nx:yx)(e,t,r)}function yx({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:a,type:null}),d=!1,f=[];for(let m=0;m<t.length;++m){let p=t[m],v=null;if(kn.isNode(p))!d&&p.spaceBefore&&f.push(""),pl(r,f,p.commentBefore,d),p.comment&&(v=p.comment);else if(kn.isPair(p)){let N=kn.isNode(p.key)?p.key:null;N&&(!d&&N.spaceBefore&&f.push(""),pl(r,f,N.commentBefore,d))}d=!1;let g=tw.stringify(p,u,()=>v=null,()=>d=!0);v&&(g+=hl.lineComment(g,a,l(v))),d&&v&&(d=!1),f.push(i+g)}let h;if(f.length===0)h=n.start+n.end;else{h=f[0];for(let m=1;m<f.length;++m){let p=f[m];h+=p?`
|
|
@@ -118,34 +118,34 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
|
|
|
118
118
|
`});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 Ly(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function Vh(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of i)a.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
119
119
|
`};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}Hl.createScalarToken=uI;Hl.resolveAsScalar=lI;Hl.setScalarValue=dI});var By=C(Fy=>{"use strict";var hI=e=>"type"in e?Ll(e):Dl(e);function Ll(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Ll(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Dl(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Dl(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Dl(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function Dl({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Ll(t)),r)for(let a of r)n+=a.source;return i&&(n+=Ll(i)),n}Fy.stringify=hI});var zy=C(Wy=>{"use strict";var qh=Symbol("break visit"),pI=Symbol("skip children"),Vy=Symbol("remove item");function Rn(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),qy(Object.freeze([]),e,t)}Rn.BREAK=qh;Rn.SKIP=pI;Rn.REMOVE=Vy;Rn.itemAtPath=(e,t)=>{let r=e;for(let[i,n]of t){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};Rn.parentCollection=(e,t)=>{let r=Rn.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function qy(e,t,r){let i=r(t,e);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=qy(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===qh)return qh;s===Vy&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}Wy.visit=Rn});var Ml=C(gt=>{"use strict";var Wh=My(),mI=By(),vI=zy(),zh="\uFEFF",Jh="",Gh="",Uh="",gI=e=>!!e&&"items"in e,wI=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function yI(e){switch(e){case zh:return"<BOM>";case Jh:return"<DOC>";case Gh:return"<FLOW_END>";case Uh:return"<SCALAR>";default:return JSON.stringify(e)}}function NI(e){switch(e){case zh:return"byte-order-mark";case Jh:return"doc-mode";case Gh:return"flow-error-end";case Uh:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
120
120
|
`:case`\r
|
|
121
|
-
`: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}gt.createScalarToken=Wh.createScalarToken;gt.resolveAsScalar=Wh.resolveAsScalar;gt.setScalarValue=Wh.setScalarValue;gt.stringify=mI.stringify;gt.visit=vI.visit;gt.BOM=zh;gt.DOCUMENT=Jh;gt.FLOW_END=Gh;gt.SCALAR=Uh;gt.isCollection=gI;gt.isScalar=wI;gt.prettyToken=yI;gt.tokenType=NI});var Xh=C(Gy=>{"use strict";var os=Ml();function
|
|
121
|
+
`: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}gt.createScalarToken=Wh.createScalarToken;gt.resolveAsScalar=Wh.resolveAsScalar;gt.setScalarValue=Wh.setScalarValue;gt.stringify=mI.stringify;gt.visit=vI.visit;gt.BOM=zh;gt.DOCUMENT=Jh;gt.FLOW_END=Gh;gt.SCALAR=Uh;gt.isCollection=gI;gt.isScalar=wI;gt.prettyToken=yI;gt.tokenType=NI});var Xh=C(Gy=>{"use strict";var os=Ml();function ir(e){switch(e){case void 0:case" ":case`
|
|
122
122
|
`:case"\r":case" ":return!0;default:return!1}}var Jy=new Set("0123456789ABCDEFabcdef"),bI=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Fl=new Set(",[]{}"),kI=new Set(` ,[]{}
|
|
123
123
|
\r `),Kh=e=>!e||kI.has(e),Yh=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
|
|
124
124
|
`?!0:r==="\r"?this.buffer[t+1]===`
|
|
125
125
|
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let i=0;for(;r===" ";)r=this.buffer[++i+t];if(r==="\r"){let n=this.buffer[i+t+1];if(n===`
|
|
126
126
|
`||!n&&!this.atEnd)return t+i+1}return r===`
|
|
127
|
-
`||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&
|
|
128
|
-
`,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]===os.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield os.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&
|
|
127
|
+
`||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&ir(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(`
|
|
128
|
+
`,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]===os.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield os.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&ir(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!ir(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&ir(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Kh),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&ir(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield os.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(Kh),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||ir(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
|
|
129
129
|
`,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
|
|
130
|
-
`,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>
|
|
130
|
+
`,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>ir(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
|
|
131
131
|
`:t=a,r=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
132
132
|
`)break}default:break e}if(!i&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
|
|
133
133
|
`,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(i=this.buffer[n];i===" ";)i=this.buffer[++n];if(i===" "){for(;i===" "||i===" "||i==="\r"||i===`
|
|
134
134
|
`;)i=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
|
|
135
|
-
`&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield os.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(
|
|
135
|
+
`&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield os.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(ir(a)||t&&Fl.has(a))break;r=i}else if(ir(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
|
|
136
136
|
`?(i+=1,n=`
|
|
137
137
|
`,a=this.buffer[i+1]):r=i),a==="#"||t&&Fl.has(a))break;if(n===`
|
|
138
|
-
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&Fl.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield os.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Kh),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(
|
|
138
|
+
`){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&Fl.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield os.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Kh),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(ir(i)||r&&Fl.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!ir(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(bI.has(r))r=this.buffer[++t];else if(r==="%"&&Jy.has(this.buffer[t+1])&&Jy.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
|
|
139
139
|
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
140
140
|
`?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};Gy.Lexer=Yh});var Zh=C(Uy=>{"use strict";var Qh=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<t?r=a+1:i=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let n=this.lineStarts[r-1];return{line:r,col:t-n+1}}}};Uy.LineCounter=Qh});var tp=C(Zy=>{"use strict";var SI=qc("process"),Ky=Ml(),EI=Xh();function ki(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function Yy(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 Qy(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 Bl(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 ka(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 Vl(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function Xy(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!ki(t.start,"explicit-key-ind")&&!ki(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Qy(t.value)?t.value.end?Vl(t.value.end,t.sep):t.value.end=t.sep:Vl(t.start,t.sep),delete t.sep)}var ep=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 EI.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,r))yield*this.next(i);r||(yield*this.end())}*next(t){if(this.source=t,SI.env.LOG_TOKENS&&console.log("|",Ky.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=Ky.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let i=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in i?i.indent:0:r.type==="flow-collection"&&i.type==="document"&&(r.indent=0),r.type==="flow-collection"&&Xy(r),i.type){case"document":i.value=r;break;case"block-scalar":i.props.push(r);break;case"block-map":{let n=i.items[i.items.length-1];if(n.value){i.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=r;else{Object.assign(n,{key:r,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=i.items[i.items.length-1];n.value?i.items.push({start:[],value:r}):n.value=r;break}case"flow-collection":{let n=i.items[i.items.length-1];!n||n.value?i.items.push({start:[],key:r,sep:[]}):n.sep?n.value=r:Object.assign(n,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let n=r.items[r.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&Yy(n.start)===-1&&(r.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(i.type==="document"?i.end=n.start:i.items.push({start:n.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{Yy(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=Bl(this.peek(2)),i=ka(r),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
|
|
141
141
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
142
142
|
`,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Vl(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,n=i&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&r.sep&&!r.value){let o=[];for(let s=0;s<r.sep.length;++s){let c=r.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=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||r.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):n||r.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(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(ki(r.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(Qy(r.key)&&!ki(r.sep,"newline")){let o=ka(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(ki(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=ka(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):ki(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{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||r.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!ki(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){Vl(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||ki(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:n,sep:[]}):r.sep?this.stack.push(n):Object.assign(r,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===t.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let n=Bl(i),a=ka(n);Xy(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 r=this.source.indexOf(`
|
|
143
143
|
`)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
|
|
144
|
-
`,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=Bl(t),i=ka(r);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=Bl(t),i=ka(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Zy.Parser=ep});var nN=C(cs=>{"use strict";var eN=Bh(),PI=Zo(),ss=rs(),RI=Mf(),CI=U(),xI=Zh(),tN=tp();function rN(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new xI.LineCounter||null,prettyErrors:t}}function AI(e,t={}){let{lineCounter:r,prettyErrors:i}=rN(t),n=new tN.Parser(r?.addNewLine),a=new eN.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(ss.prettifyError(e,r)),s.warnings.forEach(ss.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function iN(e,t={}){let{lineCounter:r,prettyErrors:i}=rN(t),n=new tN.Parser(r?.addNewLine),a=new eN.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 ss.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(ss.prettifyError(e,r)),o.warnings.forEach(ss.prettifyError(e,r))),o}function _I(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=iN(e,r);if(!n)return null;if(n.warnings.forEach(a=>RI.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:i},r))}function II(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return CI.isDocument(e)&&!i?e.toString(r):new PI.Document(e,i,r).toString(r)}cs.parse=_I;cs.parseAllDocuments=AI;cs.parseDocument=iN;cs.stringify=II});var Cn=C(Z=>{"use strict";var TI=Bh(),jI=Zo(),$I=bh(),rp=rs(),OI=Do(),Si=U(),HI=wi(),DI=xe(),LI=Ni(),MI=bi(),FI=Ml(),BI=Xh(),VI=Zh(),qI=tp(),ql=nN(),aN=jo();Z.Composer=TI.Composer;Z.Document=jI.Document;Z.Schema=$I.Schema;Z.YAMLError=rp.YAMLError;Z.YAMLParseError=rp.YAMLParseError;Z.YAMLWarning=rp.YAMLWarning;Z.Alias=OI.Alias;Z.isAlias=Si.isAlias;Z.isCollection=Si.isCollection;Z.isDocument=Si.isDocument;Z.isMap=Si.isMap;Z.isNode=Si.isNode;Z.isPair=Si.isPair;Z.isScalar=Si.isScalar;Z.isSeq=Si.isSeq;Z.Pair=HI.Pair;Z.Scalar=DI.Scalar;Z.YAMLMap=LI.YAMLMap;Z.YAMLSeq=MI.YAMLSeq;Z.CST=FI;Z.Lexer=BI.Lexer;Z.LineCounter=VI.LineCounter;Z.Parser=qI.Parser;Z.parse=ql.parse;Z.parseAllDocuments=ql.parseAllDocuments;Z.parseDocument=ql.parseDocument;Z.stringify=ql.stringify;Z.visit=aN.visit;Z.visitAsync=aN.visitAsync});import{execFileSync as WI}from"child_process";import ls from"path";function Ei(e,t){return WI("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function zI(e,t){let r=ls.normalize(e),i=ls.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function ae(e){try{let t=ls.resolve(Ei(e,["rev-parse","--show-toplevel"])),i=Ei(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?ls.resolve(i.slice(9)):t,a=null;try{a=Ei(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!zI(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function oN(e){try{Ei(e,["rev-parse","--is-inside-work-tree"]);let t=Ei(e,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:ls.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}catch{return[]}}function ir(e){return oN(e).map(t=>t.root)}function us(e,t){try{return Ei(e,["check-ref-format","--branch",t]),Ei(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function qr(e,t){try{let r=Ei(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}var Lt=A(()=>{"use strict"});import ip from"path";function UI(e){return e.toLowerCase().startsWith(".env")}function kr(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>UI(i))?"environment-file":r.some(i=>GI.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>JI.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function np(e,t){let r=kr(t);if(r)return r;let i=ip.resolve(e.projectRoot,...t.split("/")),n=ip.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||i===ip.resolve(e.configFile)?"native-runtime":null}var JI,GI,ds=A(()=>{"use strict";JI=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),GI=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function Pi(e){return e!==0&&e!==0n&&e!=="0"}function Rt(e,t){return Pi(e.dev)&&Pi(t.dev)&&Pi(e.ino)&&Pi(t.ino)}function J(e,t){let r=Pi(e.dev)&&Pi(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Pi(e.ino)&&Pi(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var fs=A(()=>{"use strict"});var nr=A(()=>{"use strict";fs()});import{createHash as KI}from"node:crypto";import{promises as ar}from"node:fs";import Mt from"node:path";import{TextDecoder as YI}from"node:util";function ap(e,t){let r=Mt.relative(e,t);return r===""||!Mt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Mt.sep}`)}function XI(e){let t=Mt.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})||Mt.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=kr(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function QI(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function ZI(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Wl(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Rt(r,i)?J(r,i):J(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function sN(e){let t=await ar.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await ar.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function eT(e,t){let r=Mt.resolve(e),i=Mt.resolve(t);if(!ap(r,i))throw new Error("Native artifact path is outside its root");let n=[await sN(r)],a=r;for(let o of Mt.relative(r,i).split(Mt.sep).filter(Boolean)){a=Mt.join(a,o);let s=await sN(a);if(!ap(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function cN(e){for(let t of e){let r=await ar.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!ZI(t,r)||await ar.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function te(e){let t=XI(e.ref),r=e.maxBytes===null?null:QI(e.maxBytes??hs),i=Mt.resolve(e.root,...t.split("/")),n=await eT(e.root,Mt.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await ar.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await ar.realpath(i);if(!ap(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await ar.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),ar.lstat(i),ar.realpath(i)]);if(await cN(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Wl(a,c)||!Wl(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,h=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let E=r===null?h.length:r+1-f,w=await s.read(h,0,Math.min(h.length,E),null);if(w.bytesRead===0)break;if(f+=w.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,w.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,p,v]=await Promise.all([s.stat(),ar.lstat(i),ar.realpath(i)]);if(await cN(n),!p.isFile()||p.isSymbolicLink()||v!==o||!Wl(c,m)||!Wl(c,p))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,f),N;try{N=new YI("utf-8",{fatal:!0}).decode(g)}catch(E){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:E})}return{ref:t,size:f,hash:e.includeHash===!1?null:KI("sha256").update(g).digest("hex"),text:N}}finally{await s.close()}}var hs,Ft=A(()=>{"use strict";ds();nr();hs=1024*1024});import{randomUUID as tT}from"crypto";import{promises as He}from"fs";import or from"path";function zl(e,t){let r=or.relative(e,t);return r===""||!or.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${or.sep}`)}function rT(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Jl(e,t){return J({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function iT(e,t){return Jl(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function lN(e){let t=await He.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 He.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Sa(e){for(let t of e){let r=await He.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!rT(t,r)||await He.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function nT(e,t,r){let[i,n]=await Promise.all([He.lstat(e),He.realpath(e),r?Sa(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!Jl(i,t)||r&&!zl(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function aT(e,t){let r=or.resolve(e),i=or.resolve(t);if(!zl(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await lN(r)],a=or.relative(r,i).split(or.sep).filter(Boolean),o=r;for(let s of a){await Sa(n),o=or.join(o,s);try{await He.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await lN(o);if(!zl(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Sa(n),n}async function oT(e){let t;try{t=await He.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function uN(e,t,r={}){let i=or.dirname(e),n=r.containedRoot?await aT(r.containedRoot,i):null;n||await He.mkdir(i,{recursive:!0});let a=or.join(i,`.${or.basename(e)}.${tT()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await He.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([He.lstat(a),He.realpath(a)]);if(await Sa(n),!l.isFile()||l.isSymbolicLink()||!Jl(s,l)||!zl(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(),!Jl(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await nT(a,c,n),await r.beforeCommit?.(),n){await Sa(n);let l=await He.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!iT(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await He.link(a,e),await He.unlink(a)):await He.rename(a,e),await oT(i)}catch(l){if(await o?.close(),!n)await He.rm(a,{force:!0});else try{await Sa(n),await He.rm(a,{force:!0})}catch{}throw l}}async function ge(e,t,r={}){await uN(e,t,r)}async function dN(e,t,r={}){await uN(e,t,r)}async function re(e,t,r={}){await ge(e,JSON.stringify(t,null,2)+`
|
|
145
|
-
`,r)}var ue=A(()=>{"use strict";
|
|
144
|
+
`,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=Bl(t),i=ka(r);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=Bl(t),i=ka(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Zy.Parser=ep});var nN=C(cs=>{"use strict";var eN=Bh(),PI=Zo(),ss=rs(),RI=Mf(),CI=U(),xI=Zh(),tN=tp();function rN(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new xI.LineCounter||null,prettyErrors:t}}function AI(e,t={}){let{lineCounter:r,prettyErrors:i}=rN(t),n=new tN.Parser(r?.addNewLine),a=new eN.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(ss.prettifyError(e,r)),s.warnings.forEach(ss.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function iN(e,t={}){let{lineCounter:r,prettyErrors:i}=rN(t),n=new tN.Parser(r?.addNewLine),a=new eN.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 ss.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(ss.prettifyError(e,r)),o.warnings.forEach(ss.prettifyError(e,r))),o}function _I(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=iN(e,r);if(!n)return null;if(n.warnings.forEach(a=>RI.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:i},r))}function II(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return CI.isDocument(e)&&!i?e.toString(r):new PI.Document(e,i,r).toString(r)}cs.parse=_I;cs.parseAllDocuments=AI;cs.parseDocument=iN;cs.stringify=II});var Cn=C(Z=>{"use strict";var TI=Bh(),jI=Zo(),$I=bh(),rp=rs(),OI=Do(),Si=U(),HI=wi(),DI=xe(),LI=Ni(),MI=bi(),FI=Ml(),BI=Xh(),VI=Zh(),qI=tp(),ql=nN(),aN=jo();Z.Composer=TI.Composer;Z.Document=jI.Document;Z.Schema=$I.Schema;Z.YAMLError=rp.YAMLError;Z.YAMLParseError=rp.YAMLParseError;Z.YAMLWarning=rp.YAMLWarning;Z.Alias=OI.Alias;Z.isAlias=Si.isAlias;Z.isCollection=Si.isCollection;Z.isDocument=Si.isDocument;Z.isMap=Si.isMap;Z.isNode=Si.isNode;Z.isPair=Si.isPair;Z.isScalar=Si.isScalar;Z.isSeq=Si.isSeq;Z.Pair=HI.Pair;Z.Scalar=DI.Scalar;Z.YAMLMap=LI.YAMLMap;Z.YAMLSeq=MI.YAMLSeq;Z.CST=FI;Z.Lexer=BI.Lexer;Z.LineCounter=VI.LineCounter;Z.Parser=qI.Parser;Z.parse=ql.parse;Z.parseAllDocuments=ql.parseAllDocuments;Z.parseDocument=ql.parseDocument;Z.stringify=ql.stringify;Z.visit=aN.visit;Z.visitAsync=aN.visitAsync});import{execFileSync as WI}from"child_process";import ls from"path";function Ei(e,t){return WI("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function zI(e,t){let r=ls.normalize(e),i=ls.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function ae(e){try{let t=ls.resolve(Ei(e,["rev-parse","--show-toplevel"])),i=Ei(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?ls.resolve(i.slice(9)):t,a=null;try{a=Ei(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!zI(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function oN(e){try{Ei(e,["rev-parse","--is-inside-work-tree"]);let t=Ei(e,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:ls.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}catch{return[]}}function nr(e){return oN(e).map(t=>t.root)}function us(e,t){try{return Ei(e,["check-ref-format","--branch",t]),Ei(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function Wr(e,t){try{let r=Ei(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}var Lt=A(()=>{"use strict"});import ip from"path";function UI(e){return e.toLowerCase().startsWith(".env")}function Sr(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>UI(i))?"environment-file":r.some(i=>GI.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>JI.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function np(e,t){let r=Sr(t);if(r)return r;let i=ip.resolve(e.projectRoot,...t.split("/")),n=ip.relative(e.projectRoot,e.nativeRoot).replaceAll("\\","/"),a=t.replaceAll("\\","/");return a===n||a.startsWith(`${n}/`)||i===ip.resolve(e.configFile)?"native-runtime":null}var JI,GI,ds=A(()=>{"use strict";JI=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),GI=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function Pi(e){return e!==0&&e!==0n&&e!=="0"}function Rt(e,t){return Pi(e.dev)&&Pi(t.dev)&&Pi(e.ino)&&Pi(t.ino)}function J(e,t){let r=Pi(e.dev)&&Pi(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Pi(e.ino)&&Pi(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var fs=A(()=>{"use strict"});var ar=A(()=>{"use strict";fs()});import{createHash as KI}from"node:crypto";import{promises as or}from"node:fs";import Mt from"node:path";import{TextDecoder as YI}from"node:util";function ap(e,t){let r=Mt.relative(e,t);return r===""||!Mt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Mt.sep}`)}function XI(e){let t=Mt.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})||Mt.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=Sr(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function QI(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function ZI(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Wl(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Rt(r,i)?J(r,i):J(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function sN(e){let t=await or.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await or.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function eT(e,t){let r=Mt.resolve(e),i=Mt.resolve(t);if(!ap(r,i))throw new Error("Native artifact path is outside its root");let n=[await sN(r)],a=r;for(let o of Mt.relative(r,i).split(Mt.sep).filter(Boolean)){a=Mt.join(a,o);let s=await sN(a);if(!ap(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function cN(e){for(let t of e){let r=await or.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!ZI(t,r)||await or.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function te(e){let t=XI(e.ref),r=e.maxBytes===null?null:QI(e.maxBytes??hs),i=Mt.resolve(e.root,...t.split("/")),n=await eT(e.root,Mt.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await or.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await or.realpath(i);if(!ap(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await or.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),or.lstat(i),or.realpath(i)]);if(await cN(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Wl(a,c)||!Wl(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,h=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let E=r===null?h.length:r+1-f,w=await s.read(h,0,Math.min(h.length,E),null);if(w.bytesRead===0)break;if(f+=w.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(h.subarray(0,w.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,p,v]=await Promise.all([s.stat(),or.lstat(i),or.realpath(i)]);if(await cN(n),!p.isFile()||p.isSymbolicLink()||v!==o||!Wl(c,m)||!Wl(c,p))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,f),N;try{N=new YI("utf-8",{fatal:!0}).decode(g)}catch(E){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:E})}return{ref:t,size:f,hash:e.includeHash===!1?null:KI("sha256").update(g).digest("hex"),text:N}}finally{await s.close()}}var hs,Ft=A(()=>{"use strict";ds();ar();hs=1024*1024});import{randomUUID as tT}from"crypto";import{promises as He}from"fs";import sr from"path";function zl(e,t){let r=sr.relative(e,t);return r===""||!sr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${sr.sep}`)}function rT(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Jl(e,t){return J({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function iT(e,t){return Jl(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function lN(e){let t=await He.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 He.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Sa(e){for(let t of e){let r=await He.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!rT(t,r)||await He.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function nT(e,t,r){let[i,n]=await Promise.all([He.lstat(e),He.realpath(e),r?Sa(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!Jl(i,t)||r&&!zl(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function aT(e,t){let r=sr.resolve(e),i=sr.resolve(t);if(!zl(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await lN(r)],a=sr.relative(r,i).split(sr.sep).filter(Boolean),o=r;for(let s of a){await Sa(n),o=sr.join(o,s);try{await He.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await lN(o);if(!zl(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Sa(n),n}async function oT(e){let t;try{t=await He.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function uN(e,t,r={}){let i=sr.dirname(e),n=r.containedRoot?await aT(r.containedRoot,i):null;n||await He.mkdir(i,{recursive:!0});let a=sr.join(i,`.${sr.basename(e)}.${tT()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await He.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([He.lstat(a),He.realpath(a)]);if(await Sa(n),!l.isFile()||l.isSymbolicLink()||!Jl(s,l)||!zl(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(),!Jl(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await nT(a,c,n),await r.beforeCommit?.(),n){await Sa(n);let l=await He.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!iT(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await He.link(a,e),await He.unlink(a)):await He.rename(a,e),await oT(i)}catch(l){if(await o?.close(),!n)await He.rm(a,{force:!0});else try{await Sa(n),await He.rm(a,{force:!0})}catch{}throw l}}async function ge(e,t,r={}){await uN(e,t,r)}async function dN(e,t,r={}){await uN(e,t,r)}async function re(e,t,r={}){await ge(e,JSON.stringify(t,null,2)+`
|
|
145
|
+
`,r)}var ue=A(()=>{"use strict";ar()});import Ri from"path";function wN(e,t){return Ea[t][e]}function dT(e,t,r,i){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 Ea.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in Ea.en)return s}if(a===4&&t==="knowledge"&&i==="remote"){let s=`knowledge.remote.${o}`;if(s in Ea.en)return s}if(a===4&&t==="knowledge"&&i==="local"){let s=`knowledge.local.${o}`;if(s in Ea.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"&&r==="snapshot"){let s=`native.snapshot.${o}`;if(s in Ea.en)return s}return null}function vs(e,t){let r=[],i=null,n=null,a=null;for(let o of(0,ps.stringify)(e).trimEnd().split(`
|
|
146
146
|
`)){let s=dT(o,i,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of wN(s,t).split(`
|
|
147
147
|
`))r.push(`${c}${l}`)}r.push(o),/^[a-z_]+:/u.test(o)?(o.startsWith("native:")?i="native":o.startsWith("classic:")?i="classic":o.startsWith("hook:")?i="hook":o.startsWith("memory:")?i="memory":o.startsWith("knowledge:")?i="knowledge":i=null,n=null,a=null):/^ {2}[a-z_]+:/u.test(o)&&(i==="native"&&(n=o.startsWith(" snapshot:")?"snapshot":null),i==="knowledge"&&(a=o.startsWith(" local:")?"local":o.startsWith(" remote:")?"remote":null))}return r.push(""),r.join(`
|
|
148
|
-
`)}function fT(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Ri.posix.isAbsolute(r)||Ri.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function Pa(e){let t=fT(e,"native.artifact_root");return t.length===0?".":t.join("/")}function yN(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function Yl(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||Ri.posix.isAbsolute(i)||Ri.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function Wr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function NN(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function Xl(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>Ul)throw new Error(`${t} exceeds ${Ul} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>Kl)throw new Error(`${t} contains more than ${Kl} wildcard tokens`);return e}function mN(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>Xl(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function op(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function hT(e){if(e===void 0)return{...sr,include:[...sr.include],exclude:[...sr.exclude]};let t=Wr(e,"native.snapshot");return{include:mN(t.include,"native.snapshot.include",sr.include),exclude:mN(t.exclude,"native.snapshot.exclude",sr.exclude),max_files:op(t.max_files,sr.max_files,"native.snapshot.max_files"),max_total_bytes:op(t.max_total_bytes,sr.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:op(t.max_duration_ms,sr.max_duration_ms,"native.snapshot.max_duration_ms")}}function pT(e){if(e===void 0)return;let t=Wr(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=Wr(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:r,fromArtifactRoot:Pa(i),toArtifactRoot:Pa(n),stage:a,...o?{cleanup:o}:{}}}function mT(e){if(e===void 0)return;let t=Wr(e,"native.finish");if(t.pull_request===void 0)return{};let r=Wr(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Ri.posix.isAbsolute(i[0])||Ri.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??sT;if(!Number.isSafeInteger(n)||n<1||n>pN)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${pN}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function vT(e,t={}){let r=Wr(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??vN;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=pT(r.pending_root_move),c=mT(r.finish);return{artifact_root:Pa(i),language:NN(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:hT(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function gT(e){let t=Wr(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:yN(t.artifact_layout),language:NN(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function wT(e){let r=Wr(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>Yl(i,`hook.allow_paths[${n}]`)))]}}function yT(e){if(e===void 0)return{...Gl};let t=Wr(e,"memory"),r=t.learning??Gl.learning,i=t.retrieval??Gl.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function sp(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function NT(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Ri.posix.isAbsolute(r)||Ri.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>fN)throw new Error(`${t} exceeds ${fN} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>hN)throw new Error(`${t} contains more than ${hN} wildcard tokens`);return r}function bT(e){let r=sp(e,"knowledge.local").include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(r.map((i,n)=>NT(i,`knowledge.local.include[${n}]`)))]}}function kT(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function ST(e){let t=sp(e,"knowledge.remote"),r=kT(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function ET(e){if(e===void 0)return{...gN};let t=sp(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:bT(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:ST(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function PT(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function RT(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let 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:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function Ra(e,t={}){let r=(0,ps.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=PT(n.ambient_resume),o=n.hook===void 0?void 0:wT(n.hook),s=yT(n.memory),c=ET(n.knowledge),l=n.native===void 0?void 0:vT(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:gT(n.classic),d=RT(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 bN(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 kN(e){let t=e.knowledge??{...gN};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...Gl},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:bN(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 Ct(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function gs(e,t){let r=kN(t),i=Ra((0,ps.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...Ct(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=Ct(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=Ct(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local&&i.knowledge.local.include.length>0?o.local={...Ct(a.local),include:[...i.knowledge.local.include]}:delete o.local,i.knowledge.remote){let c={...Ct(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=Ct(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures};if(i.native.finish?.pull_request){let s=Ct(a.finish);o.finish={...s,pull_request:{...Ct(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...Ct(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=Ct(a.pending_root_move),c=bN(i.native.pending_root_move),l=Ct(s.cleanup),u=Ct(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...Ct(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition}),n}var ps,ms,Ul,Kl,fN,hN,vN,Gl,gN,sT,pN,cT,lT,uT,sr,Ea,Ci=A(()=>{"use strict";ps=da(Cn(),1),ms=64*1024,Ul=1024,Kl=64,fN=1024,hN=64,vN=5,Gl={learning:!0,retrieval:!0},gN={provider:"local"},sT=12e4,pN=6e5,cT=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".devin/skills/**",".dsh/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],lT=["**/.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"],uT=[...cT,...lT].sort((e,t)=>e.localeCompare(t,"en")),sr={include:["**/*"],exclude:[...uT],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Ea={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.
|
|
148
|
+
`)}function fT(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Ri.posix.isAbsolute(r)||Ri.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function Pa(e){let t=fT(e,"native.artifact_root");return t.length===0?".":t.join("/")}function yN(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function Yl(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||Ri.posix.isAbsolute(i)||Ri.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function zr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function NN(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function Xl(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>Ul)throw new Error(`${t} exceeds ${Ul} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>Kl)throw new Error(`${t} contains more than ${Kl} wildcard tokens`);return e}function mN(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>Xl(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function op(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function hT(e){if(e===void 0)return{...cr,include:[...cr.include],exclude:[...cr.exclude]};let t=zr(e,"native.snapshot");return{include:mN(t.include,"native.snapshot.include",cr.include),exclude:mN(t.exclude,"native.snapshot.exclude",cr.exclude),max_files:op(t.max_files,cr.max_files,"native.snapshot.max_files"),max_total_bytes:op(t.max_total_bytes,cr.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:op(t.max_duration_ms,cr.max_duration_ms,"native.snapshot.max_duration_ms")}}function pT(e){if(e===void 0)return;let t=zr(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=zr(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:r,fromArtifactRoot:Pa(i),toArtifactRoot:Pa(n),stage:a,...o?{cleanup:o}:{}}}function mT(e){if(e===void 0)return;let t=zr(e,"native.finish");if(t.pull_request===void 0)return{};let r=zr(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Ri.posix.isAbsolute(i[0])||Ri.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??sT;if(!Number.isSafeInteger(n)||n<1||n>pN)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${pN}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function vT(e,t={}){let r=zr(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??vN;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=pT(r.pending_root_move),c=mT(r.finish);return{artifact_root:Pa(i),language:NN(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:hT(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function gT(e){let t=zr(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:yN(t.artifact_layout),language:NN(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function wT(e){let r=zr(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>Yl(i,`hook.allow_paths[${n}]`)))]}}function yT(e){if(e===void 0)return{...Gl};let t=zr(e,"memory"),r=t.learning??Gl.learning,i=t.retrieval??Gl.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function sp(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function NT(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Ri.posix.isAbsolute(r)||Ri.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>fN)throw new Error(`${t} exceeds ${fN} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>hN)throw new Error(`${t} contains more than ${hN} wildcard tokens`);return r}function bT(e){let r=sp(e,"knowledge.local").include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(r.map((i,n)=>NT(i,`knowledge.local.include[${n}]`)))]}}function kT(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function ST(e){let t=sp(e,"knowledge.remote"),r=kT(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function ET(e){if(e===void 0)return{...gN};let t=sp(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:bT(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:ST(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function PT(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function RT(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let 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:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function Ra(e,t={}){let r=(0,ps.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=PT(n.ambient_resume),o=n.hook===void 0?void 0:wT(n.hook),s=yT(n.memory),c=ET(n.knowledge),l=n.native===void 0?void 0:vT(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:gT(n.classic),d=RT(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 bN(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 kN(e){let t=e.knowledge??{...gN};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...Gl},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:bN(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 Ct(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function gs(e,t){let r=kN(t),i=Ra((0,ps.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...Ct(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=Ct(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=Ct(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local&&i.knowledge.local.include.length>0?o.local={...Ct(a.local),include:[...i.knowledge.local.include]}:delete o.local,i.knowledge.remote){let c={...Ct(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=Ct(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures};if(i.native.finish?.pull_request){let s=Ct(a.finish);o.finish={...s,pull_request:{...Ct(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...Ct(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=Ct(a.pending_root_move),c=bN(i.native.pending_root_move),l=Ct(s.cleanup),u=Ct(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...Ct(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition}),n}var ps,ms,Ul,Kl,fN,hN,vN,Gl,gN,sT,pN,cT,lT,uT,cr,Ea,Ci=A(()=>{"use strict";ps=da(Cn(),1),ms=64*1024,Ul=1024,Kl=64,fN=1024,hN=64,vN=5,Gl={learning:!0,retrieval:!0},gN={provider:"local"},sT=12e4,pN=6e5,cT=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".devin/skills/**",".dsh/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],lT=["**/.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"],uT=[...cT,...lT].sort((e,t)=>e.localeCompare(t,"en")),cr={include:["**/*"],exclude:[...uT],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Ea={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.
|
|
149
149
|
# 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.
|
|
150
150
|
# learning: true | false`,"memory.retrieval":`# Allows personal memories to be injected into Agent context for this project.
|
|
151
151
|
# retrieval: true | false`,knowledge:"# Project knowledge retrieval provider used by ordinary Comet tasks.","knowledge.provider":`# Provider for project knowledge.
|
|
@@ -169,45 +169,45 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
|
|
|
169
169
|
# 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。
|
|
170
170
|
# 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
|
|
171
171
|
# 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
|
|
172
|
-
# 可选值:true | false`}}});import{constants as Ql,promises as xn}from"fs";function cp(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function SN(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ws(e){return{dev:e.dev,ino:e.ino,birthtime:cp(e)}}function Zl(e,t){let r=ws(e),i=ws(t);return Rt(r,i)?J(r,i):J(r,i)&&cp(e)===cp(t)&&SN(e)===SN(t)&&e.size===t.size}async function An(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await xn.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new cr("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new cr("too-large",`${i} exceeds ${t} bytes`);let o=await xn.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ws(a)});let s=process.platform==="win32"?Ql.O_RDONLY:Ql.O_RDONLY|Ql.O_NOFOLLOW|Ql.O_NONBLOCK,c;try{c=await xn.open(e,s)}catch(l){throw l.code==="ELOOP"?new cr("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),xn.lstat(e,{bigint:n}),xn.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Zl(a,l)||!Zl(a,u))throw new cr("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:ws(l)}),await r.hooks?.afterOpen?.();let f=[],h=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let N=t+1-h,{bytesRead:E}=await c.read(m,0,Math.min(m.length,N),null);if(E===0)break;if(h+=E,h>t)throw new cr("too-large",`${i} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,E)))}await r.hooks?.beforeFinalCheck?.();let[p,v,g]=await Promise.all([c.stat({bigint:n}),xn.lstat(e,{bigint:n}),xn.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!Zl(a,p)||!Zl(a,v))throw new cr("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:ws(p)}),{bytes:Buffer.concat(f,h),stat:p,realPath:g}}finally{await c.close()}}var cr,ys=A(()=>{"use strict";fs();cr=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as eu}from"fs";import xi from"path";function CT(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function lp(e,t){let r=xi.relative(e,t);return r===""||!xi.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${xi.sep}`)}async function EN(e,t){let r=xi.resolve(e),i=await eu.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return eu.realpath(r)}async function PN(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=xi.join(n,r[a]);let o;try{o=await eu.lstat(n)}catch(u){if(CT(u))return{exists:!1,kind:"missing"};throw u}let s=xi.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await eu.realpath(n);if(!lp(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Ca(e,t,r){let i=Yl(t,r.label),n=xi.resolve(e),a=await EN(n,r.label),o=i.split("/"),s=xi.resolve(n,...o);if(!lp(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await PN(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Ai(e,t,r,i){let n=await Ca(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await EN(n.projectRoot,i.label);return An(n.target,r,{...i,verify:async(o,s)=>{if(!lp(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await PN(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var _n=A(()=>{"use strict";ys();Ci()});import{createHash as xT}from"crypto";function up(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function AT(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function tu(e,t={}){return(await bs(e,t)).document}async function RN(e){try{return(await Ai(e,Ns,ms,{label:Ns})).bytes}catch(t){if(AT(t))return null;throw t}}function CN(e){return e?{exists:!0,sha256:xT("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function ru(e){return CN(await RN(e))}async function bs(e,t={}){let r=await RN(e);return{document:r?Ra(r.toString("utf8"),t):null,identity:CN(r)}}async function dp(e){return(await tu(e))?.config??null}var Ns,xa=A(()=>{"use strict";Ci();_n();Ns=".comet/config.yaml"});var Aa=A(()=>{"use strict";fs()});var X1,fp=A(()=>{"use strict";Aa();xa();_n();X1=16*1024});async function hp(e,t){if(!t)return;let r=await ru(e);if(!up(r,t))throw new Error("Project config changed before commit; rerun the operation")}var pp=A(()=>{"use strict";Aa();Ci();xa();_n();fp()});import{existsSync as xN,promises as _i}from"fs";import Y from"path";import jT from"os";async function mp(e){try{return await _i.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function OT(e){try{let t=await _i.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Ia(e,t){let r=Y.relative(e,t);return r===""||!Y.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Y.sep}`)}async function _a(e){let t=[],r=e;for(;!await mp(r);){let n=Y.dirname(r);if(n===r)break;t.push(Y.basename(r)),r=n}let i=await _i.realpath(r);return Y.resolve(i,...t.reverse())}async function vp(e){try{return(await _i.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function gp(e){let t=Y.resolve(e);try{(await _i.stat(t)).isDirectory()||(t=Y.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=Y.resolve(jT.homedir());for(;;){if(!(t===i&&r!==i)){let o=Y.join(t,...iu.split("/")),s=t===r||await OT(o);if(await mp(o)&&s)return t}if(await mp(Y.join(t,".git")))return t;let a=Y.dirname(t);if(a===t)return r;t=a}}function nu(e){return Pa(e)}async function HT(e,t){let r=nu(t),i=Y.resolve(e,...r.split("/")),n=await _i.realpath(e),a=await _a(i);if(!Ia(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Ke(e,t){let r=nu(t),i=await HT(e,r),n=Y.join(i,"comet");if(await vp(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([_a(i),_a(n)]);if(!Ia(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=Y.resolve(e),c=Y.join(s,".comet","runtime","native");if(await vp(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([_i.realpath(s),_a(c)]);if(!Ia(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:Y.join(e,...iu.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:Y.join(n,"specs"),changesDir:Y.join(n,"changes"),archiveDir:Y.join(n,"archive"),runtimeDir:c,changesRuntimeDir:Y.join(c,"changes"),locksDir:Y.join(c,"locks"),transactionsDir:Y.join(c,"transactions")}}function _N(e){if(!$T.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Ye(e,t){_N(t);let r=Y.join(e.changesRuntimeDir,t);if(!D(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function In(e,t){_N(t);let r=Y.join(e.changesDir,t,"runtime");if(!D(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function M(e,t){let r=Ye(e,t);if(xN(r))return r;let i=In(e,t);return xN(i)?i:r}async function AN(e){try{let t=await _i.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Ss(e,t){let r=Ye(e,t),i=In(e,t),[n,a]=await Promise.all([AN(r),AN(i)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:r,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:i,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:r,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:r}:a==="directory"?{status:"available",layout:"legacy",path:i}:{status:"missing",layout:"missing",path:r}}function Ii(e,t){if(!t.startsWith("runtime/")||Y.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=Y.resolve(e,...t.slice(8).split("/"));if(!D(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function $(e,t){let r=Y.resolve(t);if(D(e.runtimeDir,r))return e.runtimeDir;if(D(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function D(e,t){return Ia(Y.resolve(e),Y.resolve(t))}async function T(e,t){let r=Y.resolve(e),i=Y.resolve(t);if(!Ia(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await vp(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([_a(r),_a(i)]);if(!Ia(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var iu,$T,Q=A(()=>{"use strict";Ci();iu=".comet/config.yaml",$T=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import DT from"path";async function Ee(e){let t=(await tu(e))?.config??null;return t?.native?t:null}async function Ta(e){let t=await Ee(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 Ti(e,t,r={}){let i=await bs(e,{allowPartialProject:!0}),n=gs(i.document?.value??{},t),a=DT.join(e,...iu.split("/"));await ge(a,vs(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await hp(e,i.identity)}})}var wp,au,ot=A(()=>{"use strict";Ci();xa();pp();ue();Q();wp=sr,au=Xl});import{AsyncLocalStorage as LT}from"async_hooks";import{randomUUID as $N}from"crypto";import{promises as Bt}from"fs";import ON from"os";import we from"path";function FT(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function BT(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return r}function HN(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 su(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Rt(r,i)?J(r,i):J(r,i)&&e.size===t.size}function cu(e,t){return su(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function VT(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&&cu(e.identity,t.identity)}async function lr(e){let t,r;try{let i=await An(e,TN,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof cr?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${TN} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:BT(JSON.parse(t.toString("utf8")),e),identity:HN(r)}}async function qT(e){return(await lr(e))?.owner??null}function Np(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==ON.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=KT(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function WT(e,t){try{await Bt.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await Bt.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function lu(e,t){let r=await lr(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!cu(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Bt.mkdir(t,{recursive:!0});let i=we.join(t,`${we.basename(e.file)}.${e.owner.id}.${$N()}.removed`);try{await Bt.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await lr(i);if(!n||n.owner.id!==e.owner.id||!su(n.identity,e.identity))throw await WT(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Bt.rm(i,{force:!0}),"removed"}function DN(e){return{id:$N(),pid:process.pid,hostname:ON.hostname(),createdAt:new Date().toISOString(),operation:e}}async function LN(e,t){let r;try{r=await Bt.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await qT(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(t,null,2)+`
|
|
173
|
-
`,"utf8"),await r.sync(),i=HN(await r.stat({bigint:!0}))}finally{await r.close()}let n=await
|
|
174
|
-
${Ps(t)}`).digest("hex")}var Xe=A(()=>{"use strict"});import FN from"node:path";function aj(e,t){return e<t?-1:e>t?1:0}function qN(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{value:r,truncated:!0}}function WN(e,t){let r=t.toString(36),i=O("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${r}.${i}`}function oj(e){if(!ij.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=nj.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 r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==O("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:r}))throw new Error("Native acceptance cursor integrity check failed");return r}function sj(e,t){let r=qN(e.text,
|
|
172
|
+
# 可选值:true | false`}}});import{constants as Ql,promises as xn}from"fs";function cp(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function SN(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ws(e){return{dev:e.dev,ino:e.ino,birthtime:cp(e)}}function Zl(e,t){let r=ws(e),i=ws(t);return Rt(r,i)?J(r,i):J(r,i)&&cp(e)===cp(t)&&SN(e)===SN(t)&&e.size===t.size}async function An(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await xn.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new lr("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new lr("too-large",`${i} exceeds ${t} bytes`);let o=await xn.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ws(a)});let s=process.platform==="win32"?Ql.O_RDONLY:Ql.O_RDONLY|Ql.O_NOFOLLOW|Ql.O_NONBLOCK,c;try{c=await xn.open(e,s)}catch(l){throw l.code==="ELOOP"?new lr("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),xn.lstat(e,{bigint:n}),xn.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Zl(a,l)||!Zl(a,u))throw new lr("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:ws(l)}),await r.hooks?.afterOpen?.();let f=[],h=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let N=t+1-h,{bytesRead:E}=await c.read(m,0,Math.min(m.length,N),null);if(E===0)break;if(h+=E,h>t)throw new lr("too-large",`${i} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,E)))}await r.hooks?.beforeFinalCheck?.();let[p,v,g]=await Promise.all([c.stat({bigint:n}),xn.lstat(e,{bigint:n}),xn.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!Zl(a,p)||!Zl(a,v))throw new lr("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:ws(p)}),{bytes:Buffer.concat(f,h),stat:p,realPath:g}}finally{await c.close()}}var lr,ys=A(()=>{"use strict";fs();lr=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as eu}from"fs";import xi from"path";function CT(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function lp(e,t){let r=xi.relative(e,t);return r===""||!xi.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${xi.sep}`)}async function EN(e,t){let r=xi.resolve(e),i=await eu.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return eu.realpath(r)}async function PN(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=xi.join(n,r[a]);let o;try{o=await eu.lstat(n)}catch(u){if(CT(u))return{exists:!1,kind:"missing"};throw u}let s=xi.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await eu.realpath(n);if(!lp(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Ca(e,t,r){let i=Yl(t,r.label),n=xi.resolve(e),a=await EN(n,r.label),o=i.split("/"),s=xi.resolve(n,...o);if(!lp(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await PN(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Ai(e,t,r,i){let n=await Ca(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await EN(n.projectRoot,i.label);return An(n.target,r,{...i,verify:async(o,s)=>{if(!lp(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await PN(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var _n=A(()=>{"use strict";ys();Ci()});import{createHash as xT}from"crypto";function up(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function AT(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function tu(e,t={}){return(await bs(e,t)).document}async function RN(e){try{return(await Ai(e,Ns,ms,{label:Ns})).bytes}catch(t){if(AT(t))return null;throw t}}function CN(e){return e?{exists:!0,sha256:xT("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function ru(e){return CN(await RN(e))}async function bs(e,t={}){let r=await RN(e);return{document:r?Ra(r.toString("utf8"),t):null,identity:CN(r)}}async function dp(e){return(await tu(e))?.config??null}var Ns,xa=A(()=>{"use strict";Ci();_n();Ns=".comet/config.yaml"});var Aa=A(()=>{"use strict";fs()});var X1,fp=A(()=>{"use strict";Aa();xa();_n();X1=16*1024});async function hp(e,t){if(!t)return;let r=await ru(e);if(!up(r,t))throw new Error("Project config changed before commit; rerun the operation")}var pp=A(()=>{"use strict";Aa();Ci();xa();_n();fp()});import{existsSync as xN,promises as _i}from"fs";import Y from"path";import jT from"os";async function mp(e){try{return await _i.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function OT(e){try{let t=await _i.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Ia(e,t){let r=Y.relative(e,t);return r===""||!Y.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Y.sep}`)}async function _a(e){let t=[],r=e;for(;!await mp(r);){let n=Y.dirname(r);if(n===r)break;t.push(Y.basename(r)),r=n}let i=await _i.realpath(r);return Y.resolve(i,...t.reverse())}async function vp(e){try{return(await _i.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function gp(e){let t=Y.resolve(e);try{(await _i.stat(t)).isDirectory()||(t=Y.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=Y.resolve(jT.homedir());for(;;){if(!(t===i&&r!==i)){let o=Y.join(t,...iu.split("/")),s=t===r||await OT(o);if(await mp(o)&&s)return t}if(await mp(Y.join(t,".git")))return t;let a=Y.dirname(t);if(a===t)return r;t=a}}function nu(e){return Pa(e)}async function HT(e,t){let r=nu(t),i=Y.resolve(e,...r.split("/")),n=await _i.realpath(e),a=await _a(i);if(!Ia(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Ke(e,t){let r=nu(t),i=await HT(e,r),n=Y.join(i,"comet");if(await vp(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([_a(i),_a(n)]);if(!Ia(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=Y.resolve(e),c=Y.join(s,".comet","runtime","native");if(await vp(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([_i.realpath(s),_a(c)]);if(!Ia(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:Y.join(e,...iu.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:Y.join(n,"specs"),changesDir:Y.join(n,"changes"),archiveDir:Y.join(n,"archive"),runtimeDir:c,changesRuntimeDir:Y.join(c,"changes"),locksDir:Y.join(c,"locks"),transactionsDir:Y.join(c,"transactions")}}function _N(e){if(!$T.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Ye(e,t){_N(t);let r=Y.join(e.changesRuntimeDir,t);if(!D(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function In(e,t){_N(t);let r=Y.join(e.changesDir,t,"runtime");if(!D(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function M(e,t){let r=Ye(e,t);if(xN(r))return r;let i=In(e,t);return xN(i)?i:r}async function AN(e){try{let t=await _i.lstat(e);return t.isDirectory()&&!t.isSymbolicLink()?"directory":"invalid"}catch(t){if(t.code==="ENOENT")return"missing";throw t}}async function Ss(e,t){let r=Ye(e,t),i=In(e,t),[n,a]=await Promise.all([AN(r),AN(i)]);return n==="invalid"?{status:"invalid",layout:"project-local",path:r,message:"Native Runtime path must be a real directory"}:a==="invalid"?{status:"invalid",layout:"legacy",path:i,message:"Legacy Native Runtime path must be a real directory"}:n==="directory"&&a==="directory"?{status:"invalid",layout:"project-local",path:r,message:"Both project-local and legacy Native Runtime directories exist"}:n==="directory"?{status:"available",layout:"project-local",path:r}:a==="directory"?{status:"available",layout:"legacy",path:i}:{status:"missing",layout:"missing",path:r}}function Ii(e,t){if(!t.startsWith("runtime/")||Y.isAbsolute(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Native Runtime ref: ${t}`);let r=Y.resolve(e,...t.slice(8).split("/"));if(!D(e,r))throw new Error(`Native Runtime ref escaped: ${t}`);return r}function $(e,t){let r=Y.resolve(t);if(D(e.runtimeDir,r))return e.runtimeDir;if(D(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function D(e,t){return Ia(Y.resolve(e),Y.resolve(t))}async function T(e,t){let r=Y.resolve(e),i=Y.resolve(t);if(!Ia(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await vp(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([_a(r),_a(i)]);if(!Ia(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var iu,$T,Q=A(()=>{"use strict";Ci();iu=".comet/config.yaml",$T=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import DT from"path";async function Ee(e){let t=(await tu(e))?.config??null;return t?.native?t:null}async function Ta(e){let t=await Ee(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 Ti(e,t,r={}){let i=await bs(e,{allowPartialProject:!0}),n=gs(i.document?.value??{},t),a=DT.join(e,...iu.split("/"));await ge(a,vs(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await hp(e,i.identity)}})}var wp,au,ot=A(()=>{"use strict";Ci();xa();pp();ue();Q();wp=cr,au=Xl});import{AsyncLocalStorage as LT}from"async_hooks";import{randomUUID as $N}from"crypto";import{promises as Bt}from"fs";import ON from"os";import we from"path";function FT(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function BT(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return r}function HN(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 su(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Rt(r,i)?J(r,i):J(r,i)&&e.size===t.size}function cu(e,t){return su(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function VT(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&&cu(e.identity,t.identity)}async function ur(e){let t,r;try{let i=await An(e,TN,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof lr?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${TN} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:BT(JSON.parse(t.toString("utf8")),e),identity:HN(r)}}async function qT(e){return(await ur(e))?.owner??null}function Np(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==ON.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=KT(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function WT(e,t){try{await Bt.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await Bt.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function lu(e,t){let r=await ur(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!cu(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Bt.mkdir(t,{recursive:!0});let i=we.join(t,`${we.basename(e.file)}.${e.owner.id}.${$N()}.removed`);try{await Bt.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await ur(i);if(!n||n.owner.id!==e.owner.id||!su(n.identity,e.identity))throw await WT(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Bt.rm(i,{force:!0}),"removed"}function DN(e){return{id:$N(),pid:process.pid,hostname:ON.hostname(),createdAt:new Date().toISOString(),operation:e}}async function LN(e,t){let r;try{r=await Bt.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await qT(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(t,null,2)+`
|
|
173
|
+
`,"utf8"),await r.sync(),i=HN(await r.stat({bigint:!0}))}finally{await r.close()}let n=await ur(e);if(!i||!n||n.owner.id!==t.id||!su(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function zT(e,t){let r=await T(e.runtimeDir,e.locksDir);await Bt.mkdir(r,{recursive:!0});let i=await T(e.runtimeDir,we.join(r,yp));await Bt.mkdir(i,{recursive:!0});let n=DN(t),a=we.join(i,`.${n.id}.tmp`),o=we.join(i,`${n.id}.claim`);try{let s=await LN(a,n);await Bt.rename(a,o);let c=await ur(o);if(!c||!su(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await Bt.rm(a,{force:!0})}}async function JT(e){let t=we.dirname(e.file),r=!1,i=we.basename(e.file);for(let n of await Bt.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=we.join(t,n.name);if(we.resolve(a)!==we.resolve(e.file))try{let o=await ur(a),s=Np(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await lu(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function MN(e){let t=await ur(e.file);if(t){if(t.owner.id!==e.owner.id||!cu(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await lu(t,we.dirname(e.file))}}async function GT(e,t){let r=Date.now()+MT;for(;;){let i=await zT(e,t);if(!await JT(i))return i;if(await MN(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function UT(e){let t=ou.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return ou.set(e,n),await t,()=>{r(),ou.get(e)===n&&ou.delete(e)}}async function uu(e,t,r){let i=we.resolve(e.locksDir),n=jN.getStore();if(n?.has(i))return r();let a=await UT(i);try{let o=await GT(e,t),s=new Map(n??[]);return s.set(i,o),await jN.run(s,async()=>{try{return await r()}finally{await MN(o)}})}finally{a()}}async function ja(e,t,r){let i=[...new Map(e.map(a=>[we.resolve(a.locksDir),a])).values()].sort((a,o)=>we.resolve(a.locksDir).localeCompare(we.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?uu(o,t,()=>n(a+1)):r()};return n(0)}async function ji(e,t,r){return uu(e,`acquire ${t}`,async()=>{let i=await T(e.runtimeDir,e.locksDir);await Bt.mkdir(i,{recursive:!0});let n=await T(e.runtimeDir,we.join(i,FT(t))),a=DN(r),o=await LN(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function $i(e){await ur(e.file)&&await uu({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${we.basename(e.file)}`,async()=>{let t=await ur(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!cu(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=we.join(e.locksDir,yp);await lu(t,r)})}function KT(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function Es(e){return Np(await ur(e))}async function bp(e,t,r){return uu(e,`take over ${we.basename(t)}`,async()=>{let i=await T(e.runtimeDir,e.locksDir),n=await T(e.runtimeDir,t);if(we.resolve(we.dirname(n))!==we.resolve(i))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let a=await ur(n),o=Np(a);if(o.status==="missing")return{status:"missing"};if(r&&!VT(r,o))return{status:"changed",diagnosis:o};if(o.status!=="stale"||!a)return{status:"changed",diagnosis:o};let s=we.join(i,yp);return await lu(a,s)==="removed"?{status:"removed",owner:a.owner}:{status:"missing"}})}var TN,yp,MT,jN,ou,Tn=A(()=>{"use strict";ys();Q();ar();TN=16*1024,yp=".coordinator",MT=5e3,jN=new LT,ou=new Map});import{createHash as YT}from"crypto";function dr(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function XT(e,t){t.has(e)&&dr("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||dr("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&dr("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&dr("symbol properties are not supported"),`[${e.map(i=>kp(i,t)).join(",")}]`}finally{t.delete(e)}}function QT(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&dr("only plain objects are supported"),t.has(e)&&dr("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&dr("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&dr("accessor properties are not supported"),`${JSON.stringify(o)}:${kp(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function kp(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)||dr("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?XT(e,t):QT(e,t);case"bigint":case"function":case"symbol":case"undefined":return dr(`${typeof e} values are not supported`)}return dr("unsupported value type")}function Ps(e){return kp(e,new Set)}function O(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 YT("sha256").update(`${e}
|
|
174
|
+
${Ps(t)}`).digest("hex")}var Xe=A(()=>{"use strict"});import FN from"node:path";function aj(e,t){return e<t?-1:e>t?1:0}function qN(e,t){if(Buffer.byteLength(e,"utf8")<=t)return{value:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{value:r,truncated:!0}}function WN(e,t){let r=t.toString(36),i=O("comet.native.acceptance-cursor.v1",{acceptanceHash:e,offset:t});return`native-acceptance-v1.${e}.${r}.${i}`}function oj(e){if(!ij.test(e.acceptanceHash))throw new Error("Native acceptance page hash is invalid");if(e.cursor===void 0||e.cursor===null)return 0;let t=nj.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 r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.toString(36)!==t[2])throw new Error("Native acceptance cursor offset is invalid");if(t[3]!==O("comet.native.acceptance-cursor.v1",{acceptanceHash:e.acceptanceHash,offset:r}))throw new Error("Native acceptance cursor integrity check failed");return r}function sj(e,t){let r=qN(e.text,Jr.maxTextBytes),i=e.context.slice(0,Jr.maxContextItems).map(n=>qN(n,Jr.maxContextItemBytes));return{id:e.id,kind:e.kind,source:e.source,context:i.map(n=>n.value),text:r.value,contextTruncated:e.context.length>i.length||i.some(n=>n.truncated),textTruncated:r.truncated,verificationStatus:t}}function JN(e){let t=oj({acceptanceHash:e.acceptanceHash,total:e.criteria.length,cursor:e.cursor}),r=[],i=[...new Set(e.failedCheckIds??[])].sort(aj),n=i.slice(0,Jr.maxFailedCheckIds),a=e.criteria.slice(t,t+Jr.maxItems);for(let c of a){let l=[...r,sj(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:i.length>n.length,nextCursor:u<e.criteria.length?WN(e.acceptanceHash,u):null,limits:{...Jr}};if(Buffer.byteLength(JSON.stringify(d),"utf8")>Jr.maxSerializedBytes){if(r.length===0)throw new Error("Native acceptance criterion exceeds the page serialization budget");break}r.push(l.at(-1))}if(e.criteria.length>0&&r.length===0)throw new Error("Native acceptance page could not project its next criterion");let o=t+r.length,s={schema:"comet.native.acceptance-page.v1",acceptanceHash:e.acceptanceHash,total:e.criteria.length,offset:t,items:r,failedAcceptanceIds:r.filter(c=>c.verificationStatus==="failed").map(c=>c.id),missingAcceptanceIds:r.filter(c=>c.verificationStatus==="missing").map(c=>c.id),failedCheckIds:n,failedCheckIdsTruncated:i.length>n.length,nextCursor:o<e.criteria.length?WN(e.acceptanceHash,o):null,limits:{...Jr}};if(Buffer.byteLength(JSON.stringify(s),"utf8")>Jr.maxSerializedBytes)throw new Error("Native acceptance page exceeds its serialization budget");return s}function Ep(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 Sp(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function zN(e){return e.includes("-->")||e.includes("--!>")}function*$a(e){let t=null,r=!1,i=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
176
|
`,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=Sp(l,t);else if(r)zN(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let d=Sp(l,null);if(d!==null)t=d;else{let f=l.trimStart();if(f.startsWith("<!--")&&!zN(f))r=!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)&&(i=h[1])}}}if(c===-1)break;o=c+1}}function cj(e){return[...$a(e)].map(({line:t,body:r})=>({line:t,body:r}))}function Rs(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function lj(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Pp(e,t,r,i=[],n="content-hash"){let a=Rs(r),o=t.replaceAll("\\","/").trim(),s=i.map(Rs);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-${O(ZT,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Rp(e,t,r="content-hash"){let i=new Set;for(let n of e){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(a)}return e}function uj(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of $a(e)){n=s+1;let c=o?Ep(a):null;c?.level===1&&(Wc(c.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function du(e,t="brief.md",r=Cs.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=uj(e);if(n===null)return[];let a=null;for(let{line:l,body:u,index:d}of $a(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>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:u,index:d}of $a(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(),Rp(o.map(l=>Pp("brief-example",t,l.join(`
|
|
177
177
|
`),[],i)),"Brief",i)}function fu(e,t="spec.md",r=Cs.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(Pp("spec-scenario",t,[o.title,...o.body].join(`
|
|
178
178
|
`),o.context,i)),o=null}};for(let{line:c,body:l}of $a(e)){let u=l?Ep(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=Rs(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(),Rp(n,"Specification",i)}function GN(e,t="spec.md",r=Cs.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=null,c=()=>{if(s!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(Pp("spec-must",t,s.parts.join(" "),s.context,i)),s=null}},l=()=>a.some(u=>/^(?:non-?goals?|非目标)$/iu.test(u.text.trim()));for(let{line:u,body:d}of $a(e)){let f=d?Ep(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||Sp(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 m=/^\s*(?:[-*+]|\d+[.)])[ \t]+(.+)$/u.exec(u);if(m){c(),s={parts:[m[1]],context:a.map(p=>p.text)};continue}if(/^\|.*\|$/u.test(h)){c(),s={parts:[h],context:a.map(p=>p.text)},c();continue}s===null?s={parts:[h],context:a.map(p=>p.text)}:s.parts.push(h)}return c(),Rp(n,"Specification mandatory requirements",i)}function dj(e,t){let r=e.trim().replaceAll("\\","/");if(r.length===0||lj(r)||FN.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~|[A-Za-z][A-Za-z0-9+.-]*:)/u.test(r)||r.split("/").includes(".."))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);let i=FN.posix.normalize(r);if(i==="."||i===".."||i.startsWith("../"))throw new Error(`Acceptance evidence ${t} has an unsafe evidence ref`);if(i.split("/").some(n=>n.toLowerCase()===".git"||n.toLowerCase().startsWith(".env")))throw new Error(`Acceptance evidence ${t} references sensitive content`);if(!rj.test(i))throw new Error(`Acceptance evidence ${t} must reference a content-addressed typed receipt`);return i}function fj(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Acceptance evidence entry ${t} must be an object`);let r=e,i=Object.keys(r).filter(n=>!tj.has(n));if(i.length>0)throw new Error(`Acceptance evidence entry ${t} has unknown field(s): ${i.join(", ")}`);return r}function UN(e){if(!Array.isArray(e))throw new Error("Native acceptance evidence block must be a JSON array");let t=new Set;return e.map((r,i)=>{let n=fj(r,i),a=n.acceptance_id;if(typeof a!="string"||!ej.test(a))throw new Error(`Acceptance evidence entry ${i} 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 dj(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 KN(e){let t=cj(e);if(t.some(({line:l,body:u})=>!u&&(l===BN||l===VN)))throw new Error("Native acceptance evidence markers must be in the Markdown body");let i=t.flatMap(({line:l,body:u},d)=>u&&l===BN?[d]:[]),n=t.flatMap(({line:l,body:u},d)=>u&&l===VN?[d]:[]);if(i.length!==1||n.length!==1)throw new Error("Verification must contain exactly one Native acceptance evidence block");if(i[0]>=n[0])throw new Error("Native acceptance evidence markers are out of order");let a=t.slice(i[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=UN(o),c=hj(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function hj(e){let t=UN([...e]).map(r=>({...r,evidence_refs:[...r.evidence_refs].sort()})).sort((r,i)=>r.acceptance_id.localeCompare(i.acceptance_id));return JSON.stringify(t,null,2)}var ZT,ej,tj,rj,ij,nj,zr,Cs,BN,VN,xs=A(()=>{"use strict";Nn();Xe();ZT="comet.native.acceptance.v1",ej=/^acceptance-[a-f0-9]{64}$/u,tj=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),rj=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,ij=/^[a-f0-9]{64}$/u,nj=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;zr=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Cs=Object.freeze({maxCriteria:1024}),BN="<!-- comet-native:acceptance-evidence:start -->",VN="<!-- comet-native:acceptance-evidence:end -->"});import YN from"node:path";function XN(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||YN.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||YN.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function mj(e,t){return e.localeCompare(t,"en")}function hu(e){let t=XN(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>mj(a.capability,o.capability));if(new Set(r.map(a=>a.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=du(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=XN(a.source,`Native spec source for ${a.capability}`);i.push(...fu(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of i){a.text=Rs(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function QN(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!pj.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function ZN(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var pj,pu=A(()=>{"use strict";xs();pj=/^A[1-9]\d*$/u});function mu(){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 jn,As,eb,_s=A(()=>{"use strict";jn="comet.native.v4",As="comet.native.local-execution.v4",eb=["multi-session","single-session"]});var _p={};cg(_p,{NativePortableStateVersionConflictError:()=>Is,appendNativePortableHistory:()=>Oi,compareAndSwapNativePortableState:()=>Hi,createNativePortableState:()=>ib,parseNativePortableState:()=>Qe,readNativePortableState:()=>Be,writeNativePortableState:()=>Ts});import{promises as vj}from"node:fs";function st(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ct(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function De(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function xp(e,t){return e===null?null:De(e,t)}function tb(e,t){let r=De(e,t);if(!Nj.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Oa(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ye(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function kj(e,t){return e===null?null:ye(e,t,Number.MIN_SAFE_INTEGER)}function Ae(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Sr(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function wu(e,t){return Sr(e,t,(r,i)=>De(r,`${t}[${i}]`))}function $n(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Ha(e,t){let r=De(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Ap(e,t,r=!1){let i=De(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function Vt(e,t){let r=st(e,t);return ct(r,new Set(["text","truncated"]),t),{text:De(r.text,`${t}.text`,{empty:!0}),truncated:Oa(r.truncated,`${t}.truncated`)}}function Sj(e,t){let r=`Native spec_changes[${t}]`,i=st(e,r);ct(i,new Set(["capability","operation","source"]),r);let n=De(i.capability,`${r}.capability`);if(!wj.test(n))throw new Error(`${r}.capability is invalid`);let a=Ae(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Ap(i.source,`${r}.source`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);return{capability:n,operation:a,source:o}}function Ej(e){let t="Native workspace",r=st(e,t);ct(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=Ae(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=xp(r.change_branch,`${t}.change_branch`),a=xp(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:Ae(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function Pj(e){let t="Native loop",r=st(e,t);ct(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=wu(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);$n(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:Ae(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:Ae(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:ye(r.goal_cycle,`${t}.goal_cycle`,1),iteration:ye(r.iteration,`${t}.iteration`),attempt:ye(r.attempt,`${t}.attempt`),retry_epoch:ye(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:ye(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:ye(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:ye(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:xp(r.next_action,`${t}.next_action`)}}function Rj(e,t){let r=`Native acceptance[${t}]`,i=st(e,r);ct(i,new Set(["id","source","text","result","reason"]),r);let n=De(i.id,`${r}.id`);if(!yj.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Ap(i.source,`${r}.source`),text:De(i.text,`${r}.text`),result:Ae(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Vt(i.reason,`${r}.reason`)}}function Cj(e,t){let r=`Native builder_handoff.checks[${t}]`,i=st(e,r);return ct(i,new Set(["name","result","note"]),r),{name:Vt(i.name,`${r}.name`),result:Ae(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Vt(i.note,`${r}.note`)}}function xj(e){let t="Native builder_handoff",r=st(e,t);ct(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=wu(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);$n(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:st(r.review,`${t}.review`);return n&&ct(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:De(r.candidate_id,`${t}.candidate_id`),identity_provider:De(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:De(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:ye(r.iteration,`${t}.iteration`,1),summary:Vt(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Sr(r.checks,`${t}.checks`,Cj),checks_truncated:Oa(r.checks_truncated,`${t}.checks_truncated`),known_limits:Sr(r.known_limits,`${t}.known_limits`,(a,o)=>Vt(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Oa(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:Ae(n.status,["passed"],`${t}.review.status`),summary:Vt(n.summary,`${t}.review.summary`),reviewer_execution_ref:De(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Ha(r.submitted_at,`${t}.submitted_at`)}}function Aj(e,t){let r=`Native blockers[${t}]`,i=st(e,r);ct(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=wu(i.acceptance_ids,`${r}.acceptance_ids`);return $n(n,`${r}.acceptance_ids`),{owner:Ae(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Vt(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:Ae(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function _j(e,t){let r=`Native verification.checks[${t}]`,i=st(e,r);return ct(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:De(i.id,`${r}.id`),name:Vt(i.name,`${r}.name`),argv_display:Sr(i.argv_display,`${r}.argv_display`,(n,a)=>Vt(n,`${r}.argv_display[${a}]`)),argv_truncated:Oa(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Ap(i.cwd_ref,`${r}.cwd_ref`,!0),status:Ae(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:kj(i.exit_code,`${r}.exit_code`),duration_ms:ye(i.duration_ms,`${r}.duration_ms`)}}function Ij(e){let t="Native verification",r=st(e,t);ct(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Sr(r.checks,`${t}.checks`,_j);$n(i.map(a=>a.id),`${t}.checks IDs`);let n=De(r.identity_provider,`${t}.identity_provider`);return{candidate_id:De(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:De(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:ye(r.iteration,`${t}.iteration`,1),attempt:ye(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":Ae(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:Ae(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:Vt(r.summary,`${t}.summary`),risks:Sr(r.risks,`${t}.risks`,(a,o)=>Vt(a,`${t}.risks[${o}]`)),risks_truncated:Oa(r.risks_truncated,`${t}.risks_truncated`),completed_at:Ha(r.completed_at,`${t}.completed_at`)}}function rb(e,t){let r=`Native history[${t}]`,i=st(e,r);ct(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=wu(i.unresolved_ids,`${r}.unresolved_ids`);return $n(n,`${r}.unresolved_ids`),{goal_cycle:ye(i.goal_cycle,`${r}.goal_cycle`,1),iteration:ye(i.iteration,`${r}.iteration`),attempt:ye(i.attempt,`${r}.attempt`),outcome:Ae(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Vt(i.summary,`${r}.summary`),completed_at:Ha(i.completed_at,`${r}.completed_at`)}}function Tj(e){let t="Native history_overflow.outcome_counts",r=st(e,t),i=["pass","fail","blocked","execution-error","recovery"];return ct(r,new Set(i),t),{pass:ye(r.pass,`${t}.pass`),fail:ye(r.fail,`${t}.fail`),blocked:ye(r.blocked,`${t}.blocked`),"execution-error":ye(r["execution-error"],`${t}.execution-error`),recovery:ye(r.recovery,`${t}.recovery`)}}function jj(e){let t="Native history_overflow",r=st(e,t);ct(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=ye(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:Ha(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Ha(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=Tj(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function $j(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function Oj(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function Qe(e){let t=st(e,"Native portable state");if(ct(t,bj,"Native portable state"),t.schema!==jn)throw new Error(`Native portable state schema must be ${jn}`);let r=De(t.name,"Native state name");if(!gj.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Sr(t.spec_changes,"Native spec_changes",Sj);$n(i.map(s=>s.capability),"Native spec change capabilities");let n=Sr(t.acceptance,"Native acceptance",Rj);$n(n.map(s=>s.id),"Native acceptance IDs");let a=Sr(t.history,"Native history",rb);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:jn,name:r,language:Ae(t.language,["en","zh-CN"],"Native state language"),phase:Ae(t.phase,["shape","build","verify","archive"],"Native state phase"),status:Ae(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:ye(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:tb(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:tb(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:Ae(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:Ej(t.workspace),loop:Pj(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:xj(t.builder_handoff),blockers:Sr(t.blockers,"Native blockers",Aj),verification:t.verification===null?null:Ij(t.verification),history:a,history_overflow:jj(t.history_overflow),verification_result:Ae(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:Ae(t.verification_report,["verification.md"],"Native verification_report"),archived:Oa(t.archived,"Native archived"),created_at:Ha(t.created_at,"Native created_at")};return $j(o),Oj(o),o}function ib(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return Qe({schema:jn,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:mu(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function Oi(e,t){let r=Qe(e),i=rb(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return Qe({...r,history:n,history_overflow:a})}function Hj(e,t){let r=(0,gu.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function Be(e){let t=await vj.readFile(e,"utf8");return Qe(Hj(t,"Native portable state"))}async function Ts(e,t,r={}){let i=Qe(t);await ge(e,(0,gu.stringify)(i),r)}async function Dj(e,t){let r=vu.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);vu.set(e,a),await r;try{return await t()}finally{i(),vu.get(e)===a&&vu.delete(e)}}async function Hi(e){return Dj(e.file,async()=>{let t=ye(e.expectedStateVersion,"Native expected state version",1),r=Qe(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Be(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new Is(t,i.state_version);return await Ts(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Be(e.file);if(n.state_version!==t)throw new Is(t,n.state_version)}}),r})}var gu,gj,wj,yj,Nj,bj,Is,vu,Er=A(()=>{"use strict";gu=da(Cn(),1);ue();_s();gj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,wj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,yj=/^A[1-9][0-9]*$/u,Nj=/^[a-f0-9]{64}$/u,bj=new Set(["schema","name","language","phase","status","state_version","brief","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),Is=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};vu=new Map});function Lj(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function Jr(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(Lj(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var js=A(()=>{"use strict"});var Pe,Re,lt,Di,Gr,On,$s=A(()=>{"use strict";Pe="comet.native.v3",Re="comet.native.v2",lt="comet.native.v1",Di="comet.native.transition.v3",Gr="comet.native.transition.v2",On="comet.native.transition.v1"});import Mj from"node:path";function zj(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Jj(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function Gj(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function Uj(e){return e.schema===lt?Hn(e):e.schema===Re?Pr(e):wt(e)}function Kj(e){return Mj.posix.normalize(e.replaceAll("\\","/"))}function Yj(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:Kj(t.source)})}function Xj(e){return e==="shape"?"shape":"build"}function Qj(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function Zj(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function nb(e){let t=Uj(e.state);QN(e.acceptance);let r=Xj(t.phase),i=r==="shape"?0:1,n=Jj(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 Qe({schema:jn,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:Yj(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:Qj(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:Jr(Zj(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:mu(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Ip(e){let t=zj(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!Fj.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==yu)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!Vj.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!Bj.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!Wj.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!qj.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:yu,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:Gj(t.createdAt,"Native portable migration transaction createdAt")}}function ab(e){switch(Ip(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 yu,Fj,Bj,Vj,qj,Wj,Tp=A(()=>{"use strict";ke();pu();Er();js();_s();$s();yu="comet.native.portable-migration.v1",Fj=new Set(["schema","id","change","fromSchema","status","createdAt"]),Bj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Vj=/^[a-z0-9][a-z0-9-]{7,127}$/u,qj=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),Wj=new Set([lt,Re,Pe])});import{promises as e$}from"node:fs";import jp from"node:path";function cb(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function lb(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${r} fields are invalid`)}function c$(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=cb(e,r);if(lb(i,s$,r),typeof i.capability!="string"||!sb.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation;if(n==="remove"){if(i.source!==null||i.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);return{capability:i.capability,operation:n,source:i.source,content:i.content}}function l$(e){let t=cb(e,"Native portable Archive transaction");if(lb(t,o$,"Native portable Archive transaction"),t.schema!==Nu)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!i$.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!sb.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"||!n$.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"||!a$.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(c$);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Nu,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function Dn(e){let t=t$.exec(e);if(t)return{kind:"archive",change:t[1]};let r=r$.exec(e);return r?{kind:"migration",change:r[1]}:null}function Li(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=Dn(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return jp.join(e.transactionsDir,r)}async function Os(e,t){let r=Dn(t);if(!r)return null;let i=await te({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=jp.join(e.transactionsDir,t);if(r.kind==="archive"){let s=l$(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=Ip(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function Da(e,t){let r=Li(e,t);try{return await Os(e,jp.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}async function ub(e){let t;try{t=await e$.readdir(e.transactionsDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return t.map(({name:r})=>r).filter(r=>Dn(r)!==null).sort((r,i)=>r.localeCompare(i,"en"))}function db(e){return e.kind==="archive"||e.journal.status!=="committed"}var Nu,ob,t$,r$,i$,n$,a$,o$,s$,sb,La=A(()=>{"use strict";Ft();Tp();Nu="comet.native.archive-transaction.v4",ob="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",t$=new RegExp(`^portable-archive-(${ob})\\.json$`,"u"),r$=new RegExp(`^portable-migration-(${ob})\\.json$`,"u"),i$=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,n$=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,a$=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),o$=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),s$=new Set(["capability","operation","source","content"]),sb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as u$}from"node:crypto";import{constants as bu,promises as z}from"node:fs";import X from"node:path";import{TextDecoder as d$}from"node:util";function Ze(e,t){let r=X.relative(e,t);return r===""||!X.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${X.sep}`)}function fb(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Fa(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function hb(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ma(e,t){return J({...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 Mi(e,t){let r=await z.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await z.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Fi(e,t,r){let i=X.resolve(e),n=X.resolve(t);if(!Ze(i,n))throw new Error(`${r} is outside its managed root`);let a=[await Mi(i,r)],o=i;for(let s of X.relative(i,n).split(X.sep).filter(Boolean)){await Se(a,r),o=X.join(o,s);let c=await Mi(o,r);if(!Ze(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Se(a,r),a}async function Se(e,t){for(let r of e){let i=await z.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!Fa(r,i)||await z.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function f$(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function oe(e){let t=fb(e.maxBytes),r=X.resolve(e.file),i=await Fi(e.root,X.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Mi(X.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Se(i,e.label);let a=await z.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=hb(a),s=await z.realpath(r);if(!Ze(i[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"?bu.O_RDONLY:bu.O_RDONLY|bu.O_NOFOLLOW|bu.O_NONBLOCK,l=await z.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([z.lstat(r),z.realpath(r)]);if(await Se(i,e.label),await Se(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Ma(o,u)||!Ma(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await f$(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,p,v]=await Promise.all([l.stat(),z.lstat(r),z.realpath(r)]);if(await Se(i,e.label),await Se(n,e.label),!p.isFile()||p.isSymbolicLink()||v!==s||!Ma(o,m)||!Ma(o,p))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:u$("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function ku(e){let t=await oe(e),r;try{r=new d$("utf-8",{fatal:!0}).decode(t.bytes)}catch(i){throw new Error(`${e.label} is not valid UTF-8`,{cause:i})}return{...t,text:r}}async function xt(e){let t=await Fi(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await z.readdir(e.directory,{withFileTypes:!0});else{let i=fb(e.maxEntries);r=[];let n=await z.opendir(e.directory);try{for await(let a of n)if(r.push(a),r.length>i)throw new Error(`${e.label} exceeds ${i} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await Se(t,e.label),{entries:r,verify:()=>Se(t,e.label)}}async function dr(e){let t=await Fi(e.root,e.directory,e.label);return{verify:()=>Se(t,e.label)}}async function h$(e){let t=X.resolve(e.directory),r=X.resolve(e.quarantine);if(X.dirname(r)!==X.dirname(t)||!Ze(X.resolve(e.root),r)||r===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let i=await Fi(e.root,X.dirname(t),e.label),n=await Mi(t,e.label);if(!Ze(i[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await Se(i,e.label);let a=await z.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!Fa(n,a)||await z.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await z.lstat(r),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await z.rename(t,r),await Se(i,e.label);let o=await z.lstat(r);if(!o.isDirectory()||o.isSymbolicLink()||!Fa(n,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(r);try{throw await z.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:r,parentChain:i,identity:n}}async function pb(e){await h$(e)}async function Su(e){let t=X.resolve(e.file),r=await Fi(e.root,X.dirname(t),e.label),i=await z.lstat(t);if(!i.isFile()||i.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let n=hb(i),a=await z.realpath(t);if(!Ze(r[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await oe({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([z.lstat(t),z.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!Ma(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await Se(r,e.label);let[l,u]=await Promise.all([z.lstat(t),z.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Ma(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await z.rm(t),await Se(r,e.label)}async function $p(e){let t=X.resolve(e.directory),r=await Fi(e.root,X.dirname(t),e.label),i=await Mi(t,e.label);if(!Ze(r[0].realPath,i.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await Se(r,e.label);let n=await z.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!Fa(i,n)||await z.realpath(t)!==i.realPath)throw new Error(`${e.label} changed before removal`);await z.rmdir(t),await Se(r,e.label)}async function Rr(e){let t=X.resolve(e.root),r=X.resolve(e.directory);if(!Ze(t,r))throw new Error(`${e.label} is outside its managed root`);let i=[await Mi(t,e.label)],n=t;for(let a of X.relative(t,r).split(X.sep).filter(Boolean)){await Se(i,e.label),n=X.join(n,a);try{await z.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await Mi(n,e.label);if(!Ze(i[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);i.push(o)}await Se(i,e.label)}async function Op(e){let t=X.resolve(e.root),r=X.resolve(e.source),i=X.resolve(e.target);if(r===i||!Ze(t,r)||!Ze(t,i)||Ze(r,i)||Ze(i,r))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await Rr({root:t,directory:X.dirname(i),label:`${e.label} target parent`});let n=await Fi(t,X.dirname(r),e.label),a=await Fi(t,X.dirname(i),e.label),o=await Mi(r,e.label);if(!Ze(n[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await z.lstat(i),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([Se(n,e.label),Se(a,e.label)]);let s=await z.lstat(r);if(!s.isDirectory()||s.isSymbolicLink()||!Fa(o,s)||await z.realpath(r)!==o.realPath)throw new Error(`${e.label} source changed before move`);await z.rename(r,i),await Promise.all([Se(n,e.label),Se(a,e.label)]);let c=await z.lstat(i);if(!c.isDirectory()||c.isSymbolicLink()||!Fa(o,c)||!Ze(n[0].realPath,await z.realpath(i)))throw new Error(`${e.label} source identity changed while moving`);try{throw await z.lstat(r),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function Bi(e){let t=await oe({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 dN(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 z.lstat(e.target)}catch(n){if(n.code==="ENOENT")return;throw n}throw new Error(`${e.label} target changed before commit`)}if((await oe({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 r=await oe({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(r.hash!==t.hash||r.size!==t.size)throw new Error(`${e.label} target could not be verified`);return r}var yt=A(()=>{"use strict";ue();nr()});import{promises as Hs}from"fs";import qt from"path";import{TextDecoder as p$}from"util";function Ds(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ls(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Va(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Hp(e,t){if(typeof e!="string"||e.length===0||qt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Eu(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function mb(e,t){if(Hp(e,t),e.includes("\\")||e!==qt.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 S$(e,t){let r=Ds(e,`transaction operations[${t}]`);if(Ls(r,v$,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);Hp(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&Hp(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function Cu(e){let t=Ds(e,"Native Archive transaction journal");if(Ls(t,g$,"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"||!wb.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(!Va(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Eu(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=Ds(s,`Archive transaction operations[${c}]`);if(Ls(l,w$,`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`);mb(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&mb(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Eu(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(Eu(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`);Eu(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function Mp(e){let t=Ds(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Cu(t);if(Ls(t,m$,"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"||!wb.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!qt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!qt.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(!Va(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(S$),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function kb(e,t){let r=Ds(e,`Native transaction event at line ${t}`);if(Ls(r,y$,`Native transaction event at line ${t}`),r.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!Va(r.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof r.type!="string"||!yb.has(r.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let i=r.type==="operation-started"||r.type==="operation-completed";if(i&&(typeof r.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.operationId)||Buffer.byteLength(r.operationId,"utf8")>256)||!i&&r.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:r.sequence,timestamp:r.timestamp,type:r.type,...typeof r.operationId=="string"?{operationId:r.operationId}:{}}}function E$(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let i=0;i<e.length;i+=1){let n=t[i],a=e[i];if(n==="0"){if(!/[0-9]/u.test(a))return!1}else if(a!==n)return!1}let r=[[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[i,n,a,o]of r){if(e.length<=i)continue;let s=e.slice(i,Math.min(i+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&&!Va(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||Va(e)}function Ba(e,t){return e.length<t.length&&t.startsWith(e)}function P$(e){let t='","operationId":"';if(Ba(e,t))return!0;if(!e.startsWith(t))return!1;let r=e.slice(t.length),i=r.indexOf('"');if(i===-1)return r.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(r);let n=r.slice(0,i);return/^[a-z0-9][a-z0-9-]*$/u.test(n)?Ba(r.slice(i),'"}'):!1}function R$(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>Nb)return!1;let r=`{"sequence":${t},"timestamp":"`;if(Ba(e,r))return!0;if(!e.startsWith(r))return!1;let i=e.slice(r.length),n=i.slice(0,Math.min(24,i.length));if(!E$(n))return!1;if(i.length<24)return!0;if(!Va(n))return!1;let a='","type":"',o=i.slice(24);if(Ba(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of yb){if(Ba(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(P$(l))return!0}else if(Ba(l,'"}'))return!0}return!1}function C$(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>Nb)throw new Error(`Native transaction event at line ${t} is too large`);return kb(JSON.parse(e),t)}function x$(e){let t=e.split(`
|
|
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=UN(o),c=hj(s);if(a!==c)throw new Error("Native acceptance evidence block must use canonical serialization");return s}function hj(e){let t=UN([...e]).map(r=>({...r,evidence_refs:[...r.evidence_refs].sort()})).sort((r,i)=>r.acceptance_id.localeCompare(i.acceptance_id));return JSON.stringify(t,null,2)}var ZT,ej,tj,rj,ij,nj,Jr,Cs,BN,VN,xs=A(()=>{"use strict";Nn();Xe();ZT="comet.native.acceptance.v1",ej=/^acceptance-[a-f0-9]{64}$/u,tj=new Set(["acceptance_id","status","evidence_refs","skipped_reason"]),rj=/^runtime\/evidence\/receipts\/[a-f0-9]{64}\.json$/u,ij=/^[a-f0-9]{64}$/u,nj=/^native-acceptance-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u;Jr=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Cs=Object.freeze({maxCriteria:1024}),BN="<!-- comet-native:acceptance-evidence:start -->",VN="<!-- comet-native:acceptance-evidence:end -->"});import YN from"node:path";function XN(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||YN.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||YN.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function mj(e,t){return e.localeCompare(t,"en")}function hu(e){let t=XN(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>mj(a.capability,o.capability));if(new Set(r.map(a=>a.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=du(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=XN(a.source,`Native spec source for ${a.capability}`);i.push(...fu(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of i){a.text=Rs(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function QN(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!pj.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function ZN(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var pj,pu=A(()=>{"use strict";xs();pj=/^A[1-9]\d*$/u});function mu(){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 jn,As,eb,_s=A(()=>{"use strict";jn="comet.native.v4",As="comet.native.local-execution.v4",eb=["multi-session","single-session"]});var _p={};cg(_p,{NativePortableStateVersionConflictError:()=>Is,appendNativePortableHistory:()=>Oi,compareAndSwapNativePortableState:()=>Hi,createNativePortableState:()=>ib,parseNativePortableState:()=>Qe,readNativePortableState:()=>Be,writeNativePortableState:()=>Ts});import{promises as vj}from"node:fs";function st(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ct(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function De(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function xp(e,t){return e===null?null:De(e,t)}function tb(e,t){let r=De(e,t);if(!Nj.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Oa(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ye(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function kj(e,t){return e===null?null:ye(e,t,Number.MIN_SAFE_INTEGER)}function Ae(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Er(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function wu(e,t){return Er(e,t,(r,i)=>De(r,`${t}[${i}]`))}function $n(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Ha(e,t){let r=De(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Ap(e,t,r=!1){let i=De(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function Vt(e,t){let r=st(e,t);return ct(r,new Set(["text","truncated"]),t),{text:De(r.text,`${t}.text`,{empty:!0}),truncated:Oa(r.truncated,`${t}.truncated`)}}function Sj(e,t){let r=`Native spec_changes[${t}]`,i=st(e,r);ct(i,new Set(["capability","operation","source"]),r);let n=De(i.capability,`${r}.capability`);if(!wj.test(n))throw new Error(`${r}.capability is invalid`);let a=Ae(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Ap(i.source,`${r}.source`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);return{capability:n,operation:a,source:o}}function Ej(e){let t="Native workspace",r=st(e,t);ct(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=Ae(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=xp(r.change_branch,`${t}.change_branch`),a=xp(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:Ae(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function Pj(e){let t="Native loop",r=st(e,t);ct(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=wu(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);$n(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:Ae(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:Ae(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:ye(r.goal_cycle,`${t}.goal_cycle`,1),iteration:ye(r.iteration,`${t}.iteration`),attempt:ye(r.attempt,`${t}.attempt`),retry_epoch:ye(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:ye(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:ye(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:ye(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:xp(r.next_action,`${t}.next_action`)}}function Rj(e,t){let r=`Native acceptance[${t}]`,i=st(e,r);ct(i,new Set(["id","source","text","result","reason"]),r);let n=De(i.id,`${r}.id`);if(!yj.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Ap(i.source,`${r}.source`),text:De(i.text,`${r}.text`),result:Ae(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Vt(i.reason,`${r}.reason`)}}function Cj(e,t){let r=`Native builder_handoff.checks[${t}]`,i=st(e,r);return ct(i,new Set(["name","result","note"]),r),{name:Vt(i.name,`${r}.name`),result:Ae(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Vt(i.note,`${r}.note`)}}function xj(e){let t="Native builder_handoff",r=st(e,t);ct(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=wu(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);$n(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:st(r.review,`${t}.review`);return n&&ct(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:De(r.candidate_id,`${t}.candidate_id`),identity_provider:De(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:De(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:ye(r.iteration,`${t}.iteration`,1),summary:Vt(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Er(r.checks,`${t}.checks`,Cj),checks_truncated:Oa(r.checks_truncated,`${t}.checks_truncated`),known_limits:Er(r.known_limits,`${t}.known_limits`,(a,o)=>Vt(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Oa(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:Ae(n.status,["passed"],`${t}.review.status`),summary:Vt(n.summary,`${t}.review.summary`),reviewer_execution_ref:De(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Ha(r.submitted_at,`${t}.submitted_at`)}}function Aj(e,t){let r=`Native blockers[${t}]`,i=st(e,r);ct(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=wu(i.acceptance_ids,`${r}.acceptance_ids`);return $n(n,`${r}.acceptance_ids`),{owner:Ae(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Vt(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:Ae(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function _j(e,t){let r=`Native verification.checks[${t}]`,i=st(e,r);return ct(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:De(i.id,`${r}.id`),name:Vt(i.name,`${r}.name`),argv_display:Er(i.argv_display,`${r}.argv_display`,(n,a)=>Vt(n,`${r}.argv_display[${a}]`)),argv_truncated:Oa(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Ap(i.cwd_ref,`${r}.cwd_ref`,!0),status:Ae(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:kj(i.exit_code,`${r}.exit_code`),duration_ms:ye(i.duration_ms,`${r}.duration_ms`)}}function Ij(e){let t="Native verification",r=st(e,t);ct(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Er(r.checks,`${t}.checks`,_j);$n(i.map(a=>a.id),`${t}.checks IDs`);let n=De(r.identity_provider,`${t}.identity_provider`);return{candidate_id:De(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:De(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:ye(r.iteration,`${t}.iteration`,1),attempt:ye(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":Ae(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:Ae(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:Vt(r.summary,`${t}.summary`),risks:Er(r.risks,`${t}.risks`,(a,o)=>Vt(a,`${t}.risks[${o}]`)),risks_truncated:Oa(r.risks_truncated,`${t}.risks_truncated`),completed_at:Ha(r.completed_at,`${t}.completed_at`)}}function rb(e,t){let r=`Native history[${t}]`,i=st(e,r);ct(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=wu(i.unresolved_ids,`${r}.unresolved_ids`);return $n(n,`${r}.unresolved_ids`),{goal_cycle:ye(i.goal_cycle,`${r}.goal_cycle`,1),iteration:ye(i.iteration,`${r}.iteration`),attempt:ye(i.attempt,`${r}.attempt`),outcome:Ae(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Vt(i.summary,`${r}.summary`),completed_at:Ha(i.completed_at,`${r}.completed_at`)}}function Tj(e){let t="Native history_overflow.outcome_counts",r=st(e,t),i=["pass","fail","blocked","execution-error","recovery"];return ct(r,new Set(i),t),{pass:ye(r.pass,`${t}.pass`),fail:ye(r.fail,`${t}.fail`),blocked:ye(r.blocked,`${t}.blocked`),"execution-error":ye(r["execution-error"],`${t}.execution-error`),recovery:ye(r.recovery,`${t}.recovery`)}}function jj(e){let t="Native history_overflow",r=st(e,t);ct(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=ye(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:Ha(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Ha(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=Tj(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function $j(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function Oj(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function Qe(e){let t=st(e,"Native portable state");if(ct(t,bj,"Native portable state"),t.schema!==jn)throw new Error(`Native portable state schema must be ${jn}`);let r=De(t.name,"Native state name");if(!gj.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Er(t.spec_changes,"Native spec_changes",Sj);$n(i.map(s=>s.capability),"Native spec change capabilities");let n=Er(t.acceptance,"Native acceptance",Rj);$n(n.map(s=>s.id),"Native acceptance IDs");let a=Er(t.history,"Native history",rb);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:jn,name:r,language:Ae(t.language,["en","zh-CN"],"Native state language"),phase:Ae(t.phase,["shape","build","verify","archive"],"Native state phase"),status:Ae(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:ye(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:tb(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:tb(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:Ae(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:Ej(t.workspace),loop:Pj(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:xj(t.builder_handoff),blockers:Er(t.blockers,"Native blockers",Aj),verification:t.verification===null?null:Ij(t.verification),history:a,history_overflow:jj(t.history_overflow),verification_result:Ae(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:Ae(t.verification_report,["verification.md"],"Native verification_report"),archived:Oa(t.archived,"Native archived"),created_at:Ha(t.created_at,"Native created_at")};return $j(o),Oj(o),o}function ib(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return Qe({schema:jn,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:mu(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function Oi(e,t){let r=Qe(e),i=rb(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return Qe({...r,history:n,history_overflow:a})}function Hj(e,t){let r=(0,gu.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function Be(e){let t=await vj.readFile(e,"utf8");return Qe(Hj(t,"Native portable state"))}async function Ts(e,t,r={}){let i=Qe(t);await ge(e,(0,gu.stringify)(i),r)}async function Dj(e,t){let r=vu.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);vu.set(e,a),await r;try{return await t()}finally{i(),vu.get(e)===a&&vu.delete(e)}}async function Hi(e){return Dj(e.file,async()=>{let t=ye(e.expectedStateVersion,"Native expected state version",1),r=Qe(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Be(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new Is(t,i.state_version);return await Ts(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Be(e.file);if(n.state_version!==t)throw new Is(t,n.state_version)}}),r})}var gu,gj,wj,yj,Nj,bj,Is,vu,Pr=A(()=>{"use strict";gu=da(Cn(),1);ue();_s();gj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,wj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,yj=/^A[1-9][0-9]*$/u,Nj=/^[a-f0-9]{64}$/u,bj=new Set(["schema","name","language","phase","status","state_version","brief","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),Is=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};vu=new Map});function Lj(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function Gr(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(Lj(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var js=A(()=>{"use strict"});var Pe,Re,lt,Di,Ur,On,$s=A(()=>{"use strict";Pe="comet.native.v3",Re="comet.native.v2",lt="comet.native.v1",Di="comet.native.transition.v3",Ur="comet.native.transition.v2",On="comet.native.transition.v1"});import Mj from"node:path";function zj(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Jj(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function Gj(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function Uj(e){return e.schema===lt?Hn(e):e.schema===Re?Rr(e):wt(e)}function Kj(e){return Mj.posix.normalize(e.replaceAll("\\","/"))}function Yj(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:Kj(t.source)})}function Xj(e){return e==="shape"?"shape":"build"}function Qj(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function Zj(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function nb(e){let t=Uj(e.state);QN(e.acceptance);let r=Xj(t.phase),i=r==="shape"?0:1,n=Jj(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 Qe({schema:jn,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:Yj(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:Qj(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:Gr(Zj(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:mu(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Ip(e){let t=zj(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!Fj.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==yu)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!Vj.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!Bj.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!Wj.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!qj.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:yu,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:Gj(t.createdAt,"Native portable migration transaction createdAt")}}function ab(e){switch(Ip(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 yu,Fj,Bj,Vj,qj,Wj,Tp=A(()=>{"use strict";ke();pu();Pr();js();_s();$s();yu="comet.native.portable-migration.v1",Fj=new Set(["schema","id","change","fromSchema","status","createdAt"]),Bj=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Vj=/^[a-z0-9][a-z0-9-]{7,127}$/u,qj=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),Wj=new Set([lt,Re,Pe])});import{promises as e$}from"node:fs";import jp from"node:path";function cb(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function lb(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${r} fields are invalid`)}function c$(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=cb(e,r);if(lb(i,s$,r),typeof i.capability!="string"||!sb.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation;if(n==="remove"){if(i.source!==null||i.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);return{capability:i.capability,operation:n,source:i.source,content:i.content}}function l$(e){let t=cb(e,"Native portable Archive transaction");if(lb(t,o$,"Native portable Archive transaction"),t.schema!==Nu)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!i$.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!sb.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"||!n$.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"||!a$.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(c$);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Nu,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function Dn(e){let t=t$.exec(e);if(t)return{kind:"archive",change:t[1]};let r=r$.exec(e);return r?{kind:"migration",change:r[1]}:null}function Li(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=Dn(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return jp.join(e.transactionsDir,r)}async function Os(e,t){let r=Dn(t);if(!r)return null;let i=await te({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=jp.join(e.transactionsDir,t);if(r.kind==="archive"){let s=l$(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=Ip(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function Da(e,t){let r=Li(e,t);try{return await Os(e,jp.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}async function ub(e){let t;try{t=await e$.readdir(e.transactionsDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return t.map(({name:r})=>r).filter(r=>Dn(r)!==null).sort((r,i)=>r.localeCompare(i,"en"))}function db(e){return e.kind==="archive"||e.journal.status!=="committed"}var Nu,ob,t$,r$,i$,n$,a$,o$,s$,sb,La=A(()=>{"use strict";Ft();Tp();Nu="comet.native.archive-transaction.v4",ob="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",t$=new RegExp(`^portable-archive-(${ob})\\.json$`,"u"),r$=new RegExp(`^portable-migration-(${ob})\\.json$`,"u"),i$=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,n$=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,a$=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),o$=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),s$=new Set(["capability","operation","source","content"]),sb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as u$}from"node:crypto";import{constants as bu,promises as z}from"node:fs";import X from"node:path";import{TextDecoder as d$}from"node:util";function Ze(e,t){let r=X.relative(e,t);return r===""||!X.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${X.sep}`)}function fb(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Fa(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function hb(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ma(e,t){return J({...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 Mi(e,t){let r=await z.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await z.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Fi(e,t,r){let i=X.resolve(e),n=X.resolve(t);if(!Ze(i,n))throw new Error(`${r} is outside its managed root`);let a=[await Mi(i,r)],o=i;for(let s of X.relative(i,n).split(X.sep).filter(Boolean)){await Se(a,r),o=X.join(o,s);let c=await Mi(o,r);if(!Ze(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Se(a,r),a}async function Se(e,t){for(let r of e){let i=await z.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!Fa(r,i)||await z.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function f$(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function oe(e){let t=fb(e.maxBytes),r=X.resolve(e.file),i=await Fi(e.root,X.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Mi(X.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Se(i,e.label);let a=await z.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=hb(a),s=await z.realpath(r);if(!Ze(i[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"?bu.O_RDONLY:bu.O_RDONLY|bu.O_NOFOLLOW|bu.O_NONBLOCK,l=await z.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([z.lstat(r),z.realpath(r)]);if(await Se(i,e.label),await Se(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Ma(o,u)||!Ma(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let h=await f$(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,p,v]=await Promise.all([l.stat(),z.lstat(r),z.realpath(r)]);if(await Se(i,e.label),await Se(n,e.label),!p.isFile()||p.isSymbolicLink()||v!==s||!Ma(o,m)||!Ma(o,p))throw new Error(`${e.label} changed while reading`);return{bytes:h,hash:u$("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function ku(e){let t=await oe(e),r;try{r=new d$("utf-8",{fatal:!0}).decode(t.bytes)}catch(i){throw new Error(`${e.label} is not valid UTF-8`,{cause:i})}return{...t,text:r}}async function xt(e){let t=await Fi(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await z.readdir(e.directory,{withFileTypes:!0});else{let i=fb(e.maxEntries);r=[];let n=await z.opendir(e.directory);try{for await(let a of n)if(r.push(a),r.length>i)throw new Error(`${e.label} exceeds ${i} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await Se(t,e.label),{entries:r,verify:()=>Se(t,e.label)}}async function fr(e){let t=await Fi(e.root,e.directory,e.label);return{verify:()=>Se(t,e.label)}}async function h$(e){let t=X.resolve(e.directory),r=X.resolve(e.quarantine);if(X.dirname(r)!==X.dirname(t)||!Ze(X.resolve(e.root),r)||r===t)throw new Error(`${e.label} quarantine must be a distinct sibling inside its root`);let i=await Fi(e.root,X.dirname(t),e.label),n=await Mi(t,e.label);if(!Ze(i[0].realPath,n.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeQuarantine?.(),await Se(i,e.label);let a=await z.lstat(t);if(!a.isDirectory()||a.isSymbolicLink()||!Fa(n,a)||await z.realpath(t)!==n.realPath)throw new Error(`${e.label} changed before quarantine`);try{throw await z.lstat(r),new Error(`${e.label} quarantine path is occupied`)}catch(s){if(s.code!=="ENOENT")throw s}await z.rename(t,r),await Se(i,e.label);let o=await z.lstat(r);if(!o.isDirectory()||o.isSymbolicLink()||!Fa(n,o))throw new Error(`${e.label} changed while quarantining`);await e.afterQuarantine?.(r);try{throw await z.lstat(t),new Error(`${e.label} path was recreated while quarantining`)}catch(s){if(s.code!=="ENOENT")throw s}return{quarantine:r,parentChain:i,identity:n}}async function pb(e){await h$(e)}async function Su(e){let t=X.resolve(e.file),r=await Fi(e.root,X.dirname(t),e.label),i=await z.lstat(t);if(!i.isFile()||i.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let n=hb(i),a=await z.realpath(t);if(!Ze(r[0].realPath,a))throw new Error(`${e.label} resolves outside its managed root`);let o=await oe({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([z.lstat(t),z.realpath(t)]);if(!s.isFile()||s.isSymbolicLink()||!Ma(n,s)||c!==a)throw new Error(`${e.label} changed while verifying removal`);await e.beforeRemove?.(),await Se(r,e.label);let[l,u]=await Promise.all([z.lstat(t),z.realpath(t)]);if(!l.isFile()||l.isSymbolicLink()||!Ma(n,l)||u!==a)throw new Error(`${e.label} changed before removal`);await z.rm(t),await Se(r,e.label)}async function $p(e){let t=X.resolve(e.directory),r=await Fi(e.root,X.dirname(t),e.label),i=await Mi(t,e.label);if(!Ze(r[0].realPath,i.realPath))throw new Error(`${e.label} resolves outside its managed root`);await e.beforeRemove?.(),await Se(r,e.label);let n=await z.lstat(t);if(!n.isDirectory()||n.isSymbolicLink()||!Fa(i,n)||await z.realpath(t)!==i.realPath)throw new Error(`${e.label} changed before removal`);await z.rmdir(t),await Se(r,e.label)}async function Cr(e){let t=X.resolve(e.root),r=X.resolve(e.directory);if(!Ze(t,r))throw new Error(`${e.label} is outside its managed root`);let i=[await Mi(t,e.label)],n=t;for(let a of X.relative(t,r).split(X.sep).filter(Boolean)){await Se(i,e.label),n=X.join(n,a);try{await z.mkdir(n)}catch(s){if(s.code!=="EEXIST")throw s}let o=await Mi(n,e.label);if(!Ze(i[0].realPath,o.realPath))throw new Error(`${e.label} resolves outside its managed root: ${n}`);i.push(o)}await Se(i,e.label)}async function Op(e){let t=X.resolve(e.root),r=X.resolve(e.source),i=X.resolve(e.target);if(r===i||!Ze(t,r)||!Ze(t,i)||Ze(r,i)||Ze(i,r))throw new Error(`${e.label} source and target must be distinct paths inside one root`);await Cr({root:t,directory:X.dirname(i),label:`${e.label} target parent`});let n=await Fi(t,X.dirname(r),e.label),a=await Fi(t,X.dirname(i),e.label),o=await Mi(r,e.label);if(!Ze(n[0].realPath,o.realPath))throw new Error(`${e.label} source resolves outside its managed root`);try{throw await z.lstat(i),new Error(`${e.label} target already exists`)}catch(l){if(l.code!=="ENOENT")throw l}await e.beforeMove?.(),await Promise.all([Se(n,e.label),Se(a,e.label)]);let s=await z.lstat(r);if(!s.isDirectory()||s.isSymbolicLink()||!Fa(o,s)||await z.realpath(r)!==o.realPath)throw new Error(`${e.label} source changed before move`);await z.rename(r,i),await Promise.all([Se(n,e.label),Se(a,e.label)]);let c=await z.lstat(i);if(!c.isDirectory()||c.isSymbolicLink()||!Fa(o,c)||!Ze(n[0].realPath,await z.realpath(i)))throw new Error(`${e.label} source identity changed while moving`);try{throw await z.lstat(r),new Error(`${e.label} source was recreated while moving`)}catch(l){if(l.code!=="ENOENT")throw l}}async function Bi(e){let t=await oe({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 dN(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 z.lstat(e.target)}catch(n){if(n.code==="ENOENT")return;throw n}throw new Error(`${e.label} target changed before commit`)}if((await oe({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 r=await oe({root:e.targetRoot,file:e.target,maxBytes:e.maxBytes,label:`${e.label} target`});if(r.hash!==t.hash||r.size!==t.size)throw new Error(`${e.label} target could not be verified`);return r}var yt=A(()=>{"use strict";ue();ar()});import{promises as Hs}from"fs";import qt from"path";import{TextDecoder as p$}from"util";function Ds(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ls(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Va(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Hp(e,t){if(typeof e!="string"||e.length===0||qt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Eu(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function mb(e,t){if(Hp(e,t),e.includes("\\")||e!==qt.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 S$(e,t){let r=Ds(e,`transaction operations[${t}]`);if(Ls(r,v$,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);Hp(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&Hp(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function Cu(e){let t=Ds(e,"Native Archive transaction journal");if(Ls(t,g$,"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"||!wb.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(!Va(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Eu(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=Ds(s,`Archive transaction operations[${c}]`);if(Ls(l,w$,`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`);mb(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&mb(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&Eu(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(Eu(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`);Eu(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function Mp(e){let t=Ds(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Cu(t);if(Ls(t,m$,"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"||!wb.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!qt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!qt.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(!Va(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(S$),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function kb(e,t){let r=Ds(e,`Native transaction event at line ${t}`);if(Ls(r,y$,`Native transaction event at line ${t}`),r.sequence!==t)throw new Error(`Native transaction event sequence at line ${t} must be ${t}`);if(!Va(r.timestamp))throw new Error(`Native transaction event timestamp at line ${t} is invalid`);if(typeof r.type!="string"||!yb.has(r.type))throw new Error(`Native transaction event type at line ${t} is invalid`);let i=r.type==="operation-started"||r.type==="operation-completed";if(i&&(typeof r.operationId!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.operationId)||Buffer.byteLength(r.operationId,"utf8")>256)||!i&&r.operationId!==void 0)throw new Error(`Native transaction event operationId at line ${t} is invalid`);return{sequence:r.sequence,timestamp:r.timestamp,type:r.type,...typeof r.operationId=="string"?{operationId:r.operationId}:{}}}function E$(e){if(e.length>24)return!1;let t="0000-00-00T00:00:00.000Z";for(let i=0;i<e.length;i+=1){let n=t[i],a=e[i];if(n==="0"){if(!/[0-9]/u.test(a))return!1}else if(a!==n)return!1}let r=[[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[i,n,a,o]of r){if(e.length<=i)continue;let s=e.slice(i,Math.min(i+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&&!Va(`${e.slice(0,10)}T00:00:00.000Z`)?!1:e.length<24||Va(e)}function Ba(e,t){return e.length<t.length&&t.startsWith(e)}function P$(e){let t='","operationId":"';if(Ba(e,t))return!0;if(!e.startsWith(t))return!1;let r=e.slice(t.length),i=r.indexOf('"');if(i===-1)return r.length===0||/^[a-z0-9][a-z0-9-]*$/u.test(r);let n=r.slice(0,i);return/^[a-z0-9][a-z0-9-]*$/u.test(n)?Ba(r.slice(i),'"}'):!1}function R$(e,t){if(e.length===0||Buffer.byteLength(e,"utf8")>Nb)return!1;let r=`{"sequence":${t},"timestamp":"`;if(Ba(e,r))return!0;if(!e.startsWith(r))return!1;let i=e.slice(r.length),n=i.slice(0,Math.min(24,i.length));if(!E$(n))return!1;if(i.length<24)return!0;if(!Va(n))return!1;let a='","type":"',o=i.slice(24);if(Ba(o,a))return!0;if(!o.startsWith(a))return!1;let s=o.slice(a.length);for(let c of yb){if(Ba(s,c))return!0;if(!s.startsWith(c))continue;let l=s.slice(c.length);if(c==="operation-started"||c==="operation-completed"){if(P$(l))return!0}else if(Ba(l,'"}'))return!0}return!1}function C$(e,t){if(e.length===0)throw new Error("Blank transaction event line");if(Buffer.byteLength(e,"utf8")>Nb)throw new Error(`Native transaction event at line ${t} is too large`);return kb(JSON.parse(e),t)}function x$(e){let t=e.split(`
|
|
180
180
|
`),r=t.at(-1)==="";if(r&&t.pop(),t.length>Pu)throw new Error(`Native transaction event log exceeds ${Pu} events`);let i=[];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=!r&&n===t.length-1;try{i.push(C$(s,a))}catch(l){if(c){let u=!1;try{JSON.parse(s),u=!0}catch{}if(!u&&R$(s,a))break}throw new Error(`Invalid Native transaction event at line ${a}`,{cause:l})}}return i}function Sb(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
181
181
|
`)}
|
|
182
|
-
`}function A$(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return qt.join(e.transactionsDir,t)}function xu(e,t){let r=A$(e,t);return{directory:r,journal:qt.join(r,"transaction.json"),events:qt.join(r,"events.jsonl"),staged:qt.join(r,"staged"),backups:qt.join(r,"backups")}}async function Cr(e,t){let r=xu(e,t);return await Promise.all(Object.values(r).map(i=>T(e.runtimeDir,i))),r}function _$(e,t){if(t.length===0||qt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let r="runtime/",i=t==="runtime"||t.startsWith(r),n=i?e.runtimeDir:e.nativeRoot,a=t==="runtime"?"":i?t.slice(r.length):t,o=qt.resolve(n,...a.split(/[\\/]/u));if(!D(n,o))throw new Error(`Unsafe Native transaction ref: ${t}`);return o}async function Vi(e,t){let r=_$(e,t);return T($(e,r),r)}async function Ln(e){try{return await Hs.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Fp(e,t,r={}){let i=await Cr(e,t);try{await Hs.lstat(i.events)}catch(n){if(n.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw n}try{let n=await oe({root:e.runtimeDir,file:i.events,maxBytes:b$,label:`Native transaction event log ${t}`,hooks:r.hooks}),a;try{a=bb.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=x$(a),s=Sb(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 vb(e,t,r){let i=await Fp(e,t);if(i.exists!==r.exists||i.hash!==r.hash||i.size!==r.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function Wt(e,t,r,i){let n=await Cr(e,t),a=await Fp(e,t),o=a.events.find(c=>c.type===r&&c.operationId===i);if(o)return a.needsRepair&&await ge(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>vb(e,t,a)}),o;if(a.events.length>=Pu)throw new Error(`Native transaction event log ${t} exceeds ${Pu} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:r,...i?{operationId:i}:{}};return kb(s,s.sequence),await Hs.mkdir(n.directory,{recursive:!0}),await ge(n.events,Sb([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>vb(e,t,a)}),s}async function Eb(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=Mp(t);let r=await Cr(e,t.id);await Hs.mkdir(r.staged,{recursive:!0}),await Hs.mkdir(r.backups,{recursive:!0}),await re(r.journal,t,{containedRoot:e.runtimeDir}),await Wt(e,t.id,"prepared")}async function At(e,t,r={}){let i=await Cr(e,t),n=await oe({root:e.runtimeDir,file:i.journal,maxBytes:N$,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(bb.decode(n.bytes)),o=Mp(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function qi(e,t,r={}){return(await Fp(e,t,r)).events}async function Ru(e,t,r){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=Mp({...t,status:r});return await re((await Cr(e,t.id)).journal,i,{containedRoot:e.runtimeDir}),i}async function Dp(e,t,r){try{return await oe({root:$(e,t),file:t,maxBytes:Lp,label:r})}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Bp(e,t,r,i){let n=await Dp(e,t,`${i} source`);if(!n)throw new Error(`${i} source does not exist`);let a=await Dp(e,r,`${i} target`);await Rr({root:$(e,r),directory:qt.dirname(r),label:`${i} target parent`}),await Bi({sourceRoot:$(e,t),source:t,targetRoot:$(e,r),target:r,maxBytes:Lp,label:i,expectedHash:n.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function Pb(e,t,r){let i=await Dp(e,t,r);i&&await Su({root:$(e,t),file:t,maxBytes:Lp,expectedHash:i.hash,expectedSize:i.size,label:r})}async function gb(e,t){if(!t.backup)return;let r=await Vi(e,t.target),i=await Vi(e,t.backup);!await Ln(r)||await Ln(i)||await Bp(e,r,i,`Legacy Native transaction backup ${t.id}`)}async function I$(e,t){let r=await Vi(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await gb(e,t),await Bp(e,await Vi(e,t.staged),r,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await gb(e,t),await Pb(e,r,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let i=await Vi(e,t.source),[n,a]=await Promise.all([Ln(i),Ln(r)]);if(!n&&a){await(await xt({root:$(e,r),directory:r,label:`Legacy Native transaction move target ${t.id}`,maxEntries:k$})).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 Op({root:$(e,i),source:i,target:r,label:`Legacy Native transaction move ${t.id}`})}async function Rb(e,t,r){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=t.status==="prepared"?await Ru(e,t,"applying"):t,n=await qi(e,t.id),a=new Set(n.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of i.operations)a.has(s.id)||(await Wt(e,i.id,"operation-started",s.id),await I$(e,s),await Wt(e,i.id,"operation-completed",s.id),o+=1,await r?.afterOperation?.(s,o));return i=await At(e,i.id),i}async function T$(e,t){let r=await Vi(e,t.target),i=t.backup?await Vi(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 Vi(e,t.source);if(await Ln(r)){if(await Ln(n))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await Op({root:$(e,r),source:r,target:n,label:`Legacy Native transaction rollback move ${t.id}`})}return}i&&await Ln(i)?await Bp(e,i,r,`Legacy Native transaction rollback restore ${t.id}`):await Pb(e,r,`Legacy Native transaction rollback remove ${t.id}`)}async function Au(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=await qi(e,t.id);if(r.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 i=await Ru(e,t,"rolling-back");await Wt(e,i.id,"rollback-started");let n=new Set(r.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...i.operations].reverse())n.has(a.id)&&await T$(e,a);return await Wt(e,i.id,"rollback-completed"),i=await Ru(e,i,"rolled-back"),i}async function qa(e,t,r){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await Wt(e,t.id,r),r==="commit"?Ru(e,t,"committed"):t}var m$,v$,g$,w$,y$,wb,yb,N$,b$,Nb,Pu,Lp,k$,bb,Mn=A(()=>{"use strict";ue();Q();yt();m$=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),v$=new Set(["id","type","source","target","staged","backup"]),g$=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),w$=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),y$=new Set(["sequence","timestamp","type","operationId"]),wb=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),yb=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),N$=256*1024,b$=1024*1024,Nb=16*1024,Pu=1024,Lp=64*1024*1024,k$=2e4,bb=new p$("utf-8",{fatal:!0})});import{promises as j$}from"fs";import $$ from"path";async function O$(e,t,r){let i;try{i=await j$.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await At(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(Dn(n.name))try{let a=await Os(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(db(a))return!0}catch{return!0}return!1}async function H$(e,t){let r=Date.now()+5e3,i=$$.join(e.locksDir,"root-move.lock");for(;;)try{return await ji(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Es(i);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function de(e,t,r,i){let n=await H$(e,t);try{if(await Ta(e.projectRoot),await O$(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await $i(n)}}var et=A(()=>{"use strict";ot();Tn();La();Mn()});function Cb(e){return Number.isSafeInteger(e)&&e>=1}async function xb(e){if(!Cb(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(!Cb(t.revision))throw new Error("Native current revision must be a positive integer");let r=e.equals??((i,n)=>JSON.stringify(i)===JSON.stringify(n));if(t.revision===e.next.revision&&r(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}var Ab=A(()=>{"use strict"});import{createHash as _b}from"crypto";import{createReadStream as D$}from"fs";async function fr(e){let t=_b("sha256");for await(let r of D$(e))t.update(r);return t.digest("hex")}function F(e){return _b("sha256").update(e).digest("hex")}var hr=A(()=>{"use strict"});import{createHash as $u}from"crypto";import{spawn as Mb}from"node:child_process";import{promises as fe}from"fs";import q from"path";function Bb(e){let t=e.deadlineMs??rO;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 pr(e){return Math.max(0,e.deadlineAt-Date.now())}function B(e){return pr(e)>=1}function Vp(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 Ja(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function oO(e){let t={...aO,...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 sO(e,t){if(t.terminateTree){await t.terminateTree(e);return}let r=e.pid;if(r===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,n=i&&q.win32.isAbsolute(i)?q.win32.resolve(i):"C:\\Windows",a=q.win32.join(n,"System32","taskkill.exe");if(!q.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=Mb(a,["/pid",String(r),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),iO),u.unref()}catch{d(!1)}});for(let s=0;s<nO;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(-r,"SIGKILL")}catch(i){if(i.code!=="ESRCH")throw i}e.kill("SIGKILL")}function Kp(e,t,r,i){let n=pr(e);if(n<1)throw Vp();let a=e.gitProcess,o=Mb(a.command,[...a.argsPrefix??[],"-C",t,...r],{cwd:t,stdio:[i?"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=sO(o,a).then(()=>({error:null}),h=>({error:h}))},n);d.unref();let f=u.then(async h=>{if(clearTimeout(d),c){let m=await l;throw m?.error?Vp(m.error):Vp()}return{code:h,spawnError:s}});return{child:o,completion:f}}function Vb(e){let t={...Up,...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 Iu(e,t,r,i=zp){let{child:n,completion:a}=Kp(e,t,r,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",h=>{let m=Math.max(0,i-l);m>0&&o.push(Buffer.from(h).subarray(0,m)),l+=h.byteLength,l>i&&(u=!0)}),n.stderr.on("data",h=>{if(c>=Ua)return;let m=Ua-c,p=Buffer.from(h).subarray(0,m);s.push(p),c+=p.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${r.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function qp(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Fs(e,t,r,i){if(i.outputChunkBytes!==void 0&&(!Number.isSafeInteger(i.outputChunkBytes)||i.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}=Kp(e,t,r,i.stdin!==void 0),c=[],l=$u("sha256"),u=[],d=0,f=0,h=0,m=0,p=Buffer.alloc(0),v=!1,g=!1,N=!1,E=w=>{let S=0;for(;S<w.byteLength;){let k=w.indexOf(0,S),R=k<0?w.byteLength:k,b=w.subarray(S,R);if(!v&&b.byteLength>0&&(p.byteLength+b.byteLength>i.maxRecordBytes?(p=Buffer.alloc(0),v=!0,g=!0):p=Buffer.concat([p,b])),k<0)break;m+=1,p.byteLength===0&&!v&&(N=!0);let y=p.byteLength+1;!v&&m<=i.maxRecords&&h+y<=i.maxBytes?(c.push(p),h+=y):g=!0,p=Buffer.alloc(0),v=!1,S=k+1}};o.stdout.on("data",w=>{l.update(w),f+=w.byteLength,f>i.maxBytes&&(g=!0);let S=i.outputChunkBytes;if(S===void 0){E(w);return}for(let k=0;k<w.byteLength;k+=S)E(w.subarray(k,Math.min(w.byteLength,k+S)))}),o.stderr.on("data",w=>{if(d>=Ua)return;let S=Ua-d,k=Buffer.from(w).subarray(0,S);u.push(k),d+=k.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:w,spawnError:S})=>{let k=i.acceptedExitCodes??[0];if(w!==null&&k.includes(w)&&S===null&&!N&&p.byteLength===0&&!v){n({records:c,digest:l.digest("hex"),overflow:g,recordCount:m,stdoutBytes:f});return}a(new Error(`git ${r.join(" ")} failed${S?`: ${S.message}`:N||p.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),i.stdin&&o.stdin?.end(i.stdin)})}function Tu(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 cO(e,t,r){if(r.length===0)return new Set;let i=await Fs(e,t,["check-ignore","--no-index","-z","--stdin"],{...Up,maxRecords:Math.max(1,r.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${r.join("\0")}\0`,"utf8")});if(i.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(i.records.map(n=>{let a=Tu(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function lO(e,t,r){let{child:i,completion:n}=Kp(e,t,r,!1),a=[],o=0,s=!1;i.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),i.stderr.on("data",u=>{if(o>=Ua)return;let d=Ua-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 ${r.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function Ga(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||q.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||q.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function uO(e,t){return e.map(r=>{let i=Ga(r);if(i===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return i})}async function dO(e){let t=q.resolve(e);for(;;){try{return await fe.lstat(q.join(t,".git")),!0}catch(i){if(i.code!=="ENOENT")throw i}let r=q.dirname(t);if(r===t)return!1;t=r}}async function qb(e,t,r,i={}){let n=q.resolve(t.projectRoot),a=q.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let h=q.relative(n,q.resolve(f)).replaceAll("\\","/"),m=Ga(h);if(m===null)throw new Error("Native Git snapshot exclusion escaped the project root");return m}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...r,...i.outputChunkBytes===void 0?{}:{outputChunkBytes:i.outputChunkBytes}},l=await Fs(e,n,["ls-files","--stage","-z",...s],c);await i.afterStageBefore?.();let u=await Fs(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await i.afterCombined?.();let d=await Fs(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function Wb(e){return{stageBefore:qp(e.stagedBefore),combined:qp(e.combined),stageAfter:qp(e.stagedAfter)}}async function zb(e,t,r=Up,i={}){let n=q.resolve(t.projectRoot);if(!await dO(n))return null;let a;try{a=await Iu(e,n,["rev-parse","--is-inside-work-tree"])}catch(N){throw Ja(N)?N:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:N})}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 qb(e,t,r,i)}catch(N){throw Ja(N)?N:new Error("Native Git snapshot provider failed after repository detection",{cause:N})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,h=N=>{for(let E of N){let w=Tu(E),S=w.indexOf(" ");if(S<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let k=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(w.slice(0,S))?.groups;if(!k)throw new Error("Native Git snapshot provider returned a malformed staged header");let R=Ga(w.slice(S+1));if(R===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(R),k.stage==="0"&&d.set(R,k.objectId),k.mode==="160000"&&k.stage==="0"&&f.add(R)}};h(s.records),h(l.records);let m=c.records.map(Tu),p=uO(m,"combined"),v=new Set(p.filter(N=>!u.has(N))),g=new Set(p.filter((N,E)=>!u.has(N)&&m[E].endsWith("/")));for(let N of f)g.delete(N);return{tracked:u,trackedObjectIds:d,untracked:v,gitlinks:f,nestedRepositories:g,omissions:[],overflow:null,evidence:null,initialFence:Wb(o)}}function zi(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Ib(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function fO(e,t){return!zi(e.stageBefore,e.stageAfter)||!zi(e.stageAfter,t.stageBefore)||!zi(e.combined,t.combined)||!zi(t.stageBefore,t.stageAfter)}async function Jb(e,t,r,i,n){let a;try{a=await qb(e,t,r,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw Ja(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=i.initialFence,s=Wb(a),c=Ib(o)||Ib(s),l=fO(o,s);c&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),i.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)&&(i.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:F(`comet.native.git-selection-overflow.v2
|
|
183
|
-
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}function pO(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function Tb(e){let t=q.resolve(e.paths.projectRoot),r=q.resolve(e.paths.nativeRoot),i=q.resolve(e.paths.runtimeDir),n=q.resolve(e.paths.configFile),a=q.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,h=!1,m=!1,p=!1,v=()=>
|
|
182
|
+
`}function A$(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return qt.join(e.transactionsDir,t)}function xu(e,t){let r=A$(e,t);return{directory:r,journal:qt.join(r,"transaction.json"),events:qt.join(r,"events.jsonl"),staged:qt.join(r,"staged"),backups:qt.join(r,"backups")}}async function xr(e,t){let r=xu(e,t);return await Promise.all(Object.values(r).map(i=>T(e.runtimeDir,i))),r}function _$(e,t){if(t.length===0||qt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`Unsafe Native transaction ref: ${t}`);let r="runtime/",i=t==="runtime"||t.startsWith(r),n=i?e.runtimeDir:e.nativeRoot,a=t==="runtime"?"":i?t.slice(r.length):t,o=qt.resolve(n,...a.split(/[\\/]/u));if(!D(n,o))throw new Error(`Unsafe Native transaction ref: ${t}`);return o}async function Vi(e,t){let r=_$(e,t);return T($(e,r),r)}async function Ln(e){try{return await Hs.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Fp(e,t,r={}){let i=await xr(e,t);try{await Hs.lstat(i.events)}catch(n){if(n.code==="ENOENT")return{exists:!1,hash:null,size:0,events:[],canonicalSource:"",needsRepair:!1};throw n}try{let n=await oe({root:e.runtimeDir,file:i.events,maxBytes:b$,label:`Native transaction event log ${t}`,hooks:r.hooks}),a;try{a=bb.decode(n.bytes)}catch(c){throw new Error(`Native transaction event log ${t} is not valid UTF-8`,{cause:c})}let o=x$(a),s=Sb(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 vb(e,t,r){let i=await Fp(e,t);if(i.exists!==r.exists||i.hash!==r.hash||i.size!==r.size)throw new Error(`Native transaction event log ${t} changed before append`)}async function Wt(e,t,r,i){let n=await xr(e,t),a=await Fp(e,t),o=a.events.find(c=>c.type===r&&c.operationId===i);if(o)return a.needsRepair&&await ge(n.events,a.canonicalSource,{containedRoot:e.runtimeDir,beforeCommit:()=>vb(e,t,a)}),o;if(a.events.length>=Pu)throw new Error(`Native transaction event log ${t} exceeds ${Pu} events`);let s={sequence:a.events.length+1,timestamp:new Date().toISOString(),type:r,...i?{operationId:i}:{}};return kb(s,s.sequence),await Hs.mkdir(n.directory,{recursive:!0}),await ge(n.events,Sb([...a.events,s]),{containedRoot:e.runtimeDir,beforeCommit:()=>vb(e,t,a)}),s}async function Eb(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");t=Mp(t);let r=await xr(e,t.id);await Hs.mkdir(r.staged,{recursive:!0}),await Hs.mkdir(r.backups,{recursive:!0}),await re(r.journal,t,{containedRoot:e.runtimeDir}),await Wt(e,t.id,"prepared")}async function At(e,t,r={}){let i=await xr(e,t),n=await oe({root:e.runtimeDir,file:i.journal,maxBytes:N$,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(bb.decode(n.bytes)),o=Mp(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function qi(e,t,r={}){return(await Fp(e,t,r)).events}async function Ru(e,t,r){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=Mp({...t,status:r});return await re((await xr(e,t.id)).journal,i,{containedRoot:e.runtimeDir}),i}async function Dp(e,t,r){try{return await oe({root:$(e,t),file:t,maxBytes:Lp,label:r})}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Bp(e,t,r,i){let n=await Dp(e,t,`${i} source`);if(!n)throw new Error(`${i} source does not exist`);let a=await Dp(e,r,`${i} target`);await Cr({root:$(e,r),directory:qt.dirname(r),label:`${i} target parent`}),await Bi({sourceRoot:$(e,t),source:t,targetRoot:$(e,r),target:r,maxBytes:Lp,label:i,expectedHash:n.hash,expectedTargetHash:a?.hash??null,exclusive:a===null})}async function Pb(e,t,r){let i=await Dp(e,t,r);i&&await Su({root:$(e,t),file:t,maxBytes:Lp,expectedHash:i.hash,expectedSize:i.size,label:r})}async function gb(e,t){if(!t.backup)return;let r=await Vi(e,t.target),i=await Vi(e,t.backup);!await Ln(r)||await Ln(i)||await Bp(e,r,i,`Legacy Native transaction backup ${t.id}`)}async function I$(e,t){let r=await Vi(e,t.target);if(t.type==="write"){if(!t.staged)throw new Error(`Write operation ${t.id} has no staged ref`);await gb(e,t),await Bp(e,await Vi(e,t.staged),r,`Legacy Native transaction write ${t.id}`);return}if(t.type==="remove"){await gb(e,t),await Pb(e,r,`Legacy Native transaction remove ${t.id}`);return}if(!t.source)throw new Error(`Move operation ${t.id} has no source ref`);let i=await Vi(e,t.source),[n,a]=await Promise.all([Ln(i),Ln(r)]);if(!n&&a){await(await xt({root:$(e,r),directory:r,label:`Legacy Native transaction move target ${t.id}`,maxEntries:k$})).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 Op({root:$(e,i),source:i,target:r,label:`Legacy Native transaction move ${t.id}`})}async function Rb(e,t,r){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let i=t.status==="prepared"?await Ru(e,t,"applying"):t,n=await qi(e,t.id),a=new Set(n.filter(s=>s.type==="operation-completed").map(s=>s.operationId)),o=a.size;for(let s of i.operations)a.has(s.id)||(await Wt(e,i.id,"operation-started",s.id),await I$(e,s),await Wt(e,i.id,"operation-completed",s.id),o+=1,await r?.afterOperation?.(s,o));return i=await At(e,i.id),i}async function T$(e,t){let r=await Vi(e,t.target),i=t.backup?await Vi(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 Vi(e,t.source);if(await Ln(r)){if(await Ln(n))throw new Error(`Legacy Native rollback source already exists: ${t.source}`);await Op({root:$(e,r),source:r,target:n,label:`Legacy Native transaction rollback move ${t.id}`})}return}i&&await Ln(i)?await Bp(e,i,r,`Legacy Native transaction rollback restore ${t.id}`):await Pb(e,r,`Legacy Native transaction rollback remove ${t.id}`)}async function Au(e,t){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");let r=await qi(e,t.id);if(r.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 i=await Ru(e,t,"rolling-back");await Wt(e,i.id,"rollback-started");let n=new Set(r.filter(a=>a.type==="operation-started"||a.type==="operation-completed").map(a=>a.operationId));for(let a of[...i.operations].reverse())n.has(a.id)&&await T$(e,a);return await Wt(e,i.id,"rollback-completed"),i=await Ru(e,i,"rolled-back"),i}async function qa(e,t,r){if(t.schema!=="comet.native.transaction.v1")throw new Error("Native Archive v2 transactions require the content-bound transaction API");return await Wt(e,t.id,r),r==="commit"?Ru(e,t,"committed"):t}var m$,v$,g$,w$,y$,wb,yb,N$,b$,Nb,Pu,Lp,k$,bb,Mn=A(()=>{"use strict";ue();Q();yt();m$=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),v$=new Set(["id","type","source","target","staged","backup"]),g$=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),w$=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),y$=new Set(["sequence","timestamp","type","operationId"]),wb=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),yb=new Set(["prepared","operation-started","operation-completed","archive-finalization-started","archive-finalized","commit","rollback-started","rollback-completed"]),N$=256*1024,b$=1024*1024,Nb=16*1024,Pu=1024,Lp=64*1024*1024,k$=2e4,bb=new p$("utf-8",{fatal:!0})});import{promises as j$}from"fs";import $$ from"path";async function O$(e,t,r){let i;try{i=await j$.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await At(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(Dn(n.name))try{let a=await Os(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(db(a))return!0}catch{return!0}return!1}async function H$(e,t){let r=Date.now()+5e3,i=$$.join(e.locksDir,"root-move.lock");for(;;)try{return await ji(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Es(i);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function de(e,t,r,i){let n=await H$(e,t);try{if(await Ta(e.projectRoot),await O$(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await $i(n)}}var et=A(()=>{"use strict";ot();Tn();La();Mn()});function Cb(e){return Number.isSafeInteger(e)&&e>=1}async function xb(e){if(!Cb(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(!Cb(t.revision))throw new Error("Native current revision must be a positive integer");let r=e.equals??((i,n)=>JSON.stringify(i)===JSON.stringify(n));if(t.revision===e.next.revision&&r(t,e.next))return t;if(t.revision!==e.expectedRevision)throw e.conflict(t.revision);return await e.write(e.next),e.next}var Ab=A(()=>{"use strict"});import{createHash as _b}from"crypto";import{createReadStream as D$}from"fs";async function hr(e){let t=_b("sha256");for await(let r of D$(e))t.update(r);return t.digest("hex")}function F(e){return _b("sha256").update(e).digest("hex")}var pr=A(()=>{"use strict"});import{createHash as $u}from"crypto";import{spawn as Mb}from"node:child_process";import{promises as fe}from"fs";import q from"path";function Bb(e){let t=e.deadlineMs??rO;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 mr(e){return Math.max(0,e.deadlineAt-Date.now())}function B(e){return mr(e)>=1}function Vp(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 Ja(e){return e.code==="GIT_SNAPSHOT_TIMEOUT"}function oO(e){let t={...aO,...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 sO(e,t){if(t.terminateTree){await t.terminateTree(e);return}let r=e.pid;if(r===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let i=process.env.SystemRoot??process.env.WINDIR,n=i&&q.win32.isAbsolute(i)?q.win32.resolve(i):"C:\\Windows",a=q.win32.join(n,"System32","taskkill.exe");if(!q.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=Mb(a,["/pid",String(r),"/t","/f"],{stdio:"ignore",windowsHide:!0}),l.once("error",()=>d(!1)),l.once("close",f=>d(f===0)),u=setTimeout(()=>d(!1,!0),iO),u.unref()}catch{d(!1)}});for(let s=0;s<nO;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(-r,"SIGKILL")}catch(i){if(i.code!=="ESRCH")throw i}e.kill("SIGKILL")}function Kp(e,t,r,i){let n=mr(e);if(n<1)throw Vp();let a=e.gitProcess,o=Mb(a.command,[...a.argsPrefix??[],"-C",t,...r],{cwd:t,stdio:[i?"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=sO(o,a).then(()=>({error:null}),h=>({error:h}))},n);d.unref();let f=u.then(async h=>{if(clearTimeout(d),c){let m=await l;throw m?.error?Vp(m.error):Vp()}return{code:h,spawnError:s}});return{child:o,completion:f}}function Vb(e){let t={...Up,...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 Iu(e,t,r,i=zp){let{child:n,completion:a}=Kp(e,t,r,!1),o=[],s=[],c=0,l=0,u=!1;n.stdout.on("data",h=>{let m=Math.max(0,i-l);m>0&&o.push(Buffer.from(h).subarray(0,m)),l+=h.byteLength,l>i&&(u=!0)}),n.stderr.on("data",h=>{if(c>=Ua)return;let m=Ua-c,p=Buffer.from(h).subarray(0,m);s.push(p),c+=p.byteLength});let{code:d,spawnError:f}=await a;if(d===0&&f===null&&!u)return Buffer.concat(o);throw Object.assign(new Error(`git ${r.join(" ")} failed${f?`: ${f.message}`:s.length>0?`: ${Buffer.concat(s).toString("utf8").trim()}`:""}`),{code:"GIT_SNAPSHOT_UNAVAILABLE"})}function qp(e){return{hash:e.digest,recordCount:e.recordCount,storedRecordCount:e.records.length,stdoutBytes:e.stdoutBytes,overflow:e.overflow}}function Fs(e,t,r,i){if(i.outputChunkBytes!==void 0&&(!Number.isSafeInteger(i.outputChunkBytes)||i.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}=Kp(e,t,r,i.stdin!==void 0),c=[],l=$u("sha256"),u=[],d=0,f=0,h=0,m=0,p=Buffer.alloc(0),v=!1,g=!1,N=!1,E=w=>{let S=0;for(;S<w.byteLength;){let k=w.indexOf(0,S),R=k<0?w.byteLength:k,b=w.subarray(S,R);if(!v&&b.byteLength>0&&(p.byteLength+b.byteLength>i.maxRecordBytes?(p=Buffer.alloc(0),v=!0,g=!0):p=Buffer.concat([p,b])),k<0)break;m+=1,p.byteLength===0&&!v&&(N=!0);let y=p.byteLength+1;!v&&m<=i.maxRecords&&h+y<=i.maxBytes?(c.push(p),h+=y):g=!0,p=Buffer.alloc(0),v=!1,S=k+1}};o.stdout.on("data",w=>{l.update(w),f+=w.byteLength,f>i.maxBytes&&(g=!0);let S=i.outputChunkBytes;if(S===void 0){E(w);return}for(let k=0;k<w.byteLength;k+=S)E(w.subarray(k,Math.min(w.byteLength,k+S)))}),o.stderr.on("data",w=>{if(d>=Ua)return;let S=Ua-d,k=Buffer.from(w).subarray(0,S);u.push(k),d+=k.byteLength}),o.stdin?.on("error",()=>{}),s.then(({code:w,spawnError:S})=>{let k=i.acceptedExitCodes??[0];if(w!==null&&k.includes(w)&&S===null&&!N&&p.byteLength===0&&!v){n({records:c,digest:l.digest("hex"),overflow:g,recordCount:m,stdoutBytes:f});return}a(new Error(`git ${r.join(" ")} failed${S?`: ${S.message}`:N||p.byteLength>0||v?": malformed NUL-delimited output":u.length>0?`: ${Buffer.concat(u).toString("utf8").trim()}`:""}`))},a),i.stdin&&o.stdin?.end(i.stdin)})}function Tu(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 cO(e,t,r){if(r.length===0)return new Set;let i=await Fs(e,t,["check-ignore","--no-index","-z","--stdin"],{...Up,maxRecords:Math.max(1,r.length),acceptedExitCodes:[0,1],stdin:Buffer.from(`${r.join("\0")}\0`,"utf8")});if(i.overflow)throw new Error("Native Git check-ignore output exceeded its safety budget");return new Set(i.records.map(n=>{let a=Tu(n);return a.endsWith("/")?a.slice(0,-1):a}))}async function lO(e,t,r){let{child:i,completion:n}=Kp(e,t,r,!1),a=[],o=0,s=!1;i.stdout.on("data",u=>{u.byteLength>0&&(s=!0)}),i.stderr.on("data",u=>{if(o>=Ua)return;let d=Ua-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 ${r.join(" ")} failed${l?`: ${l.message}`:a.length>0?`: ${Buffer.concat(a).toString("utf8").trim()}`:""}`)}function Ga(e){let t=e.endsWith("/")?e.slice(0,-1):e;return t.length===0||t.includes("\\")||q.posix.isAbsolute(t)||/^[A-Za-z]:/u.test(t)||q.posix.normalize(t)!==t||t===".."||t.startsWith("../")||t.includes("\0")?null:t}function uO(e,t){return e.map(r=>{let i=Ga(r);if(i===null)throw new Error(`Native Git snapshot provider returned an unsafe ${t} path`);return i})}async function dO(e){let t=q.resolve(e);for(;;){try{return await fe.lstat(q.join(t,".git")),!0}catch(i){if(i.code!=="ENOENT")throw i}let r=q.dirname(t);if(r===t)return!1;t=r}}async function qb(e,t,r,i={}){let n=q.resolve(t.projectRoot),a=q.join(n,".comet","current-change.json"),s=["--",".",...[t.nativeRoot,t.runtimeDir,t.configFile,a].map(f=>{let h=q.relative(n,q.resolve(f)).replaceAll("\\","/"),m=Ga(h);if(m===null)throw new Error("Native Git snapshot exclusion escaped the project root");return m}).flatMap(f=>[`:(exclude)${f}`,`:(exclude)${f}/**`])],c={...r,...i.outputChunkBytes===void 0?{}:{outputChunkBytes:i.outputChunkBytes}},l=await Fs(e,n,["ls-files","--stage","-z",...s],c);await i.afterStageBefore?.();let u=await Fs(e,n,["ls-files","--cached","--others","--exclude-standard","-z",...s],c);await i.afterCombined?.();let d=await Fs(e,n,["ls-files","--stage","-z",...s],c);return{stagedBefore:l,combined:u,stagedAfter:d}}function Wb(e){return{stageBefore:qp(e.stagedBefore),combined:qp(e.combined),stageAfter:qp(e.stagedAfter)}}async function zb(e,t,r=Up,i={}){let n=q.resolve(t.projectRoot);if(!await dO(n))return null;let a;try{a=await Iu(e,n,["rev-parse","--is-inside-work-tree"])}catch(N){throw Ja(N)?N:new Error("Native Git snapshot provider could not inspect the repository boundary",{cause:N})}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 qb(e,t,r,i)}catch(N){throw Ja(N)?N:new Error("Native Git snapshot provider failed after repository detection",{cause:N})}let{stagedBefore:s,combined:c,stagedAfter:l}=o,u=new Set,d=new Map,f=new Set,h=N=>{for(let E of N){let w=Tu(E),S=w.indexOf(" ");if(S<0)throw new Error("Native Git snapshot provider returned a malformed staged record");let k=/^(?<mode>[0-7]{6}) (?<objectId>[a-f0-9]{40}|[a-f0-9]{64}) (?<stage>[0-3])$/u.exec(w.slice(0,S))?.groups;if(!k)throw new Error("Native Git snapshot provider returned a malformed staged header");let R=Ga(w.slice(S+1));if(R===null)throw new Error("Native Git snapshot provider returned an unsafe staged path");u.add(R),k.stage==="0"&&d.set(R,k.objectId),k.mode==="160000"&&k.stage==="0"&&f.add(R)}};h(s.records),h(l.records);let m=c.records.map(Tu),p=uO(m,"combined"),v=new Set(p.filter(N=>!u.has(N))),g=new Set(p.filter((N,E)=>!u.has(N)&&m[E].endsWith("/")));for(let N of f)g.delete(N);return{tracked:u,trackedObjectIds:d,untracked:v,gitlinks:f,nestedRepositories:g,omissions:[],overflow:null,evidence:null,initialFence:Wb(o)}}function zi(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function Ib(e){return e.stageBefore.overflow||e.combined.overflow||e.stageAfter.overflow}function fO(e,t){return!zi(e.stageBefore,e.stageAfter)||!zi(e.stageAfter,t.stageBefore)||!zi(e.combined,t.combined)||!zi(t.stageBefore,t.stageAfter)}async function Jb(e,t,r,i,n){let a;try{a=await qb(e,t,r,{...n===void 0?{}:{outputChunkBytes:n}})}catch(u){throw Ja(u)?u:new Error("Native Git snapshot provider failed during its final selection fence",{cause:u})}let o=i.initialFence,s=Wb(a),c=Ib(o)||Ib(s),l=fO(o,s);c&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-enumeration-limit"}),l&&i.omissions.push({path:".",size:null,type:"directory",reason:"git-selection-changed"}),i.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)&&(i.overflow={count:Math.max(1,o.combined.recordCount-o.combined.storedRecordCount,s.combined.recordCount-s.combined.storedRecordCount),hash:F(`comet.native.git-selection-overflow.v2
|
|
183
|
+
${JSON.stringify({initial:o.combined,final:s.combined})}`)})}function pO(e){return e.isFile()?"file":e.isDirectory()?"directory":e.isSymbolicLink()?"symlink":"other"}async function Tb(e){let t=q.resolve(e.paths.projectRoot),r=q.resolve(e.paths.nativeRoot),i=q.resolve(e.paths.runtimeDir),n=q.resolve(e.paths.configFile),a=q.join(t,".comet","current-change.json"),o=[],s=[],c=Buffer.alloc(32),l=0n,u=0,d=0,f=0,h=!1,m=!1,p=!1,v=()=>mr(e.execution)>=1?!0:(h=!0,p=!0,!1),g=w=>{let S=Buffer.from(`${w.type}\0${w.path}`,"utf8"),k=$u("sha256").update("comet.native.physical-selection-record.v1\0").update(S).digest();for(let R=0;R<c.length;R+=1)c[R]^=k[R];if(l=l+BigInt(`0x${k.toString("hex")}`)&hO,d+=1,f+=S.byteLength,Buffer.byteLength(w.path,"utf8")>e.limits.maxPathBytes||f>e.limits.maxBytes){h=!0,p=!0;return}o.push(w)},N=async w=>{if(p||!v())return;let S;try{S=await fe.opendir(w)}catch(P){if(!v())return;if(!Ie(P)&&!_e(P)||w===t&&Ie(P))throw P;m||=_e(P),h||=Ie(P),p=!0;return}if(!v()){try{await S.close()}catch(P){if(P.code!=="ERR_DIR_CLOSED")throw P}return}let k=!1,R;try{for(;!p&&v();){let P;try{P=await S.read()}catch(ie){if(!v())break;if(!Ie(ie)&&!_e(ie)||w===t&&Ie(ie))throw ie;m||=_e(ie),h||=Ie(ie),p=!0;break}if(!v()||P===null)break;if(u+=1,u>e.limits.maxNodes){h=!0,p=!0;break}let L=q.join(w,P.name),H=vO(t,L);if(L===n||L===a||vr(r,L)||vr(i,L)||e.denylist.some(ie=>vr(ie,L))||Sr(H)!==null)continue;if(!v())break;let je;try{je=await fe.lstat(L)}catch(ie){if(!v())break;if(!Ie(ie)&&!_e(ie))throw ie;if(m=!0,g({path:H,type:"other"}),s.push({path:H,size:null,type:"file",reason:Ie(ie)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(H),p||!v())break;continue}if(!v())break;let me=pO(je);if(me==="directory"){if(NO(e.policy,H))continue;if(!v())break;let ie;try{ie=await fe.realpath(L)}catch(Nr){if(!v())break;if(!Ie(Nr)&&!_e(Nr))throw Nr;if(m=!0,g({path:H,type:me}),s.push({path:H,size:null,type:"directory",reason:Ie(Nr)?"unreadable":"changed-during-read"}),await e.hooks?.afterNode?.(H),p||!v())break;continue}if(!v())break;if(!D(e.physicalProjectRoot,ie)||vr(e.physicalNativeRoot,ie))continue;if(g({path:H,type:me}),await e.hooks?.afterNode?.(H),!v()||(await N(L),p))break;continue}if(g({path:H,type:me}),await e.hooks?.afterNode?.(H),!v()||p)break}}catch(P){k=!0,R=P}let b;try{await S.close()}catch(P){b=P}let y=v();if(k)throw R;if(y&&b!==void 0&&b.code!=="ERR_DIR_CLOSED")throw b};await N(t),v(),h?(o.length=0,d=0,f=0):(o.sort((w,S)=>w.path.localeCompare(S.path,"en")),s.sort((w,S)=>w.path.localeCompare(S.path,"en")));let E=h?F(`comet.native.physical-selection-incomplete.v1
|
|
184
184
|
${JSON.stringify({maxNodes:e.limits.maxNodes,maxBytes:e.limits.maxBytes,maxPathBytes:e.limits.maxPathBytes})}`):F(`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:E,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:h,unstable:m}}}function Gb(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 mO(e,t){let r=e.overflow||t.overflow,i=e.unstable||t.unstable||!Gb(e,t),n=[];return r&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),i&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:r||i?{schema:"comet.native.physical-selection.v1",status:r&&i?"overflow-and-changed":r?"overflow":"changed",before:e,after:t}:null}}function Ub(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,r)=>t.localeCompare(r,"en"))}async function jb(e,t){let i=(await Iu(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Fb.test(i))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return F(`gitlink:${i}`)}async function $b(e,t){let r=await jb(e,t),i=await lO(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await jb(e,t);if(n!==r)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:i}}function Ms(e,t){if(
|
|
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:E,visitedNodeCount:u,recordCount:d,storedRecordCount:o.length,encodedBytes:f,overflow:h,unstable:m}}}function Gb(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 mO(e,t){let r=e.overflow||t.overflow,i=e.unstable||t.unstable||!Gb(e,t),n=[];return r&&n.push({path:".",size:null,type:"directory",reason:"physical-enumeration-limit"}),i&&n.push({path:".",size:null,type:"directory",reason:"physical-selection-changed"}),{omissions:n,evidence:r||i?{schema:"comet.native.physical-selection.v1",status:r&&i?"overflow-and-changed":r?"overflow":"changed",before:e,after:t}:null}}function Ub(e){return[...new Set([...e.tracked,...e.untracked])].sort((t,r)=>t.localeCompare(r,"en"))}async function jb(e,t){let i=(await Iu(e,t,["rev-parse","--verify","HEAD"])).toString("utf8").trim().toLowerCase();if(!Fb.test(i))throw new Error("Native Git snapshot provider received an invalid submodule HEAD");return F(`gitlink:${i}`)}async function $b(e,t){let r=await jb(e,t),i=await lO(e,t,["status","--porcelain=v1","-z","--untracked-files=normal"]),n=await jb(e,t);if(n!==r)throw new Error("Native Git snapshot provider observed a changing submodule HEAD");return{hash:n,dirty:i}}function Ms(e,t){if(Sr(t)!==null)return!1;let r=q.resolve(e.projectRoot,...t.split("/"));return!vr(q.resolve(e.nativeRoot),r)&&!vr(q.resolve(e.runtimeDir),r)}function Yp(e,t={}){let r=Kr(e),i=t.maxRecordedPaths??20;if(!Number.isSafeInteger(i)||i<0)throw new Error("Native snapshot health maxRecordedPaths must be a non-negative integer");let n=r.omitted.slice(0,i).map(a=>a.path);return{complete:r.complete,omittedCount:r.omittedCount,recordedOmissionCount:r.omitted.length,overflowCount:r.omissionOverflow?.count??0,samplePaths:n,sampleTruncated:n.length<r.omittedCount}}function vO(e,t){return q.relative(e,t).split(q.sep).join("/")}function gO(e,t){return t.map(r=>q.resolve(e,...r.split(/[\\/]/u)))}function vr(e,t){let r=q.resolve(e),i=q.resolve(t);return i===r||D(r,i)}function Ie(e){return tO.has(e.code??"")}function _e(e){return e.code==="ENOENT"}function Xp(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
186
186
|
`)}function wO(e,t){return F(`comet.native.snapshot-policy.v1
|
|
187
187
|
${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function Wp(e,t,r){let i=new Set(t),n=[...t];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function yO(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function Ob(e){let t=au(e,"Native snapshot pattern"),r=[];for(let i=0;i<t.length;i+=1){let n=t[i];n==="*"&&t[i+1]==="*"?(i+=1,t[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?yO(n):void 0;if(a&&!a())return!1;let o=Wp(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=r[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=Wp(r,c,a),o===null||o.size===0)return!1}return Wp(r,o,a)?.has(r.length)??!1}}function Kb(e){if(e===void 0)return;let t=[...new Set(e.include.map(n=>au(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(e.exclude.map(n=>au(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 i=wO(t,r);if("hash"in e&&e.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:r,hash:i},includeMatchers:t.map(Ob),excludeMatchers:r.map(Ob),excludedDirectoryPrefixes:r.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 NO(e,t){return e?.excludedDirectoryPrefixes.includes(t)??!1}function Hb(e,t,r){if(!e)return!0;let i=()=>B(r),n=!1;for(let a of e.includeMatchers){if(!i())return!1;if(a(t,i)){n=!0;break}}if(!n)return!1;for(let a of e.excludeMatchers)if(!i()||a(t,i))return!1;return!0}function Bs(e,t,r){let i=JSON.stringify(r);return F(`${e}
|
|
188
188
|
${Buffer.byteLength(t)}:${t}
|
|
189
|
-
${Buffer.byteLength(i)}:${i}`)}function Jp(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function ju(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!Jp(r))return e.splice(t,1),r}return null}function Wi(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Rt(r,i)?J(r,i):J(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function bO(e,t,r,i){if(!B(i))return{status:"budget-exhausted"};let n;try{n=await fe.open(e,"r")}catch(c){if(!B(i))return{status:"budget-exhausted"};throw c}if(!B(i))return await n.close(),{status:"budget-exhausted"};let a=$u("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!B(i))return{status:"budget-exhausted"};let c=await n.stat();if(!B(i))return{status:"budget-exhausted"};if(!c.isFile()||!Wi(r,c))return{status:"changed"};for(;;){if(!B(i))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(!B(i))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!B(i))return{status:"budget-exhausted"};let d=await n.stat();return B(i)?!d.isFile()||!Wi(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 zt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Jt(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function za(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function xr(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Yb(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 r=q.posix.normalize(e);if(r!==e||q.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function kO(e,t){let r=zt(e,`Native snapshot entry ${t}`);Jt(r,K$,`Native snapshot entry ${t}`);let i=Yb(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!Ou.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:xr(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!Fb.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function SO(e,t){let r=zt(e,`Native snapshot omission ${t}`);if(Jt(r,Y$,`Native snapshot omission ${t}`),!Z$.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!eO.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Yb(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:xr(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function EO(e){let t=zt(e,"Native snapshot omission overflow");if(Jt(t,X$,"Native snapshot omission overflow"),typeof t.hash!="string"||!Ou.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:za(t.count,"Native snapshot omission overflow count")}}function Wa(e,t){let r=zt(e,t);if(Jt(r,J$,t),typeof r.hash!="string"||!Ou.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=xr(r.recordCount,`${t} recordCount`),n=xr(r.storedRecordCount,`${t} storedRecordCount`),a=xr(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function Db(e){let t=zt(e,"Native Git selection evidence");if(Jt(t,z$,"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 r=Wa(t.stageBefore,"Native Git selection stageBefore"),i=Wa(t.combined,"Native Git selection combined"),n=Wa(t.stageAfter,"Native Git selection stageAfter"),a=Wa(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Wa(t.finalCombined,"Native Git selection finalCombined"),s=Wa(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!zi(r,n)||!zi(n,a)||!zi(i,o)||!zi(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:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Lb(e,t){let r=zt(e,t);if(Jt(r,U$,t),typeof r.hash!="string"||!Ou.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=xr(r.visitedNodeCount,`${t} visitedNodeCount`),n=xr(r.recordCount,`${t} recordCount`),a=xr(r.storedRecordCount,`${t} storedRecordCount`),o=xr(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function PO(e){let t=zt(e,"Native physical selection evidence");if(Jt(t,G$,"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 r=Lb(t.before,"Native physical selection before"),i=Lb(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!Gb(r,i);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:r,after:i}}function Ur(e){let t=zt(e,"Native content snapshot manifest");if(Jt(t,F$,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!Q$.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let k=zt(t.capture,"Native content snapshot capture");if(Jt(k,q$,"Native content snapshot capture"),k.provider!=="git"&&k.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=k.gitSelection===void 0?void 0:Db(k.gitSelection),b=k.physicalSelection===void 0?void 0:PO(k.physicalSelection),y=null;if(k.projection!==void 0){let P=zt(k.projection,"Native content snapshot projection");if(Jt(P,W$,"Native content snapshot projection"),P.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");y={provider:"git",...P.selection===void 0?{}:{selection:Db(P.selection)}}}if(k.provider==="git"){if(b||y)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(b&&y)throw new Error("Native physical-tree capture cannot combine selection and projection");r=y?{provider:"physical-tree",projection:y}:{provider:"physical-tree",...b?{physicalSelection:b}:{}}}}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 i=zt(t.limits,"Native content snapshot limits");Jt(i,B$,"Native content snapshot limits");let n={maxFiles:za(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:za(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:za(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:za(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:za(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let k=zt(t.policy,"Native snapshot policy");if(Jt(k,V$,"Native snapshot policy"),k.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(k.include)||!Array.isArray(k.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Kb({include:k.include,exclude:k.exclude,hash:k.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(kO),s=t.omitted.map(SO),c=xr(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:EO(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(k=>k.size>n.maxFileBytes)||o.reduce((k,R)=>k+R.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(k=>k.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Gp||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(k=>k.reason==="git-enumeration-limit"),f=s.filter(k=>k.reason==="git-selection-changed");for(let k of[...d,...f])if(k.path!=="."||k.size!==null||k.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=r?.provider==="git"?r.gitSelection:r?.projection?.selection,m=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(p!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(k=>k.reason==="physical-enumeration-limit"),g=s.filter(k=>k.reason==="physical-selection-changed");for(let k of[...v,...g])if(k.path!=="."||k.size!==null||k.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||g.length>1)throw new Error("Native physical selection omissions must not be duplicated");let N=r?.physicalSelection,E=N?.status==="overflow"||N?.status==="overflow-and-changed",w=N?.status==="changed"||N?.status==="overflow-and-changed";if(E!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(w!==(g.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let S={schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Xp(S)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return S}async function Hu(e,t,r={}){let i=Ur(t);if(i.capture?.provider==="git"||i.capture?.projection||i.capture?.physicalSelection)return i;let n=q.resolve(e.projectRoot),a=Bb(r),o=Vb(r.gitSelectionLimits),s=await zb(a,e,o,r.gitSelectionHooks);if(s===null)return i;let c=new Set(Ub(s).filter(b=>Ms(e,b))),l=[...s.gitlinks].filter(b=>c.has(b)),u=[...s.nestedRepositories].filter(b=>Ms(e,b)),d=(b,y)=>y.some(P=>b===P||b.startsWith(`${P}/`)),f=b=>d(b,l),h=b=>d(b,u),m=[...i.entries.map(b=>b.path),...i.omitted.flatMap(b=>b.type==="directory"?[b.path,`${b.path}/`]:[b.path])].filter(b=>!c.has(b)&&!f(b)&&!h(b)),p=await cO(a,n,m),v=i.entries.filter(b=>!f(b.path)&&!h(b.path)&&Ms(e,b.path)&&(c.has(b.path)||!p.has(b.path)));await Jb(a,e,o,s,r.gitSelectionHooks?.outputChunkBytes);let g=[...s.omissions];for(let b of l)g.push({path:b,size:null,type:"directory",reason:"legacy-gitlink-boundary"});v.sort((b,y)=>b.path.localeCompare(y.path,"en"));let N=i.omitted.filter(b=>f(b.path)||h(b.path)||!Ms(e,b.path)?!1:p.has(b.path)?c.has(b.path)||[...c].some(y=>y.startsWith(`${b.path}/`)):!0);for(let b of g)N.some(y=>y.path===b.path&&y.reason===b.reason)||N.push(b);N.sort((b,y)=>b.path.localeCompare(y.path,"en"));let E=i.omissionOverflow?.count??0,w=i.omissionOverflow?.hash??F("comet.native.snapshot-omission-overflow.v1");s.overflow&&(E+=s.overflow.count,w=Bs(w,"git-selection",{source:"git-selection",...s.overflow}));let S=b=>{E+=1,w=Bs(w,"omission",b)};for(;N.length>Gp;){let b=ju(N);if(b===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");S(b)}let k=()=>({...i,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:N.length+E===0,entries:v,omitted:N,omittedCount:N.length+E,...E>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${w}`,hash:w,count:E}}:{}}),R=k();for(;Xp(R)>i.limits.maxManifestBytes;){let b=ju(N);if(b===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");S(b),R=k()}return Ur(R)}function Xb(e,t){if(!M$.test(t))throw new Error(`Invalid Native change name: ${t}`);return q.join(M(e,t),"baseline-manifest.json")}async function Du(e,t={}){let r={maxFiles:t.limits?.maxFiles??_u.maxFiles,maxFileBytes:t.limits?.maxFileBytes??_u.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??_u.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??_u.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},i=Kb(t.policy),n=Bb({...t,deadlineMs:t.deadlineMs??r.maxDurationMs}),a=Vb(t.gitSelectionLimits),o=oO(t.physicalSelectionLimits);if(r.maxFiles<1||r.maxFileBytes<1||r.maxTotalBytes<1||r.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=q.resolve(e.projectRoot),c=await fe.realpath(s),l=q.resolve(e.nativeRoot),u=await fe.realpath(l),d=q.resolve(e.runtimeDir),f=q.resolve(e.configFile),h=q.join(s,".comet","current-change.json"),m=gO(s,t.denylist??[]),p=[],v=[],g=new Map,N=new Map,E=0,w=0,S=F("comet.native.snapshot-omission-overflow.v1"),k=0,R=!1,b=null,y=I=>{w+=1,S=Bs(S,"omission",I)},P=I=>{if(E+=1,v.length<Gp){v.push(I);return}if(Jp(I)){let _=ju(v);if(_===null)throw new Error("Native snapshot has too many required selection-integrity omissions");y(_),v.push(I);return}y(I)},L=I=>{E+=I.count,w+=I.count,S=Bs(S,"git-selection",{source:"git-selection",...I})},H=I=>{w+=1,S=Bs(S,"manifest-entry",{reason:"manifest-size",entry:I})},je=async(I,_)=>{p.push(I),k+=I.size,g.set(I.path,_),R||(R=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(I.path))},me=(I,_)=>{let j=p.findIndex(le=>le.path===I);if(j<0)return;let[W]=p.splice(j,1);k-=W.size,g.delete(I),P(_)},ie=async(I,_,j,W)=>{if(!j.isFile()||j.isSymbolicLink()||!B(n))return;let le;try{le=await fe.realpath(I)}catch(x){if(!B(n))return;if(!Ie(x)&&!_e(x))throw x;P({path:_,size:j.size,type:"file",reason:_e(x)?"changed-during-read":"unreadable"});return}if(!B(n)||!D(c,le)||mr(u,le))return;if(p.length>=r.maxFiles){P({path:_,size:j.size,type:"file",reason:"file-count"});return}if(j.size>r.maxFileBytes){P({path:_,size:j.size,type:"file",reason:"file-size"});return}if(k+j.size>r.maxTotalBytes){P({path:_,size:j.size,type:"file",reason:"total-size"});return}let K,V,Ne;try{if(K=await bO(le,j.size,j,n),K.status==="budget-exhausted"||!B(n))return;if(K.status==="changed"){P({path:_,size:null,type:"file",reason:"changed-during-read"});return}if(!B(n)||(Ne=await fe.realpath(I),!B(n)))return;V=await fe.lstat(I)}catch(x){if(!B(n))return;if(!Ie(x)&&!_e(x))throw x;P({path:_,size:j.size,type:"file",reason:_e(x)?"changed-during-read":"unreadable"});return}if(B(n)){if(K.bytes!==j.size||Ne!==le||!Wi(j,K.finalStat)||!Wi(K.finalStat,V)||!V.isFile()||V.isSymbolicLink()||V.size!==j.size||V.mtimeMs!==j.mtimeMs||V.ctimeMs!==j.ctimeMs){P({path:_,size:V.isFile()?V.size:null,type:V.isFile()?"file":"other",reason:"changed-during-read"});return}B(n)&&await je({path:_,hash:K.hash,size:V.size,type:"file",...W===void 0?{}:{gitObjectId:W}},{kind:"file",target:I,realTarget:le,stat:V})}},yr=async(I,_,j)=>{if(!B(n))return;let W,le,K;try{if(W=await fe.readlink(I,{encoding:"buffer"}),!B(n)||(K=await fe.lstat(I),!B(n)))return;le=await fe.readlink(I,{encoding:"buffer"})}catch(x){if(!B(n))return;if(!Ie(x)&&!_e(x))throw x;P({path:_,size:null,type:"other",reason:_e(x)?"changed-during-read":"unreadable"});return}if(!B(n))return;if(!K.isSymbolicLink()||!Wi(j,K)||K.mtimeMs!==j.mtimeMs||K.ctimeMs!==j.ctimeMs||!W.equals(le)){P({path:_,size:null,type:"other",reason:"changed-during-read"});return}let V=W.byteLength;if(p.length>=r.maxFiles){P({path:_,size:V,type:"other",reason:"file-count"});return}if(V>r.maxFileBytes){P({path:_,size:V,type:"other",reason:"file-size"});return}if(k+V>r.maxTotalBytes){P({path:_,size:V,type:"other",reason:"total-size"});return}let Ne=$u("sha256").update("symlink\0").update(W).digest("hex");B(n)&&await je({path:_,hash:Ne,size:V,type:"file"},{kind:"symlink",target:I,rawTarget:W,stat:K})},er=async()=>{for(let[I,_]of[...g]){if(!B(n))return;if(_.kind==="file"){let V,Ne;try{if(V=await fe.realpath(_.target),!B(n))return;Ne=await fe.lstat(_.target)}catch(x){if(!B(n))return;if(!Ie(x)&&!_e(x))throw x;me(I,{path:I,size:null,type:"file",reason:Ie(x)?"unreadable":"changed-during-read"});continue}if(!B(n))return;(V!==_.realTarget||!Ne.isFile()||Ne.isSymbolicLink()||!Wi(_.stat,Ne)||Ne.size!==_.stat.size||Ne.mtimeMs!==_.stat.mtimeMs||Ne.ctimeMs!==_.stat.ctimeMs)&&me(I,{path:I,size:Ne.isFile()?Ne.size:null,type:Ne.isFile()?"file":"other",reason:"changed-during-read"});continue}if(_.kind==="symlink"){let V,Ne;try{if(V=await fe.lstat(_.target),!B(n))return;Ne=await fe.readlink(_.target,{encoding:"buffer"})}catch(x){if(!B(n))return;if(!Ie(x)&&!_e(x))throw x;me(I,{path:I,size:null,type:"other",reason:Ie(x)?"unreadable":"changed-during-read"});continue}if(!B(n))return;(!V.isSymbolicLink()||!Wi(_.stat,V)||V.mtimeMs!==_.stat.mtimeMs||V.ctimeMs!==_.stat.ctimeMs||!_.rawTarget.equals(Ne))&&me(I,{path:I,size:null,type:"other",reason:"changed-during-read"});continue}let j,W;try{if(j=await fe.realpath(_.target),!B(n))return;W=await fe.lstat(_.target)}catch{if(!B(n))return;me(I,{path:I,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!B(n))return;if(!(j===_.realTarget&&W.isDirectory()&&!W.isSymbolicLink()&&Wi(_.stat,W)&&D(c,j)&&!mr(u,j))){me(I,{path:I,size:null,type:"directory",reason:"gitlink-changed"});continue}let K;try{if(!B(n))return;K=await $b(n,j)}catch(V){if(Ja(V))throw V;me(I,{path:I,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!B(n))return;K.dirty?me(I,{path:I,size:null,type:"directory",reason:"gitlink-dirty"}):K.hash!==_.hash&&me(I,{path:I,size:null,type:"directory",reason:"gitlink-changed"})}for(let[I,_]of N){if(!B(n))return;try{let j=await fe.lstat(_);if(!B(n))return;P({path:I,size:j.isFile()?j.size:null,type:j.isFile()?"file":j.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(j){if(!B(n))return;if(_e(j))continue;if(!Ie(j))throw j;P({path:I,size:null,type:"file",reason:"unreadable"})}}},Et=await zb(n,e,a,t.gitSelectionHooks);if(Et===null){let I=await Tb({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let W of I.records){if(W.type!=="file"&&W.type!=="symlink"||g.has(W.path))continue;if(pr(n)<1)break;if(!Hb(i,W.path,n))continue;if(pr(n)<1)break;let le=q.resolve(s,...W.path.split("/")),K;try{K=await fe.lstat(le)}catch(V){if(!B(n))break;if(!Ie(V)&&!_e(V))throw V;P({path:W.path,size:null,type:"file",reason:_e(V)?"changed-during-read":"unreadable"});continue}if(pr(n)<1)break;if(W.type==="symlink"&&K.isSymbolicLink()){if(await yr(le,W.path,K),pr(n)<1)break;continue}if(W.type!=="file"||!K.isFile()||K.isSymbolicLink()){P({path:W.path,size:K.isFile()?K.size:null,type:K.isDirectory()?"directory":K.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await ie(le,W.path,K),pr(n)<1)break}pr(n)>=1&&await er();let _=await Tb({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o}),j=mO(I.evidence,_.evidence);b=j.evidence;for(let W of[...I.omissions,..._.omissions,...j.omissions])v.some(le=>le.path===W.path&&le.reason===W.reason)||P(W)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let I=t.incrementalBaseline,_=new Map,j=!1;if(I){let x=Ur(I);for(let ve of x.entries)ve.gitObjectId!==void 0&&_.set(ve.path,ve);j=_.size>0}let W=new Set,le=!0;try{let x=await Fs(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(x.overflow)j=!1,le=!1,_.clear();else for(let ve of x.records){let be=Tu(ve),at=be.indexOf(" "),Ue=at<0?null:Ga(be.slice(at+1));if(at!==1||Ue===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");be[0]!=="H"&&W.add(Ue)}}catch(x){if(Ja(x))throw x;j=!1,le=!1,_.clear()}let K=new Set;try{let x=await Iu(n,s,["ls-files","--modified","-z"],zp);for(let ve of x.toString("utf8").split("\0")){let be=Ga(ve);be!==null&&K.add(be)}}catch{j=!1,le=!1,_.clear()}let V=new Set,Ne=new Set;for(let x of Ub(Et)){if(g.has(x)||!Ms(e,x))continue;if(pr(n)<1)break;if(!Hb(i,x,n))continue;if(pr(n)<1)break;let ve=q.resolve(s,...x.split("/"));if(ve===f||ve===h||mr(d,ve)||m.some(Pt=>mr(Pt,ve)))continue;if(Et.gitlinks.has(x)){if(p.length>=r.maxFiles){P({path:x,size:0,type:"file",reason:"file-count"});continue}let Pt,Vc;try{[Pt,Vc]=await Promise.all([fe.realpath(ve),fe.lstat(ve)])}catch{P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Vc.isSymbolicLink()||!Vc.isDirectory()||!D(c,Pt)||mr(u,Pt)){P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let ua=await $b(n,Pt);if(ua.dirty){P({path:x,size:null,type:"directory",reason:"gitlink-dirty"});continue}await je({path:x,hash:ua.hash,size:0,type:"file"},{kind:"gitlink",target:ve,realTarget:Pt,stat:Vc,hash:ua.hash})}catch(ua){if(Ja(ua))throw ua;P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let be;try{be=await fe.lstat(ve)}catch(Pt){if(_e(Pt)&&Et.tracked.has(x)){N.set(x,ve);continue}if(!Ie(Pt)&&!_e(Pt))throw Pt;P({path:x,size:null,type:"file",reason:_e(Pt)?"changed-during-read":"unreadable"});continue}if(be.isSymbolicLink()){await yr(ve,x,be);continue}if(!be.isFile()){Et.nestedRepositories.has(x)||P({path:x,size:null,type:"other",reason:"changed-during-read"});continue}let at=Et.trackedObjectIds.get(x),Ue=at?_.get(x):void 0;if(j&&Ue?.gitObjectId!==void 0&&Ue.gitObjectId===at&&!W.has(x)&&!K.has(x)){if(p.length>=r.maxFiles){P({path:x,size:Ue.size,type:"file",reason:"file-count"});continue}if(Ue.size>r.maxFileBytes){P({path:x,size:Ue.size,type:"file",reason:"file-size"});continue}if(k+Ue.size>r.maxTotalBytes){P({path:x,size:Ue.size,type:"file",reason:"total-size"});continue}p.push({...Ue}),k+=Ue.size,V.add(x);continue}let sg=le&&!W.has(x)&&!K.has(x)?at:void 0;await ie(ve,x,be,sg),sg!==void 0&&Ne.add(x)}if(await er(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await Jb(n,e,a,Et,t.gitSelectionHooks?.outputChunkBytes),V.size>0||j&&Ne.size>0){let x=await Iu(n,s,["ls-files","--modified","-z"],zp),ve=new Set;for(let be of x.toString("utf8").split("\0")){let at=Ga(be);at!==null&&ve.add(at)}for(let be of V){if(!ve.has(be))continue;let at=p.find(Ue=>Ue.path===be);me(be,{path:be,size:at?.size??null,type:"file",reason:"changed-during-read"})}for(let be of Ne){if(!ve.has(be))continue;let at=p.find(Ue=>Ue.path===be);at&&delete at.gitObjectId}}for(let x of Et.omissions)P(x);Et.overflow&&L(Et.overflow)}p.sort((I,_)=>I.path.localeCompare(_.path,"en")),v.sort((I,_)=>I.path.localeCompare(_.path,"en"));let oC=Et===null?{provider:"physical-tree",...b?{physicalSelection:b}:{}}:{provider:"git",...Et.evidence?{gitSelection:Et.evidence}:{}},og=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:oC,createdAt:(t.now??new Date).toISOString(),complete:E===0,limits:r,...i?{policy:i.manifest}:{},entries:p,omitted:v,omittedCount:E,...w>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${S}`,hash:S,count:w}}:{}}),vf=og();for(;Xp(vf)>r.maxManifestBytes;){if(v.filter(_=>!Jp(_)).length>0){let _=Math.max(1,Math.ceil(v.length/4));for(let j=0;j<_;j+=1){let W=ju(v);if(W===null)break;y(W)}}else if(p.length>0){let _=Math.max(1,Math.ceil(p.length/4));for(let j of p.splice(-_))E+=1,H(j)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");vf=og()}return vf}async function Qp(e,t,r={}){let n=(await Ee(e.projectRoot))?.native.snapshot??wp;return Du(e,{...r,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 Zp(e,t,r){let i=Xb(e,t);await T($(e,i),i),await re(i,Ur(r))}async function Ka(e,t){let r=Xb(e,t),i=$(e,r);await T(i,r);try{let n=await ku({root:i,file:r,maxBytes:L$,label:"Native baseline snapshot manifest"});return Ur(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var _u,Gp,L$,M$,F$,B$,V$,q$,W$,z$,J$,G$,U$,K$,Y$,X$,Q$,Z$,eO,Ou,Fb,tO,Ua,zp,rO,iO,nO,Up,aO,hO,Fn=A(()=>{"use strict";ue();ot();hr();nr();Q();yt();ds();_u={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Gp=1e3,L$=8*1024*1024,M$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,F$=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),B$=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),V$=new Set(["schema","include","exclude","hash"]),q$=new Set(["provider","gitSelection","physicalSelection","projection"]),W$=new Set(["provider","selection"]),z$=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),J$=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),G$=new Set(["schema","status","before","after"]),U$=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),K$=new Set(["path","hash","size","type","gitObjectId"]),Y$=new Set(["path","size","type","reason"]),X$=new Set(["ref","hash","count"]),Q$=new Set(["change-created","legacy-migration","explicit"]),Z$=new Set(["file","directory","other"]),eO=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"]),Ou=/^[a-f0-9]{64}$/u,Fb=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,tO=new Set(["EACCES","EPERM"]),Ua=64*1024,zp=64*1024,rO=6e4,iO=1e3,nO=2,Up={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},aO={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};hO=(1n<<256n)-1n});var _t,Ya=A(()=>{"use strict";_t=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"})});var Lu=A(()=>{"use strict"});var Qb=A(()=>{"use strict"});var em=A(()=>{"use strict";Lu()});var Zb=A(()=>{"use strict";Lu();em()});var IO,ek=A(()=>{"use strict";IO=da(Cn(),1);Aa();Ci();_n()});var Z2,tk=A(()=>{"use strict";Aa();_n();Z2=4*1024*1024});function jO(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function rk(e,t){return(...r)=>{let i=TO;if(i===null)return t(...r);let n=jO(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}var TO,ik=A(()=>{"use strict";TO=null});var nz,nk=A(()=>{"use strict";ik();xa();nz=rk("hookWritePolicy",async e=>(await dp(e))?.hook??{allow_paths:[]})});var ak=A(()=>{"use strict";Lu();Aa();Qb();Zb();Ci();ek();_n();xa();pp();tk();nk();fp();em()});var ok=A(()=>{"use strict";ak();fs()});import OO from"path";function qs(e,t){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return r}function Vs(e,t){let r=qs(e,t);if(OO.isAbsolute(r)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return r}function HO(e){let t=e.run_retries??"{}",r;try{r=typeof t=="string"?JSON.parse(t):t}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(r))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return r}function ck(e){if(!e.run_id)return null;let t=qs(e,"run_id"),r=qs(e,"skill"),i=qs(e,"skill_version"),n=qs(e,"skill_hash"),a=Vs(e,"pending_ref"),o=Vs(e,"trajectory_ref"),s=Vs(e,"context_ref"),c=Vs(e,"artifacts_ref"),l=Vs(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:r,skillVersion:i,skillHash:n,orchestration:e.orchestration,currentStep:sk(e,"current_step"),iteration:u,pending:sk(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:HO(e)}}var sk,eJ,lk=A(()=>{"use strict";ok();sk=(e,t)=>{let r=e[t];return r==null?null:String(r)};eJ=256*1024});function LO(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)},r=ck(t);if(!r)throw new Error("Invalid Run state: runId must be a non-empty string");return r}function Mu(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,r=Object.keys(t).find(i=>!DO.has(i));if(r)throw new Error(`Invalid Run state: unknown field ${r}`);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 LO(t)}var DO,uk=A(()=>{"use strict";lk();Ya();DO=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"])});import{createHash as MO}from"node:crypto";import{constants as Fu,promises as ut}from"node:fs";import It from"node:path";import{TextDecoder as FO}from"node:util";function zs(e,t){let r=It.relative(e,t);return r===""||!It.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${It.sep}`)}function fk(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ws(e,t){return J({...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 BO(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ji(e,t,r){let i=_t[t];if(r!==void 0&&r!==i)throw new Error(`Native Run ${t} ref must be ${i}`);let n=It.resolve(e),a=It.resolve(n,...i.slice(8).split("/"));if(!zs(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function dk(e){let t=await ut.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await ut.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function tm(e,t){let r=It.resolve(e),i=It.resolve(t);if(!zs(r,i))throw new Error("Native Run path is outside its change");let n=[await dk(r)],a=r;for(let o of It.relative(r,i).split(It.sep).filter(Boolean)){a=It.join(a,o);let s;try{s=await dk(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!zs(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function Bu(e){for(let t of e){let r=await ut.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!BO(t,r)||await ut.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function VO(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Bn(e,t,r,i,n){let a=await tm(e,It.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await ut.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${i} must be a regular file`);if(o.size>r)throw new Error(`${i} exceeds ${r} bytes`);let s=fk(o),c=await ut.realpath(t);if(!zs(a[0].realPath,c))throw new Error(`${i} resolves outside its change`);let l=process.platform==="win32"?Fu.O_RDONLY:Fu.O_RDONLY|Fu.O_NOFOLLOW|Fu.O_NONBLOCK,u;try{u=await ut.open(t,l)}catch(d){throw new Error(`${i} changed while opening`,{cause:d})}try{let[d,f,h]=await Promise.all([u.stat(),ut.lstat(t),ut.realpath(t)]);if(await Bu(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||h!==c||!Ws(s,d)||!Ws(s,f))throw new Error(`${i} changed while opening`);await n?.afterOpen?.();let m=await VO(u,r,i);await n?.beforeFinalCheck?.();let[p,v,g]=await Promise.all([u.stat(),ut.lstat(t),ut.realpath(t)]);if(await Bu(a),!v.isFile()||v.isSymbolicLink()||g!==c||!Ws(s,p)||!Ws(s,v))throw new Error(`${i} changed while reading`);let N;try{N=new FO("utf-8",{fatal:!0}).decode(m)}catch(E){throw new Error(`${i} is not valid UTF-8`,{cause:E})}return{text:N,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function qO(e,t,r){let i=await tm(e,It.dirname(t));if(!i)return{exists:!1};let n;try{n=await ut.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!n.isFile()||n.isSymbolicLink())throw new Error(`${r} must be a regular file`);let a=await ut.realpath(t);if(!zs(i[0].realPath,a))throw new Error(`${r} resolves outside its change`);return await Bu(i),{exists:!0,identity:fk(n),realPath:a}}async function WO(e,t,r,i){let n=await tm(e,It.dirname(t));if(!n){if(!r.exists)return;throw new Error(`${i} parent changed before commit`)}let a;try{a=await ut.lstat(t)}catch(o){if(o.code==="ENOENT"&&!r.exists)return;throw new Error(`${i} changed before commit`,{cause:o})}if(!r.exists||!a.isFile()||a.isSymbolicLink()||!Ws(r.identity,a)||await ut.realpath(t)!==r.realPath)throw new Error(`${i} changed before commit`);await Bu(n)}async function Vu(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let r=e.expected??await qO(e.changeDir,e.file,e.label);if(r.exists&&r.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await ge(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await WO(e.changeDir,e.file,r,e.label)}});let i=await Bn(e.changeDir,e.file,e.maxBytes,e.label);if(!i||i.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function hk(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} contains invalid JSON`,{cause:r})}}function pk(e){return`${JSON.stringify(e,null,2)}
|
|
189
|
+
${Buffer.byteLength(i)}:${i}`)}function Jp(e){return e.reason==="git-enumeration-limit"||e.reason==="git-selection-changed"||e.reason==="physical-enumeration-limit"||e.reason==="physical-selection-changed"}function ju(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(!Jp(r))return e.splice(t,1),r}return null}function Wi(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Rt(r,i)?J(r,i):J(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function bO(e,t,r,i){if(!B(i))return{status:"budget-exhausted"};let n;try{n=await fe.open(e,"r")}catch(c){if(!B(i))return{status:"budget-exhausted"};throw c}if(!B(i))return await n.close(),{status:"budget-exhausted"};let a=$u("sha256"),o=Buffer.allocUnsafe(Math.min(64*1024,t+1)),s=0;try{if(!B(i))return{status:"budget-exhausted"};let c=await n.stat();if(!B(i))return{status:"budget-exhausted"};if(!c.isFile()||!Wi(r,c))return{status:"changed"};for(;;){if(!B(i))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(!B(i))return{status:"budget-exhausted"};if(u.bytesRead===0){if(!B(i))return{status:"budget-exhausted"};let d=await n.stat();return B(i)?!d.isFile()||!Wi(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 zt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Jt(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function za(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ar(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function Yb(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 r=q.posix.normalize(e);if(r!==e||q.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function kO(e,t){let r=zt(e,`Native snapshot entry ${t}`);Jt(r,K$,`Native snapshot entry ${t}`);let i=Yb(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!Ou.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let n={path:i,hash:r.hash,size:Ar(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!Fb.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function SO(e,t){let r=zt(e,`Native snapshot omission ${t}`);if(Jt(r,Y$,`Native snapshot omission ${t}`),!Z$.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!eO.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:Yb(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:Ar(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function EO(e){let t=zt(e,"Native snapshot omission overflow");if(Jt(t,X$,"Native snapshot omission overflow"),typeof t.hash!="string"||!Ou.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:za(t.count,"Native snapshot omission overflow count")}}function Wa(e,t){let r=zt(e,t);if(Jt(r,J$,t),typeof r.hash!="string"||!Ou.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let i=Ar(r.recordCount,`${t} recordCount`),n=Ar(r.storedRecordCount,`${t} storedRecordCount`),a=Ar(r.stdoutBytes,`${t} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function Db(e){let t=zt(e,"Native Git selection evidence");if(Jt(t,z$,"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 r=Wa(t.stageBefore,"Native Git selection stageBefore"),i=Wa(t.combined,"Native Git selection combined"),n=Wa(t.stageAfter,"Native Git selection stageAfter"),a=Wa(t.finalStageBefore,"Native Git selection finalStageBefore"),o=Wa(t.finalCombined,"Native Git selection finalCombined"),s=Wa(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!zi(r,n)||!zi(n,a)||!zi(i,o)||!zi(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:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Lb(e,t){let r=zt(e,t);if(Jt(r,U$,t),typeof r.hash!="string"||!Ou.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let i=Ar(r.visitedNodeCount,`${t} visitedNodeCount`),n=Ar(r.recordCount,`${t} recordCount`),a=Ar(r.storedRecordCount,`${t} storedRecordCount`),o=Ar(r.encodedBytes,`${t} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function PO(e){let t=zt(e,"Native physical selection evidence");if(Jt(t,G$,"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 r=Lb(t.before,"Native physical selection before"),i=Lb(t.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!Gb(r,i);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:r,after:i}}function Kr(e){let t=zt(e,"Native content snapshot manifest");if(Jt(t,F$,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!Q$.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let k=zt(t.capture,"Native content snapshot capture");if(Jt(k,q$,"Native content snapshot capture"),k.provider!=="git"&&k.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let R=k.gitSelection===void 0?void 0:Db(k.gitSelection),b=k.physicalSelection===void 0?void 0:PO(k.physicalSelection),y=null;if(k.projection!==void 0){let P=zt(k.projection,"Native content snapshot projection");if(Jt(P,W$,"Native content snapshot projection"),P.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");y={provider:"git",...P.selection===void 0?{}:{selection:Db(P.selection)}}}if(k.provider==="git"){if(b||y)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...R?{gitSelection:R}:{}}}else{if(R)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(b&&y)throw new Error("Native physical-tree capture cannot combine selection and projection");r=y?{provider:"physical-tree",projection:y}:{provider:"physical-tree",...b?{physicalSelection:b}:{}}}}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 i=zt(t.limits,"Native content snapshot limits");Jt(i,B$,"Native content snapshot limits");let n={maxFiles:za(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:za(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:za(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:za(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:za(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let k=zt(t.policy,"Native snapshot policy");if(Jt(k,V$,"Native snapshot policy"),k.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(k.include)||!Array.isArray(k.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=Kb({include:k.include,exclude:k.exclude,hash:k.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(kO),s=t.omitted.map(SO),c=Ar(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:EO(t.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(k=>k.size>n.maxFileBytes)||o.reduce((k,R)=>k+R.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(k=>k.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>Gp||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(k=>k.reason==="git-enumeration-limit"),f=s.filter(k=>k.reason==="git-selection-changed");for(let k of[...d,...f])if(k.path!=="."||k.size!==null||k.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=r?.provider==="git"?r.gitSelection:r?.projection?.selection,m=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(p!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(k=>k.reason==="physical-enumeration-limit"),g=s.filter(k=>k.reason==="physical-selection-changed");for(let k of[...v,...g])if(k.path!=="."||k.size!==null||k.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||g.length>1)throw new Error("Native physical selection omissions must not be duplicated");let N=r?.physicalSelection,E=N?.status==="overflow"||N?.status==="overflow-and-changed",w=N?.status==="changed"||N?.status==="overflow-and-changed";if(E!==(v.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(w!==(g.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let S={schema:"comet.native.content-snapshot.v1",origin:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(Xp(S)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return S}async function Hu(e,t,r={}){let i=Kr(t);if(i.capture?.provider==="git"||i.capture?.projection||i.capture?.physicalSelection)return i;let n=q.resolve(e.projectRoot),a=Bb(r),o=Vb(r.gitSelectionLimits),s=await zb(a,e,o,r.gitSelectionHooks);if(s===null)return i;let c=new Set(Ub(s).filter(b=>Ms(e,b))),l=[...s.gitlinks].filter(b=>c.has(b)),u=[...s.nestedRepositories].filter(b=>Ms(e,b)),d=(b,y)=>y.some(P=>b===P||b.startsWith(`${P}/`)),f=b=>d(b,l),h=b=>d(b,u),m=[...i.entries.map(b=>b.path),...i.omitted.flatMap(b=>b.type==="directory"?[b.path,`${b.path}/`]:[b.path])].filter(b=>!c.has(b)&&!f(b)&&!h(b)),p=await cO(a,n,m),v=i.entries.filter(b=>!f(b.path)&&!h(b.path)&&Ms(e,b.path)&&(c.has(b.path)||!p.has(b.path)));await Jb(a,e,o,s,r.gitSelectionHooks?.outputChunkBytes);let g=[...s.omissions];for(let b of l)g.push({path:b,size:null,type:"directory",reason:"legacy-gitlink-boundary"});v.sort((b,y)=>b.path.localeCompare(y.path,"en"));let N=i.omitted.filter(b=>f(b.path)||h(b.path)||!Ms(e,b.path)?!1:p.has(b.path)?c.has(b.path)||[...c].some(y=>y.startsWith(`${b.path}/`)):!0);for(let b of g)N.some(y=>y.path===b.path&&y.reason===b.reason)||N.push(b);N.sort((b,y)=>b.path.localeCompare(y.path,"en"));let E=i.omissionOverflow?.count??0,w=i.omissionOverflow?.hash??F("comet.native.snapshot-omission-overflow.v1");s.overflow&&(E+=s.overflow.count,w=Bs(w,"git-selection",{source:"git-selection",...s.overflow}));let S=b=>{E+=1,w=Bs(w,"omission",b)};for(;N.length>Gp;){let b=ju(N);if(b===null)throw new Error("Projected Native snapshot has too many required selection-integrity omissions");S(b)}let k=()=>({...i,capture:{provider:"physical-tree",projection:{provider:"git",...s.evidence?{selection:s.evidence}:{}}},complete:N.length+E===0,entries:v,omitted:N,omittedCount:N.length+E,...E>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${w}`,hash:w,count:E}}:{}}),R=k();for(;Xp(R)>i.limits.maxManifestBytes;){let b=ju(N);if(b===null)throw new Error("Projected Native snapshot cannot fit its manifest byte limit");S(b),R=k()}return Kr(R)}function Xb(e,t){if(!M$.test(t))throw new Error(`Invalid Native change name: ${t}`);return q.join(M(e,t),"baseline-manifest.json")}async function Du(e,t={}){let r={maxFiles:t.limits?.maxFiles??_u.maxFiles,maxFileBytes:t.limits?.maxFileBytes??_u.maxFileBytes,maxTotalBytes:t.limits?.maxTotalBytes??_u.maxTotalBytes,maxManifestBytes:t.limits?.maxManifestBytes??_u.maxManifestBytes,...t.limits?.maxDurationMs===void 0?{}:{maxDurationMs:t.limits.maxDurationMs}},i=Kb(t.policy),n=Bb({...t,deadlineMs:t.deadlineMs??r.maxDurationMs}),a=Vb(t.gitSelectionLimits),o=oO(t.physicalSelectionLimits);if(r.maxFiles<1||r.maxFileBytes<1||r.maxTotalBytes<1||r.maxManifestBytes<1)throw new Error("Native snapshot limits must be positive");let s=q.resolve(e.projectRoot),c=await fe.realpath(s),l=q.resolve(e.nativeRoot),u=await fe.realpath(l),d=q.resolve(e.runtimeDir),f=q.resolve(e.configFile),h=q.join(s,".comet","current-change.json"),m=gO(s,t.denylist??[]),p=[],v=[],g=new Map,N=new Map,E=0,w=0,S=F("comet.native.snapshot-omission-overflow.v1"),k=0,R=!1,b=null,y=I=>{w+=1,S=Bs(S,"omission",I)},P=I=>{if(E+=1,v.length<Gp){v.push(I);return}if(Jp(I)){let _=ju(v);if(_===null)throw new Error("Native snapshot has too many required selection-integrity omissions");y(_),v.push(I);return}y(I)},L=I=>{E+=I.count,w+=I.count,S=Bs(S,"git-selection",{source:"git-selection",...I})},H=I=>{w+=1,S=Bs(S,"manifest-entry",{reason:"manifest-size",entry:I})},je=async(I,_)=>{p.push(I),k+=I.size,g.set(I.path,_),R||(R=!0,await t.gitSelectionHooks?.afterFirstEntryCaptured?.(I.path))},me=(I,_)=>{let j=p.findIndex(le=>le.path===I);if(j<0)return;let[W]=p.splice(j,1);k-=W.size,g.delete(I),P(_)},ie=async(I,_,j,W)=>{if(!j.isFile()||j.isSymbolicLink()||!B(n))return;let le;try{le=await fe.realpath(I)}catch(x){if(!B(n))return;if(!Ie(x)&&!_e(x))throw x;P({path:_,size:j.size,type:"file",reason:_e(x)?"changed-during-read":"unreadable"});return}if(!B(n)||!D(c,le)||vr(u,le))return;if(p.length>=r.maxFiles){P({path:_,size:j.size,type:"file",reason:"file-count"});return}if(j.size>r.maxFileBytes){P({path:_,size:j.size,type:"file",reason:"file-size"});return}if(k+j.size>r.maxTotalBytes){P({path:_,size:j.size,type:"file",reason:"total-size"});return}let K,V,Ne;try{if(K=await bO(le,j.size,j,n),K.status==="budget-exhausted"||!B(n))return;if(K.status==="changed"){P({path:_,size:null,type:"file",reason:"changed-during-read"});return}if(!B(n)||(Ne=await fe.realpath(I),!B(n)))return;V=await fe.lstat(I)}catch(x){if(!B(n))return;if(!Ie(x)&&!_e(x))throw x;P({path:_,size:j.size,type:"file",reason:_e(x)?"changed-during-read":"unreadable"});return}if(B(n)){if(K.bytes!==j.size||Ne!==le||!Wi(j,K.finalStat)||!Wi(K.finalStat,V)||!V.isFile()||V.isSymbolicLink()||V.size!==j.size||V.mtimeMs!==j.mtimeMs||V.ctimeMs!==j.ctimeMs){P({path:_,size:V.isFile()?V.size:null,type:V.isFile()?"file":"other",reason:"changed-during-read"});return}B(n)&&await je({path:_,hash:K.hash,size:V.size,type:"file",...W===void 0?{}:{gitObjectId:W}},{kind:"file",target:I,realTarget:le,stat:V})}},Nr=async(I,_,j)=>{if(!B(n))return;let W,le,K;try{if(W=await fe.readlink(I,{encoding:"buffer"}),!B(n)||(K=await fe.lstat(I),!B(n)))return;le=await fe.readlink(I,{encoding:"buffer"})}catch(x){if(!B(n))return;if(!Ie(x)&&!_e(x))throw x;P({path:_,size:null,type:"other",reason:_e(x)?"changed-during-read":"unreadable"});return}if(!B(n))return;if(!K.isSymbolicLink()||!Wi(j,K)||K.mtimeMs!==j.mtimeMs||K.ctimeMs!==j.ctimeMs||!W.equals(le)){P({path:_,size:null,type:"other",reason:"changed-during-read"});return}let V=W.byteLength;if(p.length>=r.maxFiles){P({path:_,size:V,type:"other",reason:"file-count"});return}if(V>r.maxFileBytes){P({path:_,size:V,type:"other",reason:"file-size"});return}if(k+V>r.maxTotalBytes){P({path:_,size:V,type:"other",reason:"total-size"});return}let Ne=$u("sha256").update("symlink\0").update(W).digest("hex");B(n)&&await je({path:_,hash:Ne,size:V,type:"file"},{kind:"symlink",target:I,rawTarget:W,stat:K})},tr=async()=>{for(let[I,_]of[...g]){if(!B(n))return;if(_.kind==="file"){let V,Ne;try{if(V=await fe.realpath(_.target),!B(n))return;Ne=await fe.lstat(_.target)}catch(x){if(!B(n))return;if(!Ie(x)&&!_e(x))throw x;me(I,{path:I,size:null,type:"file",reason:Ie(x)?"unreadable":"changed-during-read"});continue}if(!B(n))return;(V!==_.realTarget||!Ne.isFile()||Ne.isSymbolicLink()||!Wi(_.stat,Ne)||Ne.size!==_.stat.size||Ne.mtimeMs!==_.stat.mtimeMs||Ne.ctimeMs!==_.stat.ctimeMs)&&me(I,{path:I,size:Ne.isFile()?Ne.size:null,type:Ne.isFile()?"file":"other",reason:"changed-during-read"});continue}if(_.kind==="symlink"){let V,Ne;try{if(V=await fe.lstat(_.target),!B(n))return;Ne=await fe.readlink(_.target,{encoding:"buffer"})}catch(x){if(!B(n))return;if(!Ie(x)&&!_e(x))throw x;me(I,{path:I,size:null,type:"other",reason:Ie(x)?"unreadable":"changed-during-read"});continue}if(!B(n))return;(!V.isSymbolicLink()||!Wi(_.stat,V)||V.mtimeMs!==_.stat.mtimeMs||V.ctimeMs!==_.stat.ctimeMs||!_.rawTarget.equals(Ne))&&me(I,{path:I,size:null,type:"other",reason:"changed-during-read"});continue}let j,W;try{if(j=await fe.realpath(_.target),!B(n))return;W=await fe.lstat(_.target)}catch{if(!B(n))return;me(I,{path:I,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!B(n))return;if(!(j===_.realTarget&&W.isDirectory()&&!W.isSymbolicLink()&&Wi(_.stat,W)&&D(c,j)&&!vr(u,j))){me(I,{path:I,size:null,type:"directory",reason:"gitlink-changed"});continue}let K;try{if(!B(n))return;K=await $b(n,j)}catch(V){if(Ja(V))throw V;me(I,{path:I,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(!B(n))return;K.dirty?me(I,{path:I,size:null,type:"directory",reason:"gitlink-dirty"}):K.hash!==_.hash&&me(I,{path:I,size:null,type:"directory",reason:"gitlink-changed"})}for(let[I,_]of N){if(!B(n))return;try{let j=await fe.lstat(_);if(!B(n))return;P({path:I,size:j.isFile()?j.size:null,type:j.isFile()?"file":j.isDirectory()?"directory":"other",reason:"changed-during-read"})}catch(j){if(!B(n))return;if(_e(j))continue;if(!Ie(j))throw j;P({path:I,size:null,type:"file",reason:"unreadable"})}}},Et=await zb(n,e,a,t.gitSelectionHooks);if(Et===null){let I=await Tb({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o,hooks:t.physicalSelectionHooks});await t.physicalSelectionHooks?.afterInitialSelection?.();for(let W of I.records){if(W.type!=="file"&&W.type!=="symlink"||g.has(W.path))continue;if(mr(n)<1)break;if(!Hb(i,W.path,n))continue;if(mr(n)<1)break;let le=q.resolve(s,...W.path.split("/")),K;try{K=await fe.lstat(le)}catch(V){if(!B(n))break;if(!Ie(V)&&!_e(V))throw V;P({path:W.path,size:null,type:"file",reason:_e(V)?"changed-during-read":"unreadable"});continue}if(mr(n)<1)break;if(W.type==="symlink"&&K.isSymbolicLink()){if(await Nr(le,W.path,K),mr(n)<1)break;continue}if(W.type!=="file"||!K.isFile()||K.isSymbolicLink()){P({path:W.path,size:K.isFile()?K.size:null,type:K.isDirectory()?"directory":K.isFile()?"file":"other",reason:"changed-during-read"});continue}if(await ie(le,W.path,K),mr(n)<1)break}mr(n)>=1&&await tr();let _=await Tb({execution:n,paths:e,physicalProjectRoot:c,physicalNativeRoot:u,denylist:m,policy:i,limits:o}),j=mO(I.evidence,_.evidence);b=j.evidence;for(let W of[...I.omissions,..._.omissions,...j.omissions])v.some(le=>le.path===W.path&&le.reason===W.reason)||P(W)}else{await t.gitSelectionHooks?.afterInitialSelection?.();let I=t.incrementalBaseline,_=new Map,j=!1;if(I){let x=Kr(I);for(let ve of x.entries)ve.gitObjectId!==void 0&&_.set(ve.path,ve);j=_.size>0}let W=new Set,le=!0;try{let x=await Fs(n,s,["ls-files","-v","-z"],{...a,...t.gitSelectionHooks?.outputChunkBytes===void 0?{}:{outputChunkBytes:t.gitSelectionHooks.outputChunkBytes}});if(x.overflow)j=!1,le=!1,_.clear();else for(let ve of x.records){let be=Tu(ve),at=be.indexOf(" "),Ue=at<0?null:Ga(be.slice(at+1));if(at!==1||Ue===null)throw new Error("Native Git snapshot provider returned a malformed tagged record");be[0]!=="H"&&W.add(Ue)}}catch(x){if(Ja(x))throw x;j=!1,le=!1,_.clear()}let K=new Set;try{let x=await Iu(n,s,["ls-files","--modified","-z"],zp);for(let ve of x.toString("utf8").split("\0")){let be=Ga(ve);be!==null&&K.add(be)}}catch{j=!1,le=!1,_.clear()}let V=new Set,Ne=new Set;for(let x of Ub(Et)){if(g.has(x)||!Ms(e,x))continue;if(mr(n)<1)break;if(!Hb(i,x,n))continue;if(mr(n)<1)break;let ve=q.resolve(s,...x.split("/"));if(ve===f||ve===h||vr(d,ve)||m.some(Pt=>vr(Pt,ve)))continue;if(Et.gitlinks.has(x)){if(p.length>=r.maxFiles){P({path:x,size:0,type:"file",reason:"file-count"});continue}let Pt,Vc;try{[Pt,Vc]=await Promise.all([fe.realpath(ve),fe.lstat(ve)])}catch{P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}if(Vc.isSymbolicLink()||!Vc.isDirectory()||!D(c,Pt)||vr(u,Pt)){P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"});continue}try{let ua=await $b(n,Pt);if(ua.dirty){P({path:x,size:null,type:"directory",reason:"gitlink-dirty"});continue}await je({path:x,hash:ua.hash,size:0,type:"file"},{kind:"gitlink",target:ve,realTarget:Pt,stat:Vc,hash:ua.hash})}catch(ua){if(Ja(ua))throw ua;P({path:x,size:null,type:"directory",reason:"gitlink-unavailable"})}continue}let be;try{be=await fe.lstat(ve)}catch(Pt){if(_e(Pt)&&Et.tracked.has(x)){N.set(x,ve);continue}if(!Ie(Pt)&&!_e(Pt))throw Pt;P({path:x,size:null,type:"file",reason:_e(Pt)?"changed-during-read":"unreadable"});continue}if(be.isSymbolicLink()){await Nr(ve,x,be);continue}if(!be.isFile()){Et.nestedRepositories.has(x)||P({path:x,size:null,type:"other",reason:"changed-during-read"});continue}let at=Et.trackedObjectIds.get(x),Ue=at?_.get(x):void 0;if(j&&Ue?.gitObjectId!==void 0&&Ue.gitObjectId===at&&!W.has(x)&&!K.has(x)){if(p.length>=r.maxFiles){P({path:x,size:Ue.size,type:"file",reason:"file-count"});continue}if(Ue.size>r.maxFileBytes){P({path:x,size:Ue.size,type:"file",reason:"file-size"});continue}if(k+Ue.size>r.maxTotalBytes){P({path:x,size:Ue.size,type:"file",reason:"total-size"});continue}p.push({...Ue}),k+=Ue.size,V.add(x);continue}let sg=le&&!W.has(x)&&!K.has(x)?at:void 0;await ie(ve,x,be,sg),sg!==void 0&&Ne.add(x)}if(await tr(),await t.gitSelectionHooks?.afterContentRevalidation?.(),await Jb(n,e,a,Et,t.gitSelectionHooks?.outputChunkBytes),V.size>0||j&&Ne.size>0){let x=await Iu(n,s,["ls-files","--modified","-z"],zp),ve=new Set;for(let be of x.toString("utf8").split("\0")){let at=Ga(be);at!==null&&ve.add(at)}for(let be of V){if(!ve.has(be))continue;let at=p.find(Ue=>Ue.path===be);me(be,{path:be,size:at?.size??null,type:"file",reason:"changed-during-read"})}for(let be of Ne){if(!ve.has(be))continue;let at=p.find(Ue=>Ue.path===be);at&&delete at.gitObjectId}}for(let x of Et.omissions)P(x);Et.overflow&&L(Et.overflow)}p.sort((I,_)=>I.path.localeCompare(_.path,"en")),v.sort((I,_)=>I.path.localeCompare(_.path,"en"));let oC=Et===null?{provider:"physical-tree",...b?{physicalSelection:b}:{}}:{provider:"git",...Et.evidence?{gitSelection:Et.evidence}:{}},og=()=>({schema:"comet.native.content-snapshot.v1",origin:t.origin??"explicit",capture:oC,createdAt:(t.now??new Date).toISOString(),complete:E===0,limits:r,...i?{policy:i.manifest}:{},entries:p,omitted:v,omittedCount:E,...w>0?{omissionOverflow:{ref:`native-snapshot://omitted-overflow/${S}`,hash:S,count:w}}:{}}),vf=og();for(;Xp(vf)>r.maxManifestBytes;){if(v.filter(_=>!Jp(_)).length>0){let _=Math.max(1,Math.ceil(v.length/4));for(let j=0;j<_;j+=1){let W=ju(v);if(W===null)break;y(W)}}else if(p.length>0){let _=Math.max(1,Math.ceil(p.length/4));for(let j of p.splice(-_))E+=1,H(j)}else throw new Error("Native snapshot manifest byte limit is too small for its metadata");vf=og()}return vf}async function Qp(e,t,r={}){let n=(await Ee(e.projectRoot))?.native.snapshot??wp;return Du(e,{...r,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 Zp(e,t,r){let i=Xb(e,t);await T($(e,i),i),await re(i,Kr(r))}async function Ka(e,t){let r=Xb(e,t),i=$(e,r);await T(i,r);try{let n=await ku({root:i,file:r,maxBytes:L$,label:"Native baseline snapshot manifest"});return Kr(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var _u,Gp,L$,M$,F$,B$,V$,q$,W$,z$,J$,G$,U$,K$,Y$,X$,Q$,Z$,eO,Ou,Fb,tO,Ua,zp,rO,iO,nO,Up,aO,hO,Fn=A(()=>{"use strict";ue();ot();pr();ar();Q();yt();ds();_u={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Gp=1e3,L$=8*1024*1024,M$=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,F$=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),B$=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),V$=new Set(["schema","include","exclude","hash"]),q$=new Set(["provider","gitSelection","physicalSelection","projection"]),W$=new Set(["provider","selection"]),z$=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),J$=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),G$=new Set(["schema","status","before","after"]),U$=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),K$=new Set(["path","hash","size","type","gitObjectId"]),Y$=new Set(["path","size","type","reason"]),X$=new Set(["ref","hash","count"]),Q$=new Set(["change-created","legacy-migration","explicit"]),Z$=new Set(["file","directory","other"]),eO=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"]),Ou=/^[a-f0-9]{64}$/u,Fb=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,tO=new Set(["EACCES","EPERM"]),Ua=64*1024,zp=64*1024,rO=6e4,iO=1e3,nO=2,Up={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},aO={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};hO=(1n<<256n)-1n});var _t,Ya=A(()=>{"use strict";_t=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"})});var Lu=A(()=>{"use strict"});var Qb=A(()=>{"use strict"});var em=A(()=>{"use strict";Lu()});var Zb=A(()=>{"use strict";Lu();em()});var IO,ek=A(()=>{"use strict";IO=da(Cn(),1);Aa();Ci();_n()});var Z2,tk=A(()=>{"use strict";Aa();_n();Z2=4*1024*1024});function jO(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function rk(e,t){return(...r)=>{let i=TO;if(i===null)return t(...r);let n=jO(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}var TO,ik=A(()=>{"use strict";TO=null});var nz,nk=A(()=>{"use strict";ik();xa();nz=rk("hookWritePolicy",async e=>(await dp(e))?.hook??{allow_paths:[]})});var ak=A(()=>{"use strict";Lu();Aa();Qb();Zb();Ci();ek();_n();xa();pp();tk();nk();fp();em()});var ok=A(()=>{"use strict";ak();fs()});import OO from"path";function qs(e,t){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`Invalid Run state: ${t} must be a non-empty string`);return r}function Vs(e,t){let r=qs(e,t);if(OO.isAbsolute(r)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${t} must stay inside the change directory`);return r}function HO(e){let t=e.run_retries??"{}",r;try{r=typeof t=="string"?JSON.parse(t):t}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(r))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return r}function ck(e){if(!e.run_id)return null;let t=qs(e,"run_id"),r=qs(e,"skill"),i=qs(e,"skill_version"),n=qs(e,"skill_hash"),a=Vs(e,"pending_ref"),o=Vs(e,"trajectory_ref"),s=Vs(e,"context_ref"),c=Vs(e,"artifacts_ref"),l=Vs(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:r,skillVersion:i,skillHash:n,orchestration:e.orchestration,currentStep:sk(e,"current_step"),iteration:u,pending:sk(e,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:e.run_status,retries:HO(e)}}var sk,eJ,lk=A(()=>{"use strict";ok();sk=(e,t)=>{let r=e[t];return r==null?null:String(r)};eJ=256*1024});function LO(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)},r=ck(t);if(!r)throw new Error("Invalid Run state: runId must be a non-empty string");return r}function Mu(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid Run state: stored value must be an object");let t=e,r=Object.keys(t).find(i=>!DO.has(i));if(r)throw new Error(`Invalid Run state: unknown field ${r}`);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 LO(t)}var DO,uk=A(()=>{"use strict";lk();Ya();DO=new Set(["runId","skill","skillVersion","skillHash","orchestration","currentStep","iteration","pending","pendingRef","trajectoryRef","contextRef","artifactsRef","checkpointRef","status","retries"])});import{createHash as MO}from"node:crypto";import{constants as Fu,promises as ut}from"node:fs";import It from"node:path";import{TextDecoder as FO}from"node:util";function zs(e,t){let r=It.relative(e,t);return r===""||!It.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${It.sep}`)}function fk(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ws(e,t){return J({...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 BO(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Ji(e,t,r){let i=_t[t];if(r!==void 0&&r!==i)throw new Error(`Native Run ${t} ref must be ${i}`);let n=It.resolve(e),a=It.resolve(n,...i.slice(8).split("/"));if(!zs(n,a))throw new Error("Native Run path must stay inside its Runtime root");return a}async function dk(e){let t=await ut.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native Run parent must be a real directory: ${e}`);return{path:e,realPath:await ut.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function tm(e,t){let r=It.resolve(e),i=It.resolve(t);if(!zs(r,i))throw new Error("Native Run path is outside its change");let n=[await dk(r)],a=r;for(let o of It.relative(r,i).split(It.sep).filter(Boolean)){a=It.join(a,o);let s;try{s=await dk(a)}catch(c){if(c.code==="ENOENT")return null;throw c}if(!zs(n[0].realPath,s.realPath))throw new Error(`Native Run parent resolves outside its change: ${a}`);n.push(s)}return n}async function Bu(e){for(let t of e){let r=await ut.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!BO(t,r)||await ut.realpath(t.path)!==t.realPath)throw new Error(`Native Run parent changed during I/O: ${t.path}`)}}async function VO(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Bn(e,t,r,i,n){let a=await tm(e,It.dirname(t));if(!a)return null;await n?.afterParentChainCaptured?.();let o;try{o=await ut.lstat(t)}catch(d){if(d.code==="ENOENT")return null;throw d}if(!o.isFile()||o.isSymbolicLink())throw new Error(`${i} must be a regular file`);if(o.size>r)throw new Error(`${i} exceeds ${r} bytes`);let s=fk(o),c=await ut.realpath(t);if(!zs(a[0].realPath,c))throw new Error(`${i} resolves outside its change`);let l=process.platform==="win32"?Fu.O_RDONLY:Fu.O_RDONLY|Fu.O_NOFOLLOW|Fu.O_NONBLOCK,u;try{u=await ut.open(t,l)}catch(d){throw new Error(`${i} changed while opening`,{cause:d})}try{let[d,f,h]=await Promise.all([u.stat(),ut.lstat(t),ut.realpath(t)]);if(await Bu(a),!d.isFile()||!f.isFile()||f.isSymbolicLink()||h!==c||!Ws(s,d)||!Ws(s,f))throw new Error(`${i} changed while opening`);await n?.afterOpen?.();let m=await VO(u,r,i);await n?.beforeFinalCheck?.();let[p,v,g]=await Promise.all([u.stat(),ut.lstat(t),ut.realpath(t)]);if(await Bu(a),!v.isFile()||v.isSymbolicLink()||g!==c||!Ws(s,p)||!Ws(s,v))throw new Error(`${i} changed while reading`);let N;try{N=new FO("utf-8",{fatal:!0}).decode(m)}catch(E){throw new Error(`${i} is not valid UTF-8`,{cause:E})}return{text:N,target:{exists:!0,identity:s,realPath:c}}}finally{await u.close()}}async function qO(e,t,r){let i=await tm(e,It.dirname(t));if(!i)return{exists:!1};let n;try{n=await ut.lstat(t)}catch(o){if(o.code==="ENOENT")return{exists:!1};throw o}if(!n.isFile()||n.isSymbolicLink())throw new Error(`${r} must be a regular file`);let a=await ut.realpath(t);if(!zs(i[0].realPath,a))throw new Error(`${r} resolves outside its change`);return await Bu(i),{exists:!0,identity:fk(n),realPath:a}}async function WO(e,t,r,i){let n=await tm(e,It.dirname(t));if(!n){if(!r.exists)return;throw new Error(`${i} parent changed before commit`)}let a;try{a=await ut.lstat(t)}catch(o){if(o.code==="ENOENT"&&!r.exists)return;throw new Error(`${i} changed before commit`,{cause:o})}if(!r.exists||!a.isFile()||a.isSymbolicLink()||!Ws(r.identity,a)||await ut.realpath(t)!==r.realPath)throw new Error(`${i} changed before commit`);await Bu(n)}async function Vu(e){if(Buffer.byteLength(e.content,"utf8")>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);let r=e.expected??await qO(e.changeDir,e.file,e.label);if(r.exists&&r.identity.size>e.maxBytes)throw new Error(`${e.label} exceeds ${e.maxBytes} bytes`);await ge(e.file,e.content,{containedRoot:e.changeDir,beforeCommit:async()=>{await e.hooks?.beforeCommit?.(),await WO(e.changeDir,e.file,r,e.label)}});let i=await Bn(e.changeDir,e.file,e.maxBytes,e.label);if(!i||i.text!==e.content)throw new Error(`${e.label} commit could not be verified`)}function hk(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} contains invalid JSON`,{cause:r})}}function pk(e){return`${JSON.stringify(e,null,2)}
|
|
190
190
|
`}function Gi(e){return Mu(e)}async function Ve(e,t){let r=Ji(e,"stateRef"),i=await Bn(e,r,tt.runStateBytes,"Native Run state",t);return i?Mu(hk(i.text,"Native Run state")):null}async function Vn(e,t,r){let i=Mu(t);await Vu({changeDir:e,file:Ji(e,"stateRef"),content:pk(i),maxBytes:tt.runStateBytes,label:"Native Run state",hooks:r})}async function dt(e,t,r){let i=Ji(e,"trajectoryRef",t),n=await Bn(e,i,tt.trajectoryBytes,"Native Run trajectory",r);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>tt.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${tt.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 mk(e,t,r){return(await Bn(e,Ji(e,"trajectoryRef",t),tt.trajectoryBytes,"Native Run trajectory",r))?.text??null}async function vk(e,t,r,i,n){if(!/^[a-f0-9]{64}$/u.test(i))throw new Error("Native Run trajectory expected hash is invalid");let a=Ji(e,"trajectoryRef",t),o=await Bn(e,a,tt.trajectoryBytes,"Native Run trajectory");if(!o)throw new Error("Native Run trajectory disappeared before repair");if(MO("sha256").update(o.text,"utf8").digest("hex")!==i)throw new Error("Native Run trajectory changed before repair");await Vu({changeDir:e,file:a,content:r,maxBytes:tt.trajectoryBytes,label:"Native Run trajectory",expected:o.target,hooks:n})}async function gk(e,t,r,i){let n=Ji(e,"trajectoryRef",t),a=`${JSON.stringify(r)}
|
|
191
|
-
`;if(Buffer.byteLength(a,"utf8")>tt.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${tt.trajectoryEventBytes} bytes`);let o=await Bn(e,n,tt.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=tt.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${tt.trajectoryEvents} events`);await Vu({changeDir:e,file:n,content:`${o?.text??""}${a}`,maxBytes:tt.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:i})}async function Xa(e,t,r){let i=await Bn(e,Ji(e,"checkpointRef",t),tt.checkpointBytes,"Native Run checkpoint",r);return i?hk(i.text,"Native Run checkpoint"):null}async function wk(e,t,r,i){await Vu({changeDir:e,file:Ji(e,"checkpointRef",t),content:pk(r),maxBytes:tt.checkpointBytes,label:"Native Run checkpoint",hooks:i})}var tt,Ui=A(()=>{"use strict";Ya();uk();ue();
|
|
192
|
-
`)])}catch(d){if(!YO(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=i}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:rm(t),targetHash:rm(l),tailHash:rm(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function yk(e,t){let r=UO(e,t);await T($(e,r),r);let i=M(e,t),n=await mk(i,_t.trajectoryRef);return n===null?{status:"clean",file:r}:XO(r,Buffer.from(n))}async function Qa(e,t){let r=await yk(e,t);return"inspection"in r?r.inspection:r}async function Wu(e,t){let r=await Qa(e,t);if(r.status!=="clean")throw new qu(r)}async function Nk(e,t,r){return de(e,`repair trajectory tail for ${t}`,async()=>{let i=await yk(e,t);if(!("inspection"in i)){if(i.status==="clean")return null;throw new qu(i)}try{await vk(M(e,t),_t.trajectoryRef,i.targetContent,i.inspection.originalHash,{beforeCommit:r?.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 Qa(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return i.inspection})}var GO,qu,Js=A(()=>{"use strict";Ya();et();Q();Ui();GO=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,qu=class extends Error{constructor(r){super(r.status==="repairable"?`Native trajectory has an incomplete final line at ${r.file}:${r.line}; run doctor --repair`:`Native trajectory is invalid at ${r.file}:${r.line}: ${r.message}`);this.inspection=r;this.name="NativeTrajectoryRepairRequiredError"}inspection;code="native-trajectory-tail-repair-required"}});import{createHash as QO}from"node:crypto";import{promises as zu}from"node:fs";import
|
|
193
|
-
${t}`).digest("hex")}async function kk(e,t){let r=await zu.realpath(t),i=await zu.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=nm==="win32"?
|
|
191
|
+
`;if(Buffer.byteLength(a,"utf8")>tt.trajectoryEventBytes)throw new Error(`Native Run trajectory event exceeds ${tt.trajectoryEventBytes} bytes`);let o=await Bn(e,n,tt.trajectoryBytes,"Native Run trajectory");if((o?o.text.split(/\r?\n/u).filter(c=>c.length>0).length:0)>=tt.trajectoryEvents)throw new Error(`Native Run trajectory exceeds ${tt.trajectoryEvents} events`);await Vu({changeDir:e,file:n,content:`${o?.text??""}${a}`,maxBytes:tt.trajectoryBytes,label:"Native Run trajectory",expected:o?.target??{exists:!1},hooks:i})}async function Xa(e,t,r){let i=await Bn(e,Ji(e,"checkpointRef",t),tt.checkpointBytes,"Native Run checkpoint",r);return i?hk(i.text,"Native Run checkpoint"):null}async function wk(e,t,r,i){await Vu({changeDir:e,file:Ji(e,"checkpointRef",t),content:pk(r),maxBytes:tt.checkpointBytes,label:"Native Run checkpoint",hooks:i})}var tt,Ui=A(()=>{"use strict";Ya();uk();ue();ar();tt={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024}});import{createHash as zO}from"crypto";import JO from"path";function rm(e){return zO("sha256").update(e).digest("hex")}function UO(e,t){if(!GO.test(t))throw new Error(`Invalid Native change name: ${t}`);return JO.join(M(e,t),"trajectory.jsonl")}function KO(e){let t=e.split(/\n/u),r=0;for(let i=0;i<t.length;i+=1){let n=t[i].endsWith("\r")?t[i].slice(0,-1):t[i];if(n.length!==0){r=i+1;try{JSON.parse(n)}catch(a){return{status:"invalid",line:i+1,message:a.message}}}}return{status:"valid",count:r}}function YO(e,t){if(/Unexpected end|Unterminated string/iu.test(e.message))return!0;let r=/position (\d+)/iu.exec(e.message)?.[1];return r!==void 0&&Number(r)>=Math.max(0,t.length-1)}function XO(e,t){let r=t.lastIndexOf(10),i=t.subarray(0,r+1),n=KO(i.toString("utf8"));if(n.status==="invalid")return{status:"invalid",file:e,line:n.line,message:n.message};if(r===t.length-1)return{status:"clean",file:e};let a=t.subarray(r+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(!YO(d,o))return{status:"invalid",file:e,line:s,message:d.message};c="incomplete-json",l=i}return{inspection:{status:"repairable",file:e,reason:c,line:s,originalHash:rm(t),targetHash:rm(l),tailHash:rm(a),discardedBytes:c==="incomplete-json"?a.length:0},targetContent:l.toString("utf8")}}async function yk(e,t){let r=UO(e,t);await T($(e,r),r);let i=M(e,t),n=await mk(i,_t.trajectoryRef);return n===null?{status:"clean",file:r}:XO(r,Buffer.from(n))}async function Qa(e,t){let r=await yk(e,t);return"inspection"in r?r.inspection:r}async function Wu(e,t){let r=await Qa(e,t);if(r.status!=="clean")throw new qu(r)}async function Nk(e,t,r){return de(e,`repair trajectory tail for ${t}`,async()=>{let i=await yk(e,t);if(!("inspection"in i)){if(i.status==="clean")return null;throw new qu(i)}try{await vk(M(e,t),_t.trajectoryRef,i.targetContent,i.inspection.originalHash,{beforeCommit:r?.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 Qa(e,t)).status!=="clean")throw new Error(`Native trajectory tail repair did not produce a clean file for ${t}`);return i.inspection})}var GO,qu,Js=A(()=>{"use strict";Ya();et();Q();Ui();GO=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,qu=class extends Error{constructor(r){super(r.status==="repairable"?`Native trajectory has an incomplete final line at ${r.file}:${r.line}; run doctor --repair`:`Native trajectory is invalid at ${r.file}:${r.line}: ${r.message}`);this.inspection=r;this.name="NativeTrajectoryRepairRequiredError"}inspection;code="native-trajectory-tail-repair-required"}});import{createHash as QO}from"node:crypto";import{promises as zu}from"node:fs";import Yr from"node:path";function Za(e){return e0.has(e)}function Ek(e,t){let r=Yr.relative(e,t);return Yr.isAbsolute(r)||r===".."||r.startsWith(`..${Yr.sep}`)?null:r.replaceAll("\\","/")||"."}function Pk(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Rk(e,t){if(e.length===0||Pk(e)||e.includes("\\")||Yr.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=Yr.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function am(e,t){return QO("sha256").update(`${e}
|
|
193
|
+
${t}`).digest("hex")}async function kk(e,t){let r=await zu.realpath(t),i=await zu.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=nm==="win32"?Yr.normalize(r).toLowerCase():r;return am(e,`${n}
|
|
194
194
|
${i.dev}
|
|
195
195
|
${i.ino}
|
|
196
|
-
${i.birthtimeMs}`)}async function Sk(e,t){let r=await zu.realpath(t),i=await zu.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=nm==="win32"?
|
|
196
|
+
${i.birthtimeMs}`)}async function Sk(e,t){let r=await zu.realpath(t),i=await zu.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=nm==="win32"?Yr.normalize(r).toLowerCase():r;return am(e,n)}function t0(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 im(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Pk(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Ck(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(im(e.changeBranch,"Native workspace change branch"),im(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 r0(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!bk.test(t.baseCommit)||typeof t.targetCommit!="string"||!bk.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");im(t.targetBranch,"Native workspace Git target branch")}function Us(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Gs.test(String(t.projectRootId))||!Gs.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");t0(t.capturedAt),Rk(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&&!Gs.test(String(t.projectRootPathId))||a&&!Gs.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Gs.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&r0(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(Ck(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 eo(e,t){return Yr.join(M(e,t),"workspace.json")}function i0(e,t){let r=eo(e,t),i=$(e,r),n=Ek(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:Rk(n,"Native workspace file ref")}}async function xk(e,t){try{let r=i0(e,t),i=await te({root:r.root,ref:r.ref,maxBytes:ZO});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Ak(e,t){let r=ae(e.projectRoot),i={projectRoot:Yr.resolve(e.projectRoot),currentBranch:r.currentBranch,isSecondaryWorktree:r.isSecondaryWorktree};try{let n=await Tt(e,t);if(n===null)return{...i,bindingState:"missing",isolation:null,changeBranch:null,targetBranch:null,finish:null};if(n.schema!=="comet.native.workspace.v3")return{...i,bindingState:"legacy",isolation:null,changeBranch:null,targetBranch:n.git?.targetBranch??null,finish:null};let a=await to({paths:e,identity:n});return{...i,bindingState:a.state==="aligned"?"aligned":"drifted",isolation:n.isolation,changeBranch:n.changeBranch,targetBranch:n.targetBranch,finish:n.finish}}catch{return{...i,bindingState:"invalid",isolation:null,changeBranch:null,targetBranch:null,finish:null}}}async function om(e,t){let r=await xk(e,t);if(r===null)return!1;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Native workspace identity must be an object");return r.schema==="comet.native.workspace.v1"?!0:(Us(r),r.schema==="comet.native.workspace.v3"?!1:r.projectRootPathId===void 0||r.nativeRootPathId===void 0)}async function _k(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=Ek(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let r=ae(e.paths.projectRoot),i=r.isGitWorktree?Wr(e.paths.projectRoot,"HEAD"):null,n=e.binding?.targetBranch??r.currentBranch,a=n==null?null:Wr(e.paths.projectRoot,n),o=i!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:i,targetBranch:n,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([kk("comet.native.workspace-project-root.v2",e.paths.projectRoot),kk("comet.native.workspace-native-root.v2",e.paths.nativeRoot),Sk("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),Sk("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&&Ck(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:am("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 Us(h),h}async function Ju(e){let t=await _k(e),r=eo(e.paths,e.name),i=$(e.paths,r);return await T(i,r),await re(r,t,{containedRoot:i}),t}async function Tt(e,t){let r=await xk(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(Us(r),r)}async function Ik(e){return await om(e.paths,e.name)?Ju(e):null}async function Ks(e){Us(e.identity);let t=await _k({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),r=[],i=[];return t.nativeRootRef!==e.identity.nativeRootRef&&r.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&r.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&r.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&r.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&r.push("native-root-legacy-identity")),nm==="win32"&&r.length>0&&r.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?i.push("workspace-inspection-unavailable"):r.length>0&&i.push("workspace-root-changed"),{state:i.length===0?"aligned":i.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:i,driftComponents:r}}async function to(e){if(Us(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 Ks(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=ae(e.paths.projectRoot);return e.identity.changeBranch===null?r.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}:r.isGitWorktree?r.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 ${r.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!r.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 Tk(e,t){let r=await Tt(e,t);if(r===null)return null;let i=await to({paths:e,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}var Gs,bk,ZO,nm,e0,Ar=A(()=>{"use strict";Lt();ue();Ft();et();Q();Gs=/^[a-f0-9]{64}$/u,bk=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,ZO=16*1024,nm=process.platform,e0=new Set(["workspace-root-changed","workspace-inspection-unavailable"])});import{promises as jk}from"fs";import _r from"path";function ec(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Dk(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Uu(e){if(!Hk.test(e))throw new Error(`Invalid Native change name: ${e}`)}function d0(e){if(!Hk.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Lk(e,t){if(e.length===0||_r.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function f0(e,t){let r=ec(e,`spec_changes[${t}]`);if(Dk(r,o0,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(d0(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&Lk(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!cm.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!cm.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function h0(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 lm(e,t){if(Dk(e,t,Le),typeof e.name!="string")throw new Error("Native change name is required");if(Uu(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"||!s0.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&&!c0.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(f0),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!l0.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"&&Lk(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!h0(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function Hn(e){let t=ec(e,Le);if(t.schema!==lt)throw new Error(`Expected ${lt}`);return{schema:lt,...lm(t,n0)}}function Zs(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function sm(e,t,r){if(e===null)return null;let i=typeof e=="string"?u0.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function p0(e){if(e==null)return null;if(typeof e!="string"||!cm.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function m0(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 Pr(e){let t=ec(e,Le);if(t.schema!==Re)throw new Error(`Expected ${Re}`);if(Zs(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Re} minimum_runtime_version must be 2`);return{schema:Re,minimum_runtime_version:2,revision:Zs(t.revision,"Native v2 revision"),...lm(t,Ok)}}function wt(e){let t=ec(e,Le);if(t.schema!==Pe){if(t.schema===lt||t.schema===Re){let o=t.schema===lt?Hn(t):Pr(t);throw new Ys(o.name,o.schema)}throw new Yr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Zs(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Yr(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Zs(t.revision,"Native revision"),n=lm(t,a0),a=p0(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Pe,minimum_runtime_version:3,revision:i,verification_protocol:m0(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:sm(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:sm(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:sm(t.partial_allowance,"Native partial_allowance","allowances")}}function Mk(e){let t=ec(e,Le);if(t.schema===lt){let n=Hn(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Pe}`}}if(t.schema===Re){let n=Pr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Pe}`}}if(t.schema!==Pe){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 Yr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Zs(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Yr(t.schema,r).message};let i=wt(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function qn(e){let t=wt(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(r=>({capability:r.capability,operation:r.operation,...r.source?{source:r.source}:{},base_hash:r.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 Ku(e){let t=Pr(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(r=>({capability:r.capability,operation:r.operation,...r.source?{source:r.source}:{},base_hash:r.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 se(e,t){Uu(t);let r=_r.join(e.changesDir,t);if(!D(e.changesDir,r))throw new Error("Native change path escaped");return r}async function io(e,t){let r=M(e,t),i=_r.join(r,"schema-migration.json");await T(D(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await jk.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function no(e,t){let r=M(e,t),i=_r.join(r,"checkpoint-journal.json");await T(D(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await jk.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Yu(e,t=_r.dirname(e)){let r=_r.relative(t,e).split(_r.sep).join("/"),i=await te({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Gu.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function Ir(e,t){let r=_r.join(se(e,t),Le);await T(e.nativeRoot,r);let i=Mk(await Yu(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await io(e,t)?{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimumRuntimeVersion,state:i.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(i.status==="current"&&i.state&&await v0(e,i.state),i)}async function Xu(e,t){let r=_r.join(se(e,t),Le);await T(e.nativeRoot,r);let i=Mk(await Yu(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}async function v0(e,t){if(await Ka(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function We(e,t){let r=await Ir(e,t);if(r.status==="migration-required")throw new Ys(t,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new Yr(r.schema,r.minimumRuntimeVersion);return await Tk(e,t),r.state}async function Fk(e,t,r){let i={...t,schema:Pe,minimum_runtime_version:3,revision:r+1},n=await xb({expectedRevision:r,next:i,read:async()=>{let a=wt(await Yu(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>ge(e,(0,Gu.stringify)(qn(a))),equals:(a,o)=>JSON.stringify(qn(a))===JSON.stringify(qn(o)),conflict:a=>new Xs(t.name,r,a)});return Object.assign(t,n),n}async function Qu(e,t,r,i){if(await Ta(e.projectRoot),await io(e,t.name))throw new Ys(t.name,t.schema);if(!i?.allowPendingCheckpointRecovery&&await no(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await We(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Wu(e,t.name);let a=_r.join(se(e,t.name),Le);return await T(e.nativeRoot,a),Fk(a,t,r)}async function Bk(e,t){return Fk(e,t,t.revision)}async function Vk(e){return wt(await Yu(e))}var Gu,$k,n0,Ok,a0,o0,s0,c0,l0,Le,cm,Hk,u0,Ys,Yr,Xs,Qs,ro,UJ,ke=A(()=>{"use strict";Gu=da(Cn(),1);Lt();Ft();ue();Nn();ot();et();Q();yt();Ab();Fn();Js();Ar();$s();$k=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],n0=new Set($k),Ok=new Set([...$k,"minimum_runtime_version","revision"]),a0=new Set([...Ok,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),o0=new Set(["capability","operation","source","base_hash"]),s0=new Set(["shape","build","verify","archive"]),c0=new Set(["implicit","confirmed"]),l0=new Set(["pending","pass","fail"]),Le="comet-state.yaml",cm=/^[a-f0-9]{64}$/u,Hk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,u0=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Ys=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Yr=class extends Error{constructor(r,i){super(r!==Pe||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},Xs=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Qs=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},ro=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},UJ=zc("en")});import{createHash as uS}from"node:crypto";import iS from"path";function rt(e,t){return e<t?-1:e>t?1:0}function wm(e){if(!bm.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function rH(e,t){return e===t?0:e===null?-1:t===null?1:rt(e,t)}function Yi(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 r=iS.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||iS.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function hS(e,t){return e==="."?e:Yi(e,t)}function oo(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function iH(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:Yi(e.path,`${t} path`),hash:e.hash,size:oo(e.size,`${t} size`),type:"file"}}function nH(e,t){return{path:hS(e.path,`${t} path`),size:e.size===null?null:oo(e.size,`${t} size`),type:e.type,reason:e.reason}}function aH(e,t){return rt(e.path,t.path)||rt(e.hash,t.hash)||e.size-t.size}function oH(e,t){return rt(e.path,t.path)||rt(e.reason,t.reason)||rt(e.type,t.type)||(e.size??-1)-(t.size??-1)}function nc(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
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 Us(h),h}async function Ju(e){let t=await _k(e),r=eo(e.paths,e.name),i=$(e.paths,r);return await T(i,r),await re(r,t,{containedRoot:i}),t}async function Tt(e,t){let r=await xk(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(Us(r),r)}async function Ik(e){return await om(e.paths,e.name)?Ju(e):null}async function Ks(e){Us(e.identity);let t=await _k({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),r=[],i=[];return t.nativeRootRef!==e.identity.nativeRootRef&&r.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&r.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&r.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&r.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&r.push("native-root-legacy-identity")),nm==="win32"&&r.length>0&&r.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?i.push("workspace-inspection-unavailable"):r.length>0&&i.push("workspace-root-changed"),{state:i.length===0?"aligned":i.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:i,driftComponents:r}}async function to(e){if(Us(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 Ks(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=ae(e.paths.projectRoot);return e.identity.changeBranch===null?r.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}:r.isGitWorktree?r.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 ${r.currentBranch??"detached HEAD"}`}:e.identity.isolation==="worktree"&&!r.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 Tk(e,t){let r=await Tt(e,t);if(r===null)return null;let i=await to({paths:e,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}var Gs,bk,ZO,nm,e0,_r=A(()=>{"use strict";Lt();ue();Ft();et();Q();Gs=/^[a-f0-9]{64}$/u,bk=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,ZO=16*1024,nm=process.platform,e0=new Set(["workspace-root-changed","workspace-inspection-unavailable"])});import{promises as jk}from"fs";import Ir from"path";function ec(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Dk(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Uu(e){if(!Hk.test(e))throw new Error(`Invalid Native change name: ${e}`)}function d0(e){if(!Hk.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Lk(e,t){if(e.length===0||Ir.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function f0(e,t){let r=ec(e,`spec_changes[${t}]`);if(Dk(r,o0,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(d0(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&Lk(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!cm.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!cm.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function h0(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 lm(e,t){if(Dk(e,t,Le),typeof e.name!="string")throw new Error("Native change name is required");if(Uu(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"||!s0.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&&!c0.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(f0),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!l0.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"&&Lk(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!h0(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function Hn(e){let t=ec(e,Le);if(t.schema!==lt)throw new Error(`Expected ${lt}`);return{schema:lt,...lm(t,n0)}}function Zs(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function sm(e,t,r){if(e===null)return null;let i=typeof e=="string"?u0.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function p0(e){if(e==null)return null;if(typeof e!="string"||!cm.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function m0(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 Rr(e){let t=ec(e,Le);if(t.schema!==Re)throw new Error(`Expected ${Re}`);if(Zs(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Re} minimum_runtime_version must be 2`);return{schema:Re,minimum_runtime_version:2,revision:Zs(t.revision,"Native v2 revision"),...lm(t,Ok)}}function wt(e){let t=ec(e,Le);if(t.schema!==Pe){if(t.schema===lt||t.schema===Re){let o=t.schema===lt?Hn(t):Rr(t);throw new Ys(o.name,o.schema)}throw new Xr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Zs(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Xr(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Zs(t.revision,"Native revision"),n=lm(t,a0),a=p0(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Pe,minimum_runtime_version:3,revision:i,verification_protocol:m0(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:sm(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:sm(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:sm(t.partial_allowance,"Native partial_allowance","allowances")}}function Mk(e){let t=ec(e,Le);if(t.schema===lt){let n=Hn(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Pe}`}}if(t.schema===Re){let n=Rr(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Pe}`}}if(t.schema!==Pe){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 Xr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Zs(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Xr(t.schema,r).message};let i=wt(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function qn(e){let t=wt(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(r=>({capability:r.capability,operation:r.operation,...r.source?{source:r.source}:{},base_hash:r.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 Ku(e){let t=Rr(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(r=>({capability:r.capability,operation:r.operation,...r.source?{source:r.source}:{},base_hash:r.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 se(e,t){Uu(t);let r=Ir.join(e.changesDir,t);if(!D(e.changesDir,r))throw new Error("Native change path escaped");return r}async function io(e,t){let r=M(e,t),i=Ir.join(r,"schema-migration.json");await T(D(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await jk.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function no(e,t){let r=M(e,t),i=Ir.join(r,"checkpoint-journal.json");await T(D(e.runtimeDir,i)?e.runtimeDir:e.nativeRoot,i);try{return await jk.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function Yu(e,t=Ir.dirname(e)){let r=Ir.relative(t,e).split(Ir.sep).join("/"),i=await te({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Gu.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function Tr(e,t){let r=Ir.join(se(e,t),Le);await T(e.nativeRoot,r);let i=Mk(await Yu(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await io(e,t)?{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimumRuntimeVersion,state:i.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(i.status==="current"&&i.state&&await v0(e,i.state),i)}async function Xu(e,t){let r=Ir.join(se(e,t),Le);await T(e.nativeRoot,r);let i=Mk(await Yu(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}async function v0(e,t){if(await Ka(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function We(e,t){let r=await Tr(e,t);if(r.status==="migration-required")throw new Ys(t,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new Xr(r.schema,r.minimumRuntimeVersion);return await Tk(e,t),r.state}async function Fk(e,t,r){let i={...t,schema:Pe,minimum_runtime_version:3,revision:r+1},n=await xb({expectedRevision:r,next:i,read:async()=>{let a=wt(await Yu(e));if(a.name!==t.name)throw new Error(`Native change file/name mismatch: ${t.name}`);return a},write:a=>ge(e,(0,Gu.stringify)(qn(a))),equals:(a,o)=>JSON.stringify(qn(a))===JSON.stringify(qn(o)),conflict:a=>new Xs(t.name,r,a)});return Object.assign(t,n),n}async function Qu(e,t,r,i){if(await Ta(e.projectRoot),await io(e,t.name))throw new Ys(t.name,t.schema);if(!i?.allowPendingCheckpointRecovery&&await no(e,t.name))throw new Error(`Native progress checkpoint recovery is required for ${t.name} before another state write`);if((await We(e,t.name)).verification_protocol!==t.verification_protocol)throw new Error("Native verification protocol changed outside a revisioned state transition");await Wu(e,t.name);let a=Ir.join(se(e,t.name),Le);return await T(e.nativeRoot,a),Fk(a,t,r)}async function Bk(e,t){return Fk(e,t,t.revision)}async function Vk(e){return wt(await Yu(e))}var Gu,$k,n0,Ok,a0,o0,s0,c0,l0,Le,cm,Hk,u0,Ys,Xr,Xs,Qs,ro,UJ,ke=A(()=>{"use strict";Gu=da(Cn(),1);Lt();Ft();ue();Nn();ot();et();Q();yt();Ab();Fn();Js();_r();$s();$k=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],n0=new Set($k),Ok=new Set([...$k,"minimum_runtime_version","revision"]),a0=new Set([...Ok,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),o0=new Set(["capability","operation","source","base_hash"]),s0=new Set(["shape","build","verify","archive"]),c0=new Set(["implicit","confirmed"]),l0=new Set(["pending","pass","fail"]),Le="comet-state.yaml",cm=/^[a-f0-9]{64}$/u,Hk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,u0=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Ys=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Xr=class extends Error{constructor(r,i){super(r!==Pe||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},Xs=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Qs=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},ro=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},UJ=zc("en")});import{createHash as uS}from"node:crypto";import iS from"path";function rt(e,t){return e<t?-1:e>t?1:0}function wm(e){if(!bm.test(e))throw new Error("Native snapshot projection hash must be a SHA-256 hash");return`runtime/evidence/snapshots/${e}.json`}function rH(e,t){return e===t?0:e===null?-1:t===null?1:rt(e,t)}function Yi(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 r=iS.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||iS.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function hS(e,t){return e==="."?e:Yi(e,t)}function oo(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function iH(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:Yi(e.path,`${t} path`),hash:e.hash,size:oo(e.size,`${t} size`),type:"file"}}function nH(e,t){return{path:hS(e.path,`${t} path`),size:e.size===null?null:oo(e.size,`${t} size`),type:e.type,reason:e.reason}}function aH(e,t){return rt(e.path,t.path)||rt(e.hash,t.hash)||e.size-t.size}function oH(e,t){return rt(e.path,t.path)||rt(e.reason,t.reason)||rt(e.type,t.type)||(e.size??-1)-(t.size??-1)}function nc(e){return Buffer.byteLength(JSON.stringify(e,null,2)+`
|
|
199
199
|
`,"utf8")}function Ki(e,t,r){let i=`${t}
|
|
200
200
|
${Ps(r)}`;e.update(`${Buffer.byteLength(i,"utf8")}:`),e.update(i)}function sH(e){if(nc(e)<=zn)return e;let t=[...e.entries],r=[...e.omitted],i=e.omittedCount,n=e.omissionOverflow?.count??0,a=uS("sha256");a.update(`${Z0}
|
|
201
|
-
`),e.omissionOverflow&&Ki(a,"existing-overflow",e.omissionOverflow);let o=(f,h)=>{h||(i+=1),n+=1,Ki(a,"omission",f)},s=f=>{i+=1,n+=1,Ki(a,"entry",f)},c=()=>{for(let f=r.length-1;f>=0;f-=1){let h=r[f];if(!(h.reason==="git-enumeration-limit"||h.reason==="git-selection-changed"||h.reason==="physical-enumeration-limit"||h.reason==="physical-selection-changed"))return r.splice(f,1),h}return null},l=()=>({...e,complete:i===0,entries:t,omitted:r,omittedCount:i,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;nc(u)>zn;){if(r.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(r.length/4));for(let m=0;m<h;m+=1){let p=c();if(p===null)break;o(p,!0)}}else if(t.length>0){let h=Math.max(1,Math.ceil(t.length/4));for(let m of t.splice(-h))s(m)}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 ym(e){let t=
|
|
202
|
-
`);let r=0;km(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){Ki(t,"change",n);let a=0;for(let o of e.declaredArtifacts)oc(o,n.path)&&(a+=1,Ki(t,"change-attribution",o));Ki(t,"change-end",{attributionCount:a}),a===0&&Ki(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}r+=1});let i=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)i>=e.detailedOmissionCount&&Ki(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function yS(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=dH(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let R=new Set(r.externalDrift.paths),b=new Set(o.changePaths),y=r.externalDrift.paths.filter(P=>!b.has(P)||n.some(L=>oc(L,P)));if(y.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${y.slice(0,8).join(", ")}`);if(R.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=O(rc,e),c=O(rc,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[R,b]of[["baseline",e],["current",t]])for(let y of b.omitted){if(l.length>=tH)break;l.push(Qr({kind:"snapshot-omission",source:R,path:y.path,evidence:{reason:y.reason,size:y.size,type:y.type}},`${R} snapshot omitted ${y.path}: ${y.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...aS("baseline",e),...aS("current",t),...o.totalChanges===0&&a===null?[Qr({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(r.gitChangedPaths===void 0)return;let R=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(b=>R.has(b)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(b=>!R.has(b))}},m=R=>{let b=o.candidates.slice(0,R.detailedChangeCount),y=b.filter(er=>er.attributedTo.length===0&&!u.has(er.path)),P=o.totalChanges-b.length,L=o.totalUnattributed-y.length,H=d-R.detailedOmissionCount,je=L+H,me=[...y.map(er=>Qr({kind:"unattributed-change",source:"implementation-scope",path:er.path,evidence:{after:er.after,before:er.before,changeKind:er.kind}},`Changed path is not covered by a declared artifact: ${er.path}`)),...l.slice(0,R.detailedOmissionCount),...f,...je>0?[wS(R.overflowHash,{changes:P,unattributed:L,unresolved:je})]:[]],ie=lH(me),yr=R.includeGitAdvisory?h():void 0;return{schema:gm,contractHash:i,baselineProjectionRef:wm(s),baselineProjectionHash:s,currentProjectionRef:wm(c),currentProjectionHash:c,complete:ie.length===0,declaredArtifacts:n,changes:b,unattributed:y,unresolvedScopes:ie,noCodeReason:a,...yr?{gitAdvisory:yr}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},p=o.candidates.length,v=l.length,g=r.gitChangedPaths!==void 0,N="0".repeat(64);for(;;){let R=m({detailedChangeCount:p,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:N});if(nc({...R,scopeHash:N})<=zn)break;if(g){g=!1;continue}if(v>0){v-=Math.max(1,Math.ceil(v/4));continue}if(p>0){p-=Math.max(1,Math.ceil(p/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let w=o.totalChanges>p||d>v?hH({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:p,detailedOmissionCount:v}):N,S=m({detailedChangeCount:p,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:w}),k={...S,scopeHash:O(fS,S)};if(nc(k)>zn)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return k}function Em(e){let t=ym(e.baseline),r=ym(e.current),i=gS(e);return{authority:i,baseline:t,current:r,scope:yS(t,r,i)}}function Tr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function jr(e,t,r,i){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 Wn(e,t){if(typeof e!="string"||!bm.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function sS(e,t,r){let i=wm(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function so(e,t){let r=Tr(e,"Native snapshot projection");if(jr(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==dS)throw new Error("Native snapshot projection schema is invalid");let i=Ur({schema:"comet.native.content-snapshot.v1",origin:r.origin,...r.capture===void 0?{}:{capture:r.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:r.complete,limits:r.limits,...r.policy===void 0?{}:{policy:r.policy},entries:r.entries,omitted:r.omitted,omittedCount:r.omittedCount,...r.omissionOverflow===void 0?{}:{omissionOverflow:r.omissionOverflow}}),n=ym(i);if(O(rc,r)!==O(rc,n))throw new Error("Native snapshot projection is not canonical");let a=O(rc,n);if(t!==void 0&&Wn(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Pm(e,t){let r=Tr(e,`Declared artifact ${t}`);if(jr(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Yi(r.path,`Declared artifact ${t} path`),kind:r.kind}}function cS(e,t){if(e===null)return null;let r=Tr(e,t);return jr(r,["hash","size"],[],t),{hash:Wn(r.hash,`${t} hash`),size:oo(r.size,`${t} size`)}}function lS(e,t){let r=Tr(e,`Implementation change ${t}`);if(jr(r,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),r.kind!=="added"&&r.kind!=="modified"&&r.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(r.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let i=r.attributedTo.map(Pm),n=ac(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=cS(r.before,`Implementation change ${t} before`),o=cS(r.after,`Implementation change ${t} after`);if(r.kind==="added"&&(a!==null||o===null)||r.kind==="removed"&&(a===null||o!==null)||r.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:Yi(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function mH(e,t){let r=Tr(e,`Unresolved scope ${t}`);jr(r,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let i=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof r.kind!="string"||!i.has(r.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(r.source!=="baseline"&&r.source!=="current"&&r.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof r.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(r.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(r.path!==null&&typeof r.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof r.reason!="string"||r.reason.length===0||r.reason.trim()!==r.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:r.id,kind:r.kind,source:r.source,path:r.path===null?null:r.kind==="snapshot-omission"?hS(r.path,`Unresolved scope ${t} path`):Yi(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function ic(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let r=e.map((n,a)=>Yi(n,`${t} ${a}`)),i=[...new Set(r)].sort(rt);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function NS(e){let t=Tr(e,"Native implementation external drift");if(jr(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let r=ic(t.paths,"Native external drift paths");return vS({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function co(e){let t=Tr(e,"Native implementation scope"),r=[...pH].filter(y=>y!=="gitAdvisory"&&y!=="externalDrift");if(jr(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==gm)throw new Error("Native implementation scope schema is invalid");let i=Wn(t.contractHash,"Implementation scope contractHash"),n=Wn(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=sS(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=Wn(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=sS(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(Pm);if(JSON.stringify(c)!==JSON.stringify(ac(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(lS),u=[...l].sort((y,P)=>rt(y.path,P.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(y=>y.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(y=>`${y.kind}:${y.path}`));if(l.some(y=>y.attributedTo.some(P=>!d.has(`${P.kind}:${P.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(y=>JSON.stringify(y.attributedTo)!==JSON.stringify(c.filter(P=>oc(P,y.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(lS),h=t.externalDrift===void 0?void 0:NS(t.externalDrift),m=new Set(h?.paths??[]),p=l.filter(y=>y.attributedTo.length===0&&!m.has(y.path));if(JSON.stringify(f)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let v=t.unresolvedScopes.map(mH),g=v.filter(y=>y.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let N=g[0]===void 0?null:fH(g[0]);if(N&&(N.changes+N.unresolved===0||N.unattributed>N.changes||N.unattributed>N.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let E=t.noCodeReason,w=[...p.map(y=>Qr({kind:"unattributed-change",source:"implementation-scope",path:y.path,evidence:{after:y.after,before:y.before,changeKind:y.kind}},`Changed path is not covered by a declared artifact: ${y.path}`)),...l.length+(N?.changes??0)===0&&E===null?[Qr({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")]:[]],S=v.filter(y=>y.kind==="unattributed-change"||y.kind==="missing-no-code-reason");if(JSON.stringify(v)!==JSON.stringify([...v].sort(Nm))||new Set(v.map(y=>y.id)).size!==v.length||JSON.stringify(S)!==JSON.stringify(w.sort(Nm))||t.complete!==(v.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 k;if(t.gitAdvisory!==void 0){let y=Tr(t.gitAdvisory,"Implementation scope Git advisory");if(jr(y,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),y.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let P=ic(y.changedPaths,"Git changed paths"),L=ic(y.pathsPresentInSnapshotChanges,"Git present paths"),H=ic(y.pathsAbsentFromSnapshotChanges,"Git absent paths"),je=[...L,...H].sort(rt);if(JSON.stringify(je)!==JSON.stringify(P)||H.some(me=>l.some(ie=>ie.path===me)))throw new Error("Implementation scope Git advisory partition is invalid");k={advisoryOnly:!0,changedPaths:P,pathsPresentInSnapshotChanges:L,pathsAbsentFromSnapshotChanges:H}}let R={schema:gm,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:v,noCodeReason:E,...k?{gitAdvisory:k}:{},...h?{externalDrift:h}:{}},b=Wn(t.scopeHash,"Implementation scope scopeHash");if(O(fS,R)!==b)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:b}}function vH(e){let t=Tr(e,"Native implementation scope authority");if(jr(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 r=t.declaredArtifacts.map(Pm);if(JSON.stringify(r)!==JSON.stringify(ac(r)))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 i;t.gitChangedPaths!==void 0&&(i=ic(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:NS(t.externalDrift),a=gS({contractHash:t.contractHash,declaredArtifacts:r,noCodeReason:t.noCodeReason,...i===void 0?{}:{gitChangedPaths:i},...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 sc(e){let t=Tr(e,"Native implementation scope bundle");jr(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=vH(t.authority),i=so(t.baseline),n=so(t.current),a=co(t.scope),o=yS(i,n,r);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:r,baseline:i,current:n,scope:o}}function bS(e){let t=co(e.scope);return sc({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})}var gm,dS,rc,fS,X0,Q0,Z0,bm,zn,eH,tH,pH,Xi=A(()=>{"use strict";Xe();Fn();gm="comet.native.implementation-scope.v2",dS="comet.native.content-snapshot-projection.v1",rc="comet.native.content-snapshot-projection.v1",fS="comet.native.implementation-scope.v2",X0="comet.native.unresolved-scope-id.v1",Q0="comet.native.scope-detail-overflow.v1",Z0="comet.native.snapshot-projection-overflow.v2",bm=/^[a-f0-9]{64}$/u,zn=1024*1024,eH=128,tH=128;pH=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});function Gt(e){return e.replace(gH,"$1 [REDACTED]").replace(wH,"[REDACTED PRIVATE KEY]").replace(yH,"$1[REDACTED]@").replace(NH,"[REDACTED TOKEN]").replace(bH,'$1"[REDACTED]"').replace(kH,"$1$2$1$3$4[REDACTED]$4").replace(SH,"$1$2[REDACTED]")}var gH,wH,yH,NH,bH,kH,SH,Jn=A(()=>{"use strict";gH=/\b(Bearer|Basic)\s+[^\s"']+/giu,wH=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,yH=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,NH=/\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,bH=/("(?:[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,kH=/(["'])((?:[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,SH=/\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});import kS from"node:path";function Zr(e,t){if(!ES.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function PS(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function RS(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 Rm(e,t,r=2e3){let i=Gt(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function cc(e,t){let r=kS.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||kS.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function CH(e,t,r){let i=cc(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=kr(i),a=i.toLowerCase(),o=r?cc(r,"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"}): ${i}`);return i}function Cm(e){let t=cc(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 lo(e,t){return e<t?-1:e>t?1:0}function td(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function rd(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function CS(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function SS(e,t,r){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let i=`runtime/evidence/${t}/${r}.json`;if(e!==i)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function xH(e){let t=td(e,"Native acceptance trace");if(rd(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"||!ES.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 r=cc(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=td(o,`Native acceptance trace entry ${s}`);if(rd(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=>Cm(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(lo))||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:cc(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Rm(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>lo(o.acceptanceId,s.acceptanceId)))||new Set(i.map(o=>o.acceptanceId)).size!==i.length||t.total!==i.length||t.evidenced!==i.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==i.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:r,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:i},a=Zr(t.traceHash,"Native acceptance trace hash");if(O(EH,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function id(e){let t=td(e,"Native partial allowance");if(rd(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(lo))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let r={schema:"comet.native.partial-allowance.v1",change:RS(t.change),scopeHash:Zr(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Rm(t.reason,"Partial allowance reason"),confirmedSummary:Rm(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:PS(t.sourceRevision),confirmedAt:CS(t.confirmedAt,"Native partial allowance timestamp")};if(r.reason!==t.reason||r.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let i=Zr(t.allowanceHash,"Native partial allowance hash");if(O(PH,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function lc(e){let t=td(e,"Native verification evidence");if(rd(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 r=Zr(t.implementationScopeHash,"Native verification implementation scope hash"),i=xH(t.acceptanceTrace),n=Zr(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(i.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:Zr(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Cm(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(lo)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(f=>f.evidenceRefs))].sort(lo);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=>Cm(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(lo)))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:RS(t.change),sourceRevision:PS(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:Zr(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:SS(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:CH(t.reportRef,"Native verification report ref"),reportHash:Zr(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:SS(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:CS(t.createdAt,"Native verification timestamp")},d=Zr(t.envelopeHash,"Native verification envelope hash");if(O(RH,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}var ES,EH,PH,RH,uc=A(()=>{"use strict";Xe();Jn();ds();Xi();ES=/^[a-f0-9]{64}$/u,EH="comet.native.acceptance-trace.v2",PH="comet.native.partial-allowance.v1",RH="comet.native.verification-evidence.v2"});import xS from"node:path";function Qi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Zi(e,t,r,i=[]){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 ei(e,t){if(typeof e!="string"||!_H.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function jt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function $S(e,t){let r=jt(e,t);if(r<1)throw new Error(`${t} must be a positive integer`);return r}function TS(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(!Number.isFinite(r.getTime())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function DH(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>$H||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 r=xS.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||xS.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function LH(e){let t=Qi(e,"Native check receipt checker");Zi(t,["policy","version","hash","limits"],"Native check receipt checker");let r=Qi(t.limits,"Native check receipt limits");if(Zi(r,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==uo||t.version!==xm||t.hash!==_S||r.maxFiles!==bt.maxFiles||r.maxFileBytes!==bt.maxFileBytes||r.maxTotalBytes!==bt.maxTotalBytes||r.maxIssues!==bt.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:uo,version:xm,hash:_S,limits:{...bt}}}function MH(e){let t=Qi(e,"Native check receipt contract");return Zi(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:ei(t.expectedHash,"Native check expected contract hash"),beforeHash:ei(t.beforeHash,"Native check before contract hash"),afterHash:ei(t.afterHash,"Native check after contract hash")}}function FH(e){let t=Qi(e,"Native check receipt implementation");return Zi(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:ei(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:ei(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:ei(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:ei(t.afterSnapshotHash,"Native check after snapshot hash")}}function BH(e,t){let r=Qi(e,`Native check batch ${t}`);Zi(r,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let i={filesSelected:jt(r.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:jt(r.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:jt(r.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:jt(r.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:jt(r.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:jt(r.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(i.filesSelected>bt.maxFiles||i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.bytesScanned>bt.maxTotalBytes||i.recordedIssueCount>i.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return i}function VH(e){let t=Qi(e,"Native check receipt counts");Zi(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let r={filesSelected:jt(t.filesSelected,"Native check filesSelected"),filesScanned:jt(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:jt(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:jt(t.bytesScanned,"Native check bytesScanned"),issueCount:jt(t.issueCount,"Native check issueCount"),recordedIssueCount:jt(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(BH):(()=>{throw new Error("Native check receipt batches must be an array")})()}},i=r.batches;if(i!==void 0){if(i.length===0)throw new Error("Native check receipt batches must not be empty");let n=i.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({...r,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.recordedIssueCount>r.issueCount||r.recordedIssueCount>bt.maxIssues||i===void 0&&(r.filesScanned+r.binaryFilesSkipped>bt.maxFiles||r.bytesScanned>bt.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return r}function qH(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||IS.indexOf(e.kind)-IS.indexOf(t.kind)}function WH(e){if(!Array.isArray(e)||e.length>bt.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((i,n)=>{let a=Qi(i,`Native check issue ${n}`);if(Zi(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!OH.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:DH(a.path,`Native check issue ${n} path`),line:$S(a.line,`Native check issue ${n} line`),kind:a.kind}}),r=[...t].sort(qH);if(JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function zH(e){if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!HH.has(i)))throw new Error("Native check receipt stale reasons are invalid");let t=e,r=jS.filter(i=>t.includes(i));if(new Set(t).size!==t.length||JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function JH(e){return O(jH,e)}function nd(e){let t=Qi(e,"Native check receipt");if(Zi(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==AS)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!IH.test(t.change))throw new Error("Native check receipt change name is invalid");let r=$S(t.sourceRevision,"Native check source revision"),i=LH(t.checker),n=MH(t.contract),a=FH(t.implementation),o=JH({change:t.change,sourceRevision:r,checkerHash:i.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(ei(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=TS(t.startedAt,"Native check receipt startedAt"),c=TS(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=VH(t.counts),u=WH(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=zH(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>bt.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>bt.maxFiles&&!u.some(p=>p.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let h={schema:AS,change:t.change,sourceRevision:r,checker:i,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},m=ei(t.receiptHash,"Native check receipt content hash");if(O(AH,h)!==m)throw new Error("Native check receipt content hash mismatch");return{...h,receiptHash:m}}var AS,AH,uo,xm,bt,_H,IH,TH,jH,$H,_S,OH,IS,jS,HH,ad=A(()=>{"use strict";Xe();AS="comet.native.check-receipt.v1",AH="comet.native.check-receipt.v1",uo="scoped-text-safety",xm=1,bt=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),_H=/^[a-f0-9]{64}$/u,IH=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,TH="comet.native.checker-policy.v1",jH="comet.native.check-input.v1",$H=2048,_S=O(TH,{policy:uo,version:xm,limits:bt,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),OH=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),IS=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],jS=["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"],HH=new Set(jS)});function fo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function en(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function ti(e,t){if(typeof e!="string"||!KH.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function vr(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=Gt(e).trim();if(!r||r.length>ZH||r!==e.trim())throw new Error(`${t} is invalid`);return r}function Am(e,t){let r=vr(e,t),i=new Date(r);if(Number.isNaN(i.getTime())||i.toISOString()!==r)throw new Error(`${t} must be a canonical timestamp`);return r}function dc(e,t,r=vr,i=!1,n=eD){if(!Array.isArray(e)||e.length>n||!i&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>r(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function rD(e,t){if(typeof e!="string"||!YH.test(e))throw new Error(`${t} is invalid`);return e}function iD(e){let t=fo(e,"Native verification receipt bindings");if(en(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!XH.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:ti(t.contractHash,"Native verification receipt contract hash"),scopeHash:ti(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:ti(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:ti(t.artifactHash,"Native verification receipt artifact hash")}}function nD(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=QH.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function aD(e,t,r,i){let n=fo(t,`Native ${e} evidence`);if(e==="automated-check"){if(en(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=Am(n.startedAt,"Native automated-check start time"),o=Am(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(r==="passed"&&n.exitCode!==0||r==="failed"&&n.exitCode===0||r==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=fo(n.worktree,"Native automated-check worktree");if(en(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=fo(n.afterFence,"Native automated-check after fence");if(en(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(r==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:vr(n.executable,"Native automated-check executable"),args:dc(n.args,"Native automated-check arguments",vr,!0),cwd:vr(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:vr(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:ti(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:ti(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:ti(n.outputHash,"Native automated-check output hash"),outputSummary:vr(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){en(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=nD(n.checkReceiptRef);if(ti(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:dc(n.subjects,"Native static inspection subjects",vr,i==="required-check"),rule:vr(n.rule,"Native static inspection rule"),resultSummary:vr(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return en(n,["steps","observations"],"Native manual-evidence evidence"),{steps:dc(n.steps,"Native manual evidence steps"),observations:dc(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function oD(e){let t=fo(e,"Native verification receipt");if(en(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 r=t.kind,i=t.role,n=t.status,a=vr(t.actor,"Native verification receipt actor"),o=dc(t.acceptanceIds,"Native receipt acceptance IDs",rD,i==="required-check",tD).sort();if(i==="required-check"&&o.length!==0||i==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(i==="required-check"&&r!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:_m,kind:r,role:i,status:n,bindings:iD(t.bindings),acceptanceIds:o,actor:a,issuedAt:Am(t.issuedAt,"Native verification receipt issue time"),evidence:aD(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==uo||s.actor!==`native-runtime:${uo}`))throw new Error("Native required check policy identity is invalid");return s}function od(e){let t=fo(e,"Native verification receipt");if(en(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==_m)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=oD(i),a=ti(t.receiptHash,"Native verification receipt hash");if(O(GH,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Im(e){return O(UH,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,r)=>t.path.localeCompare(r.path)||t.kind.localeCompare(r.kind)))}var _m,GH,UH,KH,YH,XH,QH,ZH,eD,tD,ho=A(()=>{"use strict";Xe();ad();Jn();_m="comet.native.verification-receipt.v3",GH=_m,UH="comet.native.declared-artifacts.v1",KH=/^[a-f0-9]{64}$/u,YH=/^acceptance-[a-f0-9]{64}$/u,XH=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,QH=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,ZH=4096,eD=256,tD=1024});import{createHash as sD}from"node:crypto";import{promises as gr}from"node:fs";import $r from"node:path";function Tm(e,t){let r=$r.relative(e,t);return r===""||!$r.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${$r.sep}`)}function cD(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function sd(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Rt(r,i)?J(r,i):J(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function OS(e){let t=await gr.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await gr.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function lD(e,t){let r=$r.resolve(e),i=$r.resolve(t);if(!Tm(r,i))throw new Error("Native evidence path is outside its change");let n=[await OS(r)],a=r;for(let o of $r.relative(r,i).split($r.sep).filter(Boolean)){a=$r.join(a,o);let s=await OS(a);if(!Tm(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function HS(e){for(let t of e){let r=await gr.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!cD(t,r)||await gr.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function uD(e,t,r={}){let i=await lD(t,$r.dirname(e));await r.afterParentChainCaptured?.();let n=await gr.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await gr.realpath(e);if(!Tm(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await gr.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),gr.lstat(e),gr.realpath(e)]);if(await HS(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!sd(s,n)||!sd(s,c))throw new Error("Native evidence document changed while opening");if(s.size>tn)throw new Error(`Native evidence document exceeds ${tn} bytes`);await r.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let v=tn+1-d,g=await o.read(f,0,Math.min(f.length,v),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>tn)throw new Error(`Native evidence document exceeds ${tn} bytes`);u.push(Buffer.from(f.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[h,m,p]=await Promise.all([o.stat(),gr.lstat(e),gr.realpath(e)]);if(await HS(i),!m.isFile()||m.isSymbolicLink()||p!==a||!sd(s,h)||!sd(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function mo(e,t){if(!LS.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function MS(e){return mo("reports",e)}async function dD(e,t,r,i,n){if(!LS.test(r))throw new Error("Native report evidence hash is invalid");let a=await Gn({paths:e,name:t,kind:"reports",hash:r,hooks:i,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==r||typeof o.content!="string"||sD("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==r)throw new Error("Native report evidence does not match its hash");return o.content}function po(e,t){let r=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!r||r[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return r[2]}function fD(e,t,r,i,n){let a=mo(r,i);return n?$r.join(n,...a.split("/")):Ii(M(e,t),a)}async function Gn(e){let t=fD(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??$(e.paths,t);return await T(r,t),uD(t,r,e.hooks)}function DS(e,t){return so(e,t)}function hD(e,t){let r=co(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function pD(e,t,r){let i=id(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function mD(e,t,r){let i=lc(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}async function vD(e,t,r,i=!1,n){let a=await cd(e,t,r.implementationScopeRef,void 0,n);if(i&&await dD(e,t,r.reportHash,void 0,n),a.scopeHash!==r.implementationScopeHash||a.contractHash!==r.contractHash||(a.complete?"complete":"partial")!==r.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(r.partialAllowanceRef===null)return;let o=await FS(e,t,r.partialAllowanceRef,void 0,n);if(o.allowanceHash!==r.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=r.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function fc(e,t,r,i,n){let a=po(r,"scopes"),o=hD(await Gn({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=po(o.baselineProjectionRef,"snapshots"),c=po(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Gn({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>DS(d,s)),Gn({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>DS(d,c))]);return bS({baseline:l,current:u,scope:o})}async function cd(e,t,r,i,n){return(await fc(e,t,r,i,n)).scope}async function FS(e,t,r,i,n){let a=po(r,"allowances");return pD(await Gn({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function hc(e,t,r,i,n){let a=po(r,"receipts"),o=od(await Gn({paths:e,name:t,kind:"receipts",hash:a,hooks:i,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function vo(e,t,r,i,n){let a=po(r,"verifications"),o=mD(await Gn({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await vD(e,t,o,!1,n),o}var LS,tn,MG,ri=A(()=>{"use strict";ue();Q();nr();Xi();uc();ho();LS=/^[a-f0-9]{64}$/u,tn=zn,MG=3*tn});var BU,vd=A(()=>{"use strict";BU=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ")});var Km=A(()=>{"use strict"});import{execFileSync as iM}from"node:child_process";function UE(e,t){try{return iM("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:nM,maxBuffer:aM,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new fv(e,t,i)}}function Ce(e,t){return UE(e,t).trim()}function KE(e){let t=UE(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let r=t.split("\0").filter(Boolean),i=[];for(let n=0;n<r.length;n+=1){let a=r[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(i.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=r[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");i.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(i)].sort()}var nM,aM,fv,bc=A(()=>{"use strict";nM=3e4,aM=8*1024*1024,fv=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});import{createHash as oM}from"node:crypto";import{lstatSync as sM,readFileSync as YE,promises as cM}from"node:fs";import hv from"node:path";function XE(e){try{if(Ce(e,["ls-files","--",xd]))return!1;let t=hv.join(e,xd),r=sM(t);return!r.isFile()||r.isSymbolicLink()?!1:JSON.parse(YE(lM(e),"utf8")).hash===uM(YE(t))}catch{return!1}}function Ad(e,t=[]){return KE(e).every(r=>t.some(i=>r===i||r.startsWith(`${i}/`))||r===xd&&XE(e))}async function QE(e){XE(e)&&await cM.unlink(hv.join(e,xd))}var xd,lM,uM,pv=A(()=>{"use strict";bc();ue();xd=".comet/config.yaml",lM=e=>hv.join(e,".comet","runtime","native","workspace-config.json"),uM=e=>oM("sha256").update(e).digest("hex")});var mv=A(()=>{"use strict";vd();Km();Jn()});var kc,Sc=A(()=>{"use strict";kc="skill-coordinated"});var _d=A(()=>{"use strict";Sc()});import Id from"node:path";function ZE(...e){if(e.length===0)return Id.resolve();if(Id.win32.isAbsolute(e[0])){let t=Id.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return Id.resolve(...e)}var eP=A(()=>{"use strict"});var i4,tP=A(()=>{"use strict";vd();i4=8*1024*1024});var rP=A(()=>{"use strict";tP()});var Td,vv=A(()=>{"use strict";bc();Lt();ot();pv();Tn();Q();Td=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation}});import he from"node:path";import{promises as jd}from"node:fs";function mM(e,t){let r=he.relative(he.resolve(e),he.resolve(t));return r===""||!he.isAbsolute(r)&&!r.startsWith(`..${he.sep}`)}function vM(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 gM(e,t,r){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(r))throw new Error("Native Supervisor parent and child names are invalid");return ZE(e,".worktrees",`${t}-${r}`)}function oP(e,t){return he.join(Ye(e,t),"supervisor")}function $d(e,t){return he.join(oP(e,t),"state.json")}function sP(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!==wv)throw new Error(`Native Supervisor state schema must be ${wv}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if(dn(t.integration.targetCommit,"Native Supervisor target commit"),dn(t.integration.headCommit,"Native Supervisor integration head commit"),t.integration.checkExecution){let n=t.integration.checkExecution;if(!n.operationId||!n.key||!n.child||!["running","completed","interrupted"].includes(n.status)||!Number.isSafeInteger(n.ownerPid)||n.ownerPid<=0)throw new Error("Native Supervisor integration check execution is invalid");dn(n.candidateCommit,"Native Supervisor integration candidate commit"),dn(n.integrationCommit,"Native Supervisor integration check commit")}if(!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&dn(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(dn(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function Ot(e,t,r={}){try{let i=await jd.readFile($d(e,t),"utf8"),n=JSON.parse(i);if(sP(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativeChildrenContract:s,nativeChildrenAcceptanceValidation:c}=await Promise.resolve().then(()=>(Eo(),hP)),{readNativePortableState:l}=await Promise.resolve().then(()=>(Er(),_p)),u=await l(he.join(o.changesDir,t,"comet-state.yaml")),d=await s({changeDir:he.join(o.changesDir,t),acceptanceIds:u.acceptance.map(({id:f})=>f),validation:c(u)});if(!d)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let f of n.children)d.contract.children.some(({name:h})=>h===f.name)&&(f.acceptanceScope=lP(d.contract,f.name),f.contractHash=O("comet.native.supervisor-contract.v1",d.contract),f.task&&(f.task.acceptance=structuredClone(f.acceptanceScope),f.task.contractHash=f.contractHash,f.task.verificationBoundary="child-scope-parent-reverifies-all",f.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=e;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(Er(),_p)),s=await o(he.join(a.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(n.integration.targetBranch=s.workspace.change_branch)}catch(o){if(o.code!=="ENOENT")throw o}return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Xn(e,t){sP(t),await jd.mkdir(e.changesRuntimeDir,{recursive:!0}),await re($d(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function dn(e,t){if(!pM.test(e))throw new Error(`${t} must be a Git commit`)}function Ec(e){return structuredClone(e)}function yv(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function cP(e){dn(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:lP(e.contract,i.name),contractHash:O("comet.native.supervisor-contract.v1",e.contract)}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:wv,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function lP(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}async function Nv(e){let t=vM(e.parent),r=qr(e.paths.projectRoot,t);if(!r)return null;let i=qr(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=ir(e.paths.projectRoot).map(o=>he.resolve(o)).find(o=>ae(o).currentBranch===t);if(!n)return null;let a=cP({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return yv(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function Od(e){if(!Ad(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=Ce(e.integration.worktree,["rev-parse","--show-toplevel"]);if(he.resolve(t)!==he.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=Ce(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return Ce(e.integration.worktree,["rev-parse","HEAD"])}async function wM(e){let t=qr(e.paths.projectRoot,e.state.integration.targetBranch);if(!t||t===e.state.integration.targetCommit)return null;let r=e.state;if(Od(r)!==r.integration.headCommit)throw new Error("Native Supervisor integration head changed before target refresh");try{Ce(r.integration.worktree,["merge","--no-edit",r.integration.targetBranch])}catch(o){throw new Error(`Native Supervisor target drift requires conflict resolution in ${r.integration.worktree}`,{cause:o})}let n=Ce(r.integration.worktree,["rev-parse","HEAD"]),a=Ec(r);return a.integration.headCommit=n,a.finalVerification={status:"pending",summary:null},yv(a,{kind:"target-refreshed",child:null,runId:null,summary:`Target ${r.integration.targetBranch} was refreshed before delivery`}),a.stateVersion+=1,await Xn(e.paths,a),a}function yM(e,t){if(dn(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=Ec(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function uP(e){let t=Od(e);if(t===e.integration.headCommit)return e;try{Ce(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let r=Ec(e);return r.integration.headCommit=t,yv(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function dP(e,t){let r=t.verification;if(r===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let i=Od(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=r.checks.length>0&&r.checks.every(({status:o})=>o==="passed");return yM(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}async function Pc(e){let r=await Ot(e.paths,e.state.parent)??e.state;if(r.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before delivery; reload status first");if(r.finalVerification.status!=="passed")throw new Error("Native Supervisor delivery requires a passed final verification");if(!r.children.every(({status:p})=>p==="integrated"||p==="archived"))throw new Error("Native Supervisor delivery requires every child to be integrated");let n=ir(e.paths.projectRoot).map(p=>he.resolve(p)).find(p=>ae(p).currentBranch===r.integration.targetBranch);if(!n)throw new Error(`Native Supervisor target branch worktree is unavailable: ${r.integration.targetBranch}`);let a=he.resolve(n)===he.resolve(e.paths.projectRoot)?[he.relative(n,he.join(e.paths.changesDir,r.parent)).replaceAll("\\","/"),".comet/current-change.json",...e.archiveOwnedPaths??[]]:[];if(!Ad(n,a))throw new Error(`Native Supervisor target worktree is not clean: ${n}`);let o=Ce(n,["rev-parse","HEAD"]);if((()=>{try{return Ce(n,["merge-base","--is-ancestor",r.integration.headCommit,o]),!0}catch{return!1}})()){let p=await nP({paths:e.paths,state:r,targetCommit:o});if(await aP({paths:e.paths,plan:p,targetRoot:n}),r.children.every(({status:g})=>g==="archived"))return await gv(e.paths,r.parent),{state:r,targetRoot:n,targetCommit:o};let v=Ec(r);for(let g of v.children)g.status="archived";return v.stateVersion+=1,await Xn(e.paths,v),await gv(e.paths,r.parent),{state:v,targetRoot:n,targetCommit:o}}let l=Od(r);if(l!==r.integration.headCommit)throw new Error("Native Supervisor integration head changed after final verification");let u=qr(e.paths.projectRoot,r.integration.targetBranch),d=(()=>{if(!u)return!1;try{return Ce(r.integration.worktree,["merge-base","--is-ancestor",u,l]),!0}catch{return!1}})();if(u!==l&&!d&&u!==r.integration.targetCommit&&await wM({paths:e.paths,state:r}))throw new Error("Native Supervisor target changed; parent integration checks must be rerun before delivery");let f=await nP({paths:e.paths,state:r,targetCommit:l});u!==l&&Ce(n,["merge","--ff-only",r.integration.branch]);let h=Ce(n,["rev-parse","HEAD"]);if(h!==l)throw new Error("Native Supervisor target did not receive the verified integration head");let m=Ec(r);for(let p of m.children)p.status="archived";return await aP({paths:e.paths,plan:f,targetRoot:n}),m.stateVersion+=1,await Xn(e.paths,m),await gv(e.paths,r.parent),{state:m,targetRoot:n,targetCommit:h}}function fP(e,t){return he.join(oP(e,t),"cleanup.json")}function iP(e){let t=ir(e.paths.projectRoot).map(s=>he.resolve(s)),r=he.resolve(process.cwd()),i=[{root:e.state.integration.worktree,branch:e.state.integration.branch},...e.state.children.map(({name:s,projectRoot:c,task:l})=>({root:c??l?.projectRoot??gM(ae(e.paths.projectRoot).primaryWorktreeRoot??e.paths.projectRoot,e.state.parent,s),branch:`comet/supervisor/${e.state.parent}/${s}`}))].map(s=>({...s,root:he.resolve(s.root)})),n=e.targetCommit,a=[e.state.integration.branch,...e.state.children.map(({name:s})=>`comet/supervisor/${e.state.parent}/${s}`)],o=i.flatMap(s=>{let c=t.find(l=>l===s.root);return c?[{...s,root:c}]:[]});for(let s of o){if(mM(s.root,r))throw new Error(`Native Supervisor cannot clean the current worktree: ${s.root}`);if(!Ad(s.root))throw new Error(`Native Supervisor cleanup requires a clean worktree: ${s.root}`);let c=ae(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{Ce(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(us(e.paths.projectRoot,s))try{Ce(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 nP(e){let t=fP(e.paths,e.state.parent);try{let i=JSON.parse(await jd.readFile(t,"utf8"));if(i.parent===e.state.parent&&i.targetCommit===e.targetCommit&&Array.isArray(i.worktrees)&&i.expectedBranches&&typeof i.expectedBranches=="object"&&Array.isArray(i.branches)){let n=iP(e);return{parent:i.parent,targetCommit:i.targetCommit,worktrees:[...new Set([...i.worktrees,...n.worktrees])],expectedBranches:{...i.expectedBranches,...n.expectedBranches},branches:[...new Set([...i.branches,...n.branches])]}}}catch(i){if(i.code!=="ENOENT")throw i}let r=iP(e);return await re(t,r,{containedRoot:e.paths.changesRuntimeDir}),r}async function aP(e){for(let t of e.plan.worktrees){if(!ir(e.paths.projectRoot).map(a=>he.resolve(a)).includes(he.resolve(t)))continue;let i=e.plan.expectedBranches[t];if(!i)throw new Error(`Native Supervisor cleanup has no expected branch for ${t}`);let n=ae(t).currentBranch;if(n!==i)throw new Error(`Native Supervisor cleanup found unexpected branch ${n??"(detached)"} for ${t}; expected ${i}`);await QE(t),Ce(e.paths.projectRoot,["worktree","remove",t])}for(let t of e.plan.branches)us(e.paths.projectRoot,t)&&Ce(e.targetRoot,["branch","-d",t])}async function gv(e,t){await jd.rm(fP(e,t),{force:!0})}function bv(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:i.status==="ready"&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing"}));return{contractHash:null,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var wv,pM,So=A(()=>{"use strict";pv();ue();Xe();mv();_d();et();Q();ot();Lt();eP();bc();rP();vv();wv="comet.native.supervisor.v2",pM=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u});var hP={};cg(hP,{NATIVE_CHILDREN_FILE:()=>kv,NATIVE_CHILDREN_SCHEMA:()=>Qn,NATIVE_CHILDREN_SCHEMA_V2:()=>Rv,NATIVE_CHILDREN_V2_SCHEMA:()=>Zn,findNativeV1SupervisorParents:()=>EP,hasNativeSupervisorShapeIntent:()=>kP,hashNativeParentContract:()=>Md,inspectNativeChildren:()=>ta,nativeChildrenAcceptanceValidation:()=>Ld,nativeChildrenIndexDrift:()=>NP,parseNativeChildrenContract:()=>bP,readNativeChildrenContract:()=>ea,readNativeSupervisorShapeIntent:()=>Cv});import{promises as Ev}from"node:fs";import St from"node:path";function Dd(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Hd(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function mP(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function Sv(e,t){let r=St.normalize(St.resolve(e)),i=St.normalize(St.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function PM(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function vP(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function NP(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===Rv&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),d=e.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return i.uncovered=o.filter(l=>!gP(e.children,l)),wP(i)?i:null}if(e.schema===Qn&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!gP(e.children,a)),wP(i)?i:null}return null}function gP(e,t){return e.some(r=>r.covers.includes(t))}function wP(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Ld(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function RM(e){let t=Dd(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=Dd(n,`Native children acceptance_index.${i}`);if(Hd(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function CM(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let d=e[l];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(h=>d[h]!==u[h]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function bP(e,t,r={}){let i=(0,Pv.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Dd(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Qn&&a!==Zn)throw Hd(n,pP,"Native children contract"),new Error(`Native children schema must be ${Qn} or ${Zn}`);let o=a===Qn?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Hd(n,o==="indexed-v2"?bM:pP,"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 m=Dd(f,`Native child ${h}`);if(Hd(m,o==="indexed-v2"?EM:o==="summary-v2"?SM:kM,`Native ${s} child fields (child ${h})`),typeof m.name!="string"||!NM.test(m.name))throw new Error(`Native child ${h} name is invalid`);let p=o==="summary-v2";if(p){if(typeof m.summary!="string"||m.summary.trim().length===0)throw new Error(`Native child ${m.name} summary must be a non-empty string`);if(m.summary.length>2e3)throw new Error(`Native child ${m.name} summary exceeds 2000 characters`)}return{name:m.name,summary:p?m.summary:null,depends_on:mP(m.depends_on,`Native child ${m.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?mP(m.covers,`Native child ${m.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(m=>!u.has(m));if(h.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${h.join(", ")}`)}PM(c);let d=r.policy==="advisory";if(a===Rv){if(o==="indexed-v2"){let f=RM(n.acceptance_index);d||CM(f,t,r);let h=Object.keys(f);return d||vP(c,h,h),{schema:Zn,acceptance_index:f,children:c}}return{schema:Zn,children:c}}return t&&!d&&vP(c,t),{schema:Qn,children:c}}async function ea(e){let t=St.join(e.changeDir,kv);try{await Ev.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await te({root:e.changeDir,ref:kv}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=bP(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?NP(a,e.acceptanceIds,e.validation??{}):null}}function xM(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function kP(e){let t=xM(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function Cv(e){try{let t=await te({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return kP(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Md(e){return O("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function SP(e){let t=ir(e.projectRoot);t.some(i=>Sv(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>St.resolve(n)))]){let n=await Ee(i);n&&r.push({projectRoot:i,paths:await Ke(i,n.native.artifact_root),parent:Sv(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function EP(e){let t=await SP(e.paths),r=[],i=[],n=new Map;for(let a of t){let o;try{o=await Ev.readdir(a.paths.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o){if(!s.isDirectory()||s.isSymbolicLink()||s.name===e.childName)continue;let c=St.join(a.paths.changesDir,s.name),l;try{l=await Be(St.join(c,"comet-state.yaml"))}catch{continue}if(l.phase!=="build"||l.status!=="active")continue;let u=await ea({changeDir:c,...l.acceptance.length>0?{acceptanceIds:l.acceptance.map(({id:d})=>d)}:{}});!u||u.contract.schema!==Qn||u.contract.children.some(({name:d})=>d===e.childName)&&n.set(l.name,[...n.get(l.name)??[],{source:a,state:l}])}}for(let[a,o]of n){let s=e.targetBranch===null?[]:o.filter(({state:h})=>h.workspace.target_branch===e.targetBranch);if(e.targetBranch===null){i.push(`Native Supervisor Child ${e.childName} has no target branch to match parent ${a}`);continue}let c=s.find(({source:h,state:m})=>ae(h.projectRoot).currentBranch===m.workspace.change_branch);if(!c){let h=o.find(({state:m})=>m.workspace.target_branch!==e.targetBranch);if(h)i.push(`Native Supervisor parent ${a} targets ${h.state.workspace.target_branch??"(missing)"}, not ${e.targetBranch}`);else{let m=s[0]?.state??o[0].state;i.push(`Native Supervisor parent ${a} is not bound to branch ${m.workspace.change_branch}`)}continue}let{source:l,state:u}=c,d=l.paths,f=await ta({paths:d,state:u});if(!f)i.push(`Native Supervisor parent ${a} has no readable Child inspection`);else if(!f.confirmed)i.push(`Native Supervisor parent ${a} requires Shape confirmation`);else if(f.allDone)r.push({paths:d,state:u,inspection:f});else{let h=f.children.filter(({status:m})=>m!=="done").map(({name:m,status:p,message:v})=>`${m}=${p}${v?` (${v})`:""}`).join(", ");i.push(`Native Supervisor parent ${a} is not ready to advance: ${h||"Child facts are incomplete"}`)}}return n.size===0&&i.push(`Native Supervisor Child ${e.childName} has no active v1 parent declaring it`),n.size>1&&i.push(`Native Supervisor Child ${e.childName} has multiple active parents: ${[...n.keys()].join(", ")}`),r.length===1&&i.length===0?{candidate:r[0],blockers:i}:(r.length>1&&i.push(`Native Supervisor Child ${e.childName} has multiple eligible parents: ${r.map(({state:a})=>a.name).join(", ")}`),{candidate:null,blockers:i})}async function AM(e,t){let r=St.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Be(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function _M(e,t){let r;try{r=await Ev.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=St.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Be(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function IM(e,t,r){let i=St.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${St.sep}`))return null;let n=i.split(St.sep).join("/");try{let a=(0,Pv.parseDocument)(Ce(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:Qe(a.toJS({mapAsMap:!1}))}catch{return null}}function TM(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function yP(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function ta(e){let t=St.join(e.paths.changesDir,e.state.name),r=await Cv(t),i=null,n;try{n=await ea({changeDir:t,validation:Ld(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:g})=>g)}:{},policy:"advisory"})}catch(g){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${g.message}`,n=null}if(!n){let g=await Ot(e.paths,e.state.name,{diagnostics:!0});if(g){let N=bv(g);return{...N,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:N.children.map(E=>({...E,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=Md({acceptance:e.state.acceptance,children:n.contract}),o=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&e.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===Zn){let g=await Ot(e.paths,e.state.name,{diagnostics:!0});if(!g){let w=e.state.workspace.change_branch??e.state.workspace.target_branch;if(w){let S=await Nv({paths:e.paths,parent:e.state.name,targetBranch:w,contract:n.contract});S&&(g=S,await Xn(e.paths,S))}}if(g){let w=bv(g);return e.state.children_contract_hash!==a||n.drift?{...w,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(S=>({...S,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...w,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&w.confirmed}}let N=new Map(n.contract.children.map(w=>[w.name,w])),E=n.contract.children.map(w=>({name:w.name,summary:w.summary,dependsOn:[...w.depends_on],covers:[],status:s&&w.depends_on.every(S=>n.contract.children.filter(({name:k})=>k!==w.name).every(({name:k})=>k!==S))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let w of E){if(w.status!=="ready")continue;N.get(w.name).depends_on.length>0&&(w.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:E,readyChildren:E.filter(({status:w})=>w==="ready").map(({name:w})=>w),allDone:!1}}let c=await SP(e.paths),l=new Set(n.contract.children.map(({name:g})=>g)),u=new Map,d=new Map;for(let g of c){let N=g.parent&&o?`refs/heads/${o}`:"HEAD";for(let E of await _M(g,l)){let w={...E,source:g,committedState:IM(g,E.file,N)};u.set(E.state.name,[...u.get(E.state.name)??[],w])}for(let E of l){let w=await AM(g,E);w&&d.set(E,[...d.get(E)??[],{source:g,state:w}])}}let f=new Map;for(let g of n.contract.children){let N=(u.get(g.name)??[]).find(({source:S,committedState:k})=>S.parent&&k?.name===g.name&&yP(k,o));if(N){f.set(g.name,{kind:"done",phase:N.state.phase,projectRoot:N.source.projectRoot,message:null});continue}let E=u.get(g.name)?.[0];if(E){f.set(g.name,{kind:"blocked",phase:E.state.phase,projectRoot:E.source.projectRoot,message:`Native child ${g.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let w=d.get(g.name)??[];w.length>1?f.set(g.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${g.name} has multiple active workspace owners`}):w[0]&&f.set(g.name,TM(w[0].state,w[0].source,o))}let h=new Map(n.contract.children.map(g=>[g.name,g])),m=new Map,p=g=>{let N=m.get(g);if(N)return N;let E=h.get(g),S=E.depends_on.map(p).every(({status:L})=>L==="done"),k=f.get(g),R=k?.kind==="active"&&S?E.depends_on.filter(L=>!(u.get(L)??[]).some(({source:H,committedState:je})=>Sv(H.projectRoot,k.projectRoot)&&je?.name===L&&yP(je,o))):[],b,y=k?.message??null;k?.kind==="done"?(b=S?"done":"blocked",S||(y=`Native child ${g} was merged before its dependencies`)):k?.kind==="active"?(b=S&&R.length===0?"active":"blocked",S?R.length>0&&(y=`Native child ${g} does not include merged dependencies: ${R.join(", ")}`):y=`Native child ${g} started before its dependencies merged`):k?.kind==="blocked"?b="blocked":(b=s&&S?"ready":"pending",s||(y="Parent Shape confirmation is required"));let P={name:g,summary:E.summary,dependsOn:[...E.depends_on],covers:[...E.covers],status:b,phase:k?.phase??null,projectRoot:k?.projectRoot??null,message:y};return m.set(g,P),P},v=n.contract.children.map(({name:g})=>p(g));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:v,readyChildren:v.filter(({status:g})=>g==="ready").map(({name:g})=>g),allDone:v.every(({status:g})=>g==="done")}}var Pv,kv,Qn,Zn,Rv,NM,pP,bM,kM,SM,EM,Eo=A(()=>{"use strict";Pv=da(Cn(),1);Lt();bc();Ft();Xe();ot();Q();Er();So();kv="children.yaml",Qn="comet.native.children.v1",Zn="comet.native.children.v2",Rv=Zn,NM=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,pP=new Set(["schema","children"]),bM=new Set(["schema","acceptance_index","children"]),kM=new Set(["name","depends_on","covers"]),SM=new Set(["name","summary","depends_on"]),EM=new Set(["name","depends_on","covers"])});import{promises as nC}from"node:fs";import mf from"node:path";import{promises as cf}from"fs";import Me from"path";import{promises as OP}from"fs";import Po from"path";import{isDeepStrictEqual as XM}from"util";import{createHash as hC}from"crypto";function lg(e,t,r,i){return t.iteration>=r.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${r.maxIterations}`}:e.type==="invoke_skill"&&!r.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!r.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!r.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&r.confirmationRequiredFor.includes(e.ref)&&!i.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>r.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function ug(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))ug(e[t]);return Object.freeze(e)}function hi(e){return ug(structuredClone(e))}function wf(e,t,r,i){return e.resolveStep({pkg:hi(t),state:hi(r),context:hi(i)})}function dg(e,t,r,i,n,a){return e.resolveNext({pkg:hi(t),state:hi(r),step:hi(i),outcome:hi(n),context:hi(a)})}function pC(e,t,r){return hC("sha256").update(`${e}:${t}:${r??"adaptive"}`).digest("hex").slice(0,16)}function yf(e,t){return e.definition.orchestration.steps?.find(r=>r.id===t)}function fg(e,t,r,i,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=wf(i,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=yf(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:pC(s.runId,s.iteration,o.id),stepId:o.id};return mC(e,s,c,r)}function mC(e,t,r,i){let n=lg(r,t,e.guardrails,i);return n.allowed?{state:{...t,pending:r.id,status:"waiting"},action:r}:{state:t,action:null,reason:n.reason}}function hg(e,t,r,i,n){if(!t.pending||t.pending!==r.actionId)throw new Error(`Outcome does not match pending action: ${r.actionId}`);let a=t.orchestration==="deterministic"?wf(i,e,t,n):void 0,o=a?yf(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(r.status==="failed"){let c={...t.retries,[r.actionId]:(t.retries[r.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?dg(i,e,t,o,r,n):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!yf(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"}}Nn();ke();Ft();hr();Q();import{promises as um}from"fs";import qk from"path";var Wk=["outcome","scope","nonGoals","acceptanceExamples"],g0=[...Wk,"constraints","decisions","openQuestions","verificationExpectations"],w0=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],zk={maxFileBytes:hs};function Jk(e){let t=new Map,r=null,i=[],n=()=>{r!==null&&t.set(r,i.join(`
|
|
203
|
-
`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),r=o[1].trim(),i=[]):r!==null&&i.push(a)}return n(),t}async function y0(e,t){let r=qk.resolve(e,...t.split(/[\\/]/u));if(!D(e,r))throw new Error(`Artifact escapes Native change: ${t}`);let i=await um.realpath(e),n=await um.realpath(r);if(!D(i,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await um.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function tc(e){return{valid:e.length===0,findings:e}}function dm(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r=null;for(let i of e.split(/\r?\n/u)){let n=i.match(/^\s*(`{3,}|~{3,})/u);if(n){let s=n[1]?.[0];r===null?r=s:r===s&&(r=null);continue}if(r!==null)continue;let a=i.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(a)||a.includes("|")&&a.split("|").some(s=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(s)))return!0;let o=a.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let s=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(s)||/[./_-]/u.test(s))return!0}}return!1}async function fm(e,t){let r=[],i;try{i=(await te({root:e,ref:t,maxBytes:zk.maxFileBytes})).text}catch(a){return tc([{code:"brief-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of Jk(i))n.set(Wc(a)??a,o);for(let a of g0)n.has(a)||r.push({code:"brief-section-missing",message:`Missing brief section: ${a}`,path:t});for(let a of Wk)(n.get(a)??"").length===0&&r.push({code:"brief-section-empty",message:`Brief section is empty: ${a}`,path:t});return dm(i)&&r.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),tc(r)}async function hm(e,t){let r=[],i;try{i=(await te({root:e,ref:t,maxBytes:zk.maxFileBytes})).text}catch(a){return tc([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of Jk(i))n.set(gg(a)??a,o);for(let a of w0)n.has(a)?(n.get(a)??"").length===0&&r.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):r.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return tc(r)}function Zu(e,t){return qk.join(e.specsDir,t,"spec.md")}async function Gk(e,t){let r=[],i=se(e,t.name);for(let n of t.spec_changes){let a=Zu(e,n.capability),o=null;try{await T(e.nativeRoot,a),o=await fr(a)}catch(s){if(s.code!=="ENOENT"){r.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&r.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&r.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&r.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await y0(i,n.source)}catch(s){r.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return tc(r)}Ui();import{promises as RL}from"node:fs";import _E from"node:path";Xe();import Uk from"node:path";var N0="comet.native.archive-preflight.v1",b0="comet.native.archive-preflight.v1",k0="comet.native.archive-operation.v1",S0=/^[a-f0-9]{64}$/u,Kk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,E0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function ed(e,t){return e<t?-1:e>t?1:0}function P0(e,t){if(typeof e!="string"||!S0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Xr(e,t){return e===null?null:P0(e,t)}function R0(e,t){let r=Uk.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||Uk.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function C0(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function x0(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,r]of[["change",e.changeBranch],["target",e.targetBranch]])if(r!==null&&(r.length===0||r.trim()!==r||Array.from(r).some(i=>{let n=i.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 A0(e,t){if(!Kk.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 r=Xr(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),i=Xr(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Xr(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&r!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&r===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:r,actualBaseHash:i,proposedHash:n}}function _0(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:Xr(e.contractHash,"Native archive contract hash"),acceptanceHash:Xr(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Xr(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Xr(e.reportHash,"Native archive report hash"),envelopeHash:Xr(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Xr(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(r=>r===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 I0(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(i=>{if(typeof i!="string"||!E0.test(i))throw new Error(`Native archive preflight finding code is invalid: ${String(i)}`);return i}),r=[...new Set(t)].sort(ed);if(r.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return r}function T0(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 r of e.specs)r.actualBaseHash!==r.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(ed)}function Yk(e){if(!Kk.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(A0).sort((l,u)=>ed(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 r=t.map(l=>({...l,operationHash:O(k0,l)})),i=_0(e.evidence),n=x0(e.workspace),a=[...new Set([...I0(e.findingCodes??[]),...T0({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:i})])].sort(ed),o=C0(e.revision),s=R0(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:r,evidence:i,workspace:n,findingCodes:a};return{schema:N0,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:i.freshness,operationCount:r.length,operations:r,workspace:n,findingCodes:a,preflightHash:O(b0,c)}}Ft();ke();Xe();import{createHash as j0}from"node:crypto";import Xk from"node:path";var $0="comet.native.conflict-radar.v1",Nt=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}),O0="comet.native.conflict-radar.v1",H0="comet.native.conflict-radar-signals.v1",D0=/^[a-f0-9]{64}$/u,eS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,L0=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),M0=new Set(["capability","operation","baseHash"]),F0=new Set(["path","kind"]);function ao(e,t){return e<t?-1:e>t?1:0}function pm(e){return Buffer.byteLength(e,"utf8")}function mm(e,t,r){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${r} must be an object`);let i=e,n=Object.keys(i).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return i}function vm(e,t,r){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(pm(e)>r)throw new Error(`${t} exceeds its byte budget`);return e}function B0(e,t){let r=vm(e,t,Nt.maxArtifactPathBytes),i=Xk.posix.normalize(r);if(r.includes("\\")||Array.from(r).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(r)||Xk.posix.isAbsolute(i)||r.split("/").includes("..")||i!==r||i==="."||r.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return r}function tS(e,t){if(typeof e!="string"||!D0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function V0(e,t){let r=mm(e,M0,t),i=vm(r.capability,`${t} capability`,Nt.maxCapabilityBytes);if(!eS.test(i))throw new Error(`${t} capability is invalid`);if(r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=r.baseHash===null?null:tS(r.baseHash,`${t} canonical base hash`);if(r.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(r.operation!=="create"&&n===null)throw new Error(`${t} ${r.operation} operation requires a canonical base hash`);return{capability:i,operation:r.operation,baseHash:n}}function q0(e,t){let r=mm(e,F0,t);if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:B0(r.path,`${t} path`),kind:r.kind}}function W0(e,t){let r=mm(e,L0,`Conflict radar change ${t}`),i=vm(r.name,`Conflict radar change ${t} name`,Nt.maxNameBytes);if(!eS.test(i))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(r.revision)||r.revision<1)throw new Error(`Conflict radar change ${i} revision must be a positive safe integer`);if(!Array.isArray(r.specs))throw new Error(`Conflict radar change ${i} specs must be an array`);if(r.specs.length>Nt.maxSpecsPerChange)throw new Error(`Conflict radar change ${i} exceeds the spec budget`);if(!Array.isArray(r.declaredArtifacts))throw new Error(`Conflict radar change ${i} declared artifacts must be an array`);if(r.declaredArtifacts.length>Nt.maxArtifactsPerChange)throw new Error(`Conflict radar change ${i} exceeds the declared artifact budget`);let n=r.specs.map((c,l)=>V0(c,`Conflict radar change ${i} spec ${l}`)).sort((c,l)=>ao(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${i} has duplicate capabilities`);let a=r.declaredArtifacts.map((c,l)=>q0(c,`Conflict radar change ${i} artifact ${l}`)).sort((c,l)=>ao(c.path,l.path)||ao(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${i} has duplicate or conflicting artifact paths`);let s=r.workspaceIdentityHash===void 0||r.workspaceIdentityHash===null?null:tS(r.workspaceIdentityHash,`Conflict radar change ${i} workspace identity hash`);return{name:i,revision:r.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function z0(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Nt.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(W0).sort((n,a)=>ao(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)>Nt.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>Nt.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function J0(e,t){let r=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||r?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function G0(e,t){let r=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),i=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!r&&!i&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function U0(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function K0(e,t){let r=[],i=j0("sha256").update(`${H0}
|
|
204
|
-
[`),n=0,a=!1,o=l=>{n>0&&i.update(","),i.update(Ps(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),r.length<Nt.maxSignalsPerRelationship&&r.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(J0(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=G0(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return i.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:U0(e,t),signalCount:n,signalHash:i.digest("hex"),signals:r,signalsTruncated:r.length!==n}}function Qk(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function Y0(e,t){return Qk(e.classification)-Qk(t.classification)||ao(e.left,t.left)||ao(e.right,t.right)}function Zk(e,t,r,i){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:$0,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:r,relationshipsTruncated:r.length!==t.length,omittedRelationshipCount:t.length-r.length,radarHash:i}}function rS(e){let t=z0(e),r=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)r.push(K0(t[s],t[c]));r.sort(Y0);let i=r.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=O(O0,{changes:t,relationships:i}),a=r.slice(0,Nt.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Zk(t,r,a,n);for(;a.length>0&&pm(JSON.stringify(o))>Nt.maxSerializedBytes;)a=a.slice(0,-1),o=Zk(t,r,a,n);if(pm(JSON.stringify(o))>Nt.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}ri();yt();Ar();var gD=4096;async function wD(e,t=Nt.maxChanges){try{let r=await xt({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function BS(e,t){let r=await We(e,t),[i,n]=await Promise.all([r.implementation_scope?cd(e,t,r.implementation_scope):null,Tt(e,t).catch(()=>null)]);return{name:r.name,revision:r.revision,specs:r.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:i?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function ld(e,t,r={}){let n=(await wD(e,gD)).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 BS(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await BS(e,c).catch(d=>{if(r.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=rS([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"]:[]]}}ke();ot();Q();Ya();ue();ke();hr();Tn();et();Q();yt();Jn();import{promises as OD}from"fs";import HD from"path";import{isDeepStrictEqual as dd}from"util";Xe();Xe();var go={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var yD=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function ND(e,t){return e<t?-1:e>t?1:0}function bD(e,t,r,i){if(!Array.isArray(e)||e.length>r||!i&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!yD.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(ND)}function jm(e=[]){return bD(e,"Native repair failed check IDs",go.maxFailedCheckIds,!0)}function VS(e,t){let r=new Set(t);return e.every(i=>r.has(i))}function kD(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:VS(e.failedAcceptanceIds,t.failedAcceptanceIds)&&VS(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function $m(e,t){let r=1,i=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(kD(i,a))break;r+=1,i=a}return r}uc();Xi();function Om(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 qS="repairStagnation",$t={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},ED=/^[a-f0-9]{64}$/u;var PD=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),RD=["data","runId","sequence","timestamp","type"],WS=["disposition","overrideSummaryHash","signatureHash"],CD=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],zS=12;function Dm(e,t){return e<t?-1:e>t?1:0}function JS(e,t,r){let i=Object.keys(e).sort(Dm);if(i.length!==t.length||i.some((n,a)=>n!==t[a]))throw new Error(`${r} fields are invalid`)}function ud(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function pc(e,t){if(typeof e!="string"||!ED.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function xD(e){if(!Array.isArray(e)||e.length>go.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(Dm)}function GS(e){if(typeof e!="string"||e.length===0||e.length>$t.maxRunIdCharacters||Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Hm(e,t,r,i,n=!1){if(r.nodes+=1,r.nodes>$t.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>$t.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(`${i} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>$t.maxTextCharacters&&(!n||e.length>$t.maxEventDataCharacters))throw new Error(`${i} contains oversized text`);if(r.characters+=e.length,r.characters>$t.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${i} contains a non-JSON value`);if(r.ancestors.has(e))throw new Error(`${i} contains a cycle`);r.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>$t.maxArrayEntries)throw new Error(`${i} contains an oversized array`);e.forEach((s,c)=>Hm(s,t+1,r,`${i}[${c}]`));return}let a=ud(e,i),o=Object.keys(a);if(o.length>$t.maxObjectFields)throw new Error(`${i} contains too many fields`);for(let s of o){if(s.length===0||s.length>$t.maxKeyCharacters)throw new Error(`${i} contains an invalid field name`);if(r.characters+=s.length,r.characters>$t.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Hm(a[s],t+1,r,`${i}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{r.ancestors.delete(e)}}}function AD(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 _D(e,t,r){let i=ud(e,`Native repair trajectory event ${t+1}`);if(JS(i,RD,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(i.sequence)||i.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(AD(i.timestamp),typeof i.type!="string"||!PD.has(i.type))throw new Error("Native repair trajectory event type is invalid");if(GS(i.runId)!==r)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Hm(i.data,0,n,"Native trajectory event data"),ud(i.data,"Native repair trajectory event data"),{event:i,dataNodes:n.nodes,dataCharacters:n.characters}}function Lm(e){let t=ud(e,"Native repair trajectory projection"),r=Object.keys(t).sort(Dm),i=r.length===WS.length&&r.every((l,u)=>l===WS[u]);i||JS(t,CD,"Native repair trajectory projection");let n=pc(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:pc(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(i)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=pc(t.contractHash,"Native repair trajectory contract hash"),s=xD(t.failedAcceptanceIds),c=jm(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 ID(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 TD(e,t){let r=t.filter(s=>s.kind==="failure"),i=r.length+1,n=e.maxVerifyFailures??zS;if(i>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=$m({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},r),o=i>=n?"hard-stop":a<go.warningAtConsecutiveFailures?"continue":a<go.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function jD(e,t,r){let i=t.filter(a=>a.kind==="failure"),n=r?.maxVerifyFailures??zS;if(i.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(r?.disposition!=="manual-stop"||r.signatureHash!==e.signatureHash||i.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 US(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>$t.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=GS(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 r=[],i=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=_D(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>$t.maxTotalDataNodes||c>$t.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,h=Object.hasOwn(f,"repairScopeHash")?pc(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?pc(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,qS)){if(i?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(h!==null&&n!==null&&h!==n||h===null&&(i?.disposition==="manual-stop"||i?.disposition==="hard-stop"))){r.length=0,i=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 m=Lm(f[qS]);if(ID(f,m),m.overrideSummaryHash===null)m.contractHash!==null&&a!==null&&m.contractHash!==a&&(r.length=0,o=0),m.contractHash!==null&&(a=m.contractHash),m.contractHash===null&&h!==null&&n!==null&&h!==n&&(r.length=0,o=0),h!==null&&(n=h),TD(m,r),o+=1,r.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:m.signatureHash,...m.contractHash===null?{}:{failedAcceptanceIds:[...m.failedAcceptanceIds],failedCheckIds:[...m.failedCheckIds]}});else{if(i?.contractHash===null&&h!==null&&n!==null&&h!==n)throw new Error("Native repair override cannot cross implementation scope progress");jD(m,r,i);let p=r.at(-1);if(!p||p.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");r.push({kind:"override",revision:d.sequence,iteration:p.iteration,signatureHash:m.signatureHash,summaryHash:m.overrideSummaryHash})}if(i=m,r.length>go.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:r,latestProjection:i}}function KS(e){return US(e).history}function YS(e){let t=US(e).latestProjection;return t?{...t}:null}hr();var Or={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:[]},mc=F("comet-native-runtime:v3:scope-reopen"),$D=[{skillVersion:"3",skillHash:F("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:F("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:F("comet-native-runtime:v1")}];function XS(e){return e.skillVersion===Or.definition.metadata.version&&e.skillHash===mc||$D.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var Mm={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(r=>r.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};Ui();hr();Ui();async function rn(e){let r={sequence:(await dt(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 gk(e.changeDir,e.run.trajectoryRef,r),r}async function Un(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:F(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await wk(e.changeDir,e.run.checkpointRef,t),t}hr();function QS(e){return F(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}))}Js();$s();var oE=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],DD=new Set(oE),sE=new Set([...oE,"minimum_runtime_version","revision"]),LD=new Set([...sE,"operation"]),MD=512*1024,Fm=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),FD=new Set([...Fm,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),vc=class extends Error{constructor(r){super(`Native transition for ${r} requires doctor migration before recovery`);this.change=r;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function it(e,t){return HD.join(M(e,t),"transition.json")}function BD(e){return`transition-${e}`}async function VD(e,t,r){let i=BD(t);return ji(e,i,r)}async function Kn(e,t,r,i){let n=await VD(e,t,r);try{return await i()}finally{await $i(n)}}function hd(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Vm(e,t){let r=Object.keys(e).find(i=>!t.has(i));if(r)throw new Error(`Native transition journal contains unknown field: ${r}`)}function fd(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Hr(e,t){return dd(e,t)}function Bm(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let r=e,i=Object.keys(r),n=i.find(u=>!FD.has(u)),a=[...Fm].find(u=>!Object.hasOwn(r,u)),o=Fm.size+(Object.hasOwn(r,"implementationScopeHash")?1:0)+(Object.hasOwn(r,"repairScopeHash")?1:0)+(Object.hasOwn(r,"repairStagnation")?1:0)+(Object.hasOwn(r,"returnToBuild")?1:0);if(n||a||i.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(r.previousPhase)||!["shape","build","verify","archive"].includes(r.nextPhase))throw new Error("Native transition journal event phases are invalid");if(r.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(r.returnToBuild!==void 0&&typeof r.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(Om(r.summary,"Native transition journal event summary"),Gt(r.summary)!==r.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(r.artifacts)||r.artifacts.length>128||r.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(r.noCodeReason!==null&&(Om(r.noCodeReason,"Native transition journal event no-code reason"),Gt(r.noCodeReason)!==r.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(r.verificationResult!==null&&r.verificationResult!=="pass"&&r.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(r,"implementationScopeHash")?r.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||r.previousPhase!=="build"&&r.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(r,"repairStagnation")?Lm(r.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(r.previousPhase!=="verify"||r.nextPhase!=="build"||r.verificationResult!=="fail")||!u&&(r.previousPhase!=="build"||r.nextPhase!=="verify"||r.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(r,"repairScopeHash")?r.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||r.previousPhase!=="build"&&r.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:t,summary:r.summary,artifacts:[...r.artifacts],noCodeReason:r.noCodeReason,verificationResult:r.verificationResult,...r.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function qD(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e,i=Object.keys(r),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(i.length===n.size&&i.every(a=>n.has(a))&&r.reason==="spec-rebase")return Bm({previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:r.evidenceHash,summary:r.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Bm(e,t)}function qm(e,t,r=!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 i=r?qD(e.eventData,e.evidenceHash):Bm(e.eventData,e.evidenceHash),n=Gi(e.nextRun),a=e.previousRun===null?null:Gi(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:i}}function ZS(e,t,r=!1){if(e.skill!==Or.definition.metadata.name||(r?!XS(e):e.skillVersion!==Or.definition.metadata.version||e.skillHash!==mc)||e.orchestration!==Or.definition.orchestration.mode||e.pendingRef!==_t.pendingRef||e.trajectoryRef!==_t.trajectoryRef||e.contextRef!==_t.contextRef||e.artifactsRef!==_t.artifactsRef||e.checkpointRef!==_t.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function eE(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 tE(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 Wm(e,t,r,i=!1,n="advance"){let{previousRun:a,nextRun:o}=r;if(ZS(o,"next Run",i||a!==null),tE(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(ZS(a,"previous Run",!0),tE(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(!dd(eE(a),eE(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function WD(e,t,r){return F(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:r}))}function cE(e,t,r){return e.phase!=="shape"&&t.phase==="build"&&r.verificationResult===null?"spec-rebase":"advance"}function rE(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function zm(e,t,r,i,n=!1){let a=r.eventData,o=rE(e),s=rE(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(i==="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&&dd(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(i==="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&&dd(e.spec_changes,t.spec_changes),l=QS({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||r.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(i==="spec-rebase"){let c=WD(e.name,a.summary,t.spec_changes),l=F(`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&&r.evidenceHash!==c||n&&r.evidenceHash!==c&&r.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 Jm(e,t){let r=hd(e);if(Vm(r,LD),r.schema!==Di)throw new Error(`Expected Native transition schema ${Di}`);let i=fd(r.minimum_runtime_version,"Native transition minimum_runtime_version");if(i>3)throw new Error(`Native transition requires runtime protocol ${i}; current protocol is ${3}`);if(i!==3)throw new Error(`Native transition ${Di} minimum_runtime_version must be ${3}`);let n=fd(r.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(r.operation!=="advance"&&r.operation!=="spec-rebase"&&r.operation!=="evidence-retreat"&&r.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=qm(r,t),o=wt(r.previousState),s=wt(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(zm(o,s,a,r.operation),Wm(o,s,a,!1,r.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:Di,minimum_runtime_version:3,revision:n,operation:r.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 zD(e,t){let r=hd(e);if(Vm(r,DD),r.schema!==On)throw new Error(`Expected Native transition schema ${On}`);let i=qm(r,t,!0),n=Hn(r.previousState),a=Hn(r.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return zm(n,a,i,cE(n,a,i.eventData),!0),Wm(n,a,i,!0),{schema:On,id:i.id,change:t,evidenceHash:i.evidenceHash,createdAt:i.createdAt,previousState:n,nextState:a,previousRun:i.previousRun,nextRun:i.nextRun,eventData:i.eventData}}function Gm(e,t){let r=hd(e);if(Vm(r,sE),r.schema!==Gr)throw new Error(`Expected Native transition schema ${Gr}`);if(fd(r.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Gr} minimum_runtime_version must be 2`);let n=fd(r.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=qm(r,t,!0),o=Pr(r.previousState),s=Pr(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(zm(o,s,a,cE(o,s,a.eventData),!0),Wm(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Gr,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 JD(e,t){let r=hd(e);if(r.schema===Di)return{status:"current",journal:Jm(r,t)};if(r.schema===On)return{status:"migration-required",journal:zD(r,t)};if(r.schema===Gr)return{status:"migration-required",journal:Gm(r,t)};throw new Error(`Unsupported Native transition journal schema: ${String(r.schema)}`)}async function Um(e,t){let r=it(e,t),i=$(e,r);await T(i,r);try{let n=await oe({root:i,file:r,maxBytes:MD,label:`Native transition journal ${t}`});return JD(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function ii(e,t){let r=await Um(e,t);if(!r)return null;if(r.status==="migration-required")throw new vc(t);return r.journal}function iE(e,t){if(Hr(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(Hr(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function nE(e,t){if(Hr(e,t.nextState))return"next";if(Hr(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function GD(e){let{journal:t}=e;return lE({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 lE(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function aE(e,t){let r=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),i=r.filter(({event:a})=>a.type==="run_started"),n=r.filter(({event:a})=>a.type==="state_transitioned");if(r.length!==i.length+n.length||i.length>(t.previousRun===null?1:0)||n.length>1||t.previousRun===null&&n.length===1&&(i.length!==1||i[0].index>=n[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...i,...n]){let o=GD({sequence:a.index+1,journal:t,type:a.event.type});if(!Hr(lE(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:i[0]?.event??null,transitioned:n[0]?.event??null}}async function pd(e,t,r){if(await io(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Wu(e,t);let i=await ii(e,t);if(!i)return null;let n=M(e,t),a=aE(await dt(n,i.nextRun.trajectoryRef),i),[o,s]=await Promise.all([Ve(n),We(e,t)]),c=iE(o,i),l=nE(s,i);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${i.change}; recovery journal was preserved`);if(c==="previous"&&(await Vn(n,i.nextRun),await r?.afterRunStateWritten?.(i)),!Hr(await Ve(n),i.nextRun))throw new Error(`Native transition Run content changed while continuing ${i.change}; recovery journal was preserved`);if(l==="previous"){let v=await Qu(e,i.nextState,i.previousState.revision);if(!Hr(v,i.nextState))throw new Error(`Native transition change write diverged for ${i.change}; recovery journal was preserved`);await r?.afterChangeStateWritten?.(i)}if(!Hr(await We(e,t),i.nextState))throw new Error(`Native transition change content changed while continuing ${i.change}; recovery journal was preserved`);let u=await ii(e,t);if(!u||!Hr(u,i))throw new Error(`Native transition journal changed while continuing ${i.change}; it was preserved`);let d=aE(await dt(n,i.nextRun.trajectoryRef),i);i.previousRun===null&&(d.started||await rn({changeDir:n,run:i.nextRun,type:"run_started",data:{runtime:"comet-native",phase:i.previousState.phase,transitionId:i.id},now:new Date(i.createdAt)}));let f=d.transitioned;f||(f=await rn({changeDir:n,run:i.nextRun,type:"state_transitioned",data:{...i.eventData,transitionId:i.id},now:new Date(i.createdAt)})),await Un({changeDir:n,run:i.nextRun,trajectoryOffset:f.sequence,evidenceHash:i.evidenceHash,now:new Date(i.createdAt)});let[h,m]=await Promise.all([Ve(n),We(e,t)]);iE(h,{...i,previousRun:i.nextRun}),nE(m,{...i,previousState:i.nextState});let p=await ii(e,t);if(!p||!Hr(p,i))throw new Error(`Native transition journal changed while continuing ${i.change}; it was not removed`);return await OD.rm(it(e,t),{force:!0}),i.nextState}async function uE(e,t,r){return de(e,`continue transition ${t}`,()=>Kn(e,t,`continue transition ${t}`,()=>pd(e,t,r)))}xs();Ft();ke();Ft();xs();Xe();import dE from"node:path";var UD="comet.native.contract.v1",KD="comet.native.acceptance-set.v1",fE=/^[a-f0-9]{64}$/u,gc={maxAcceptanceCriteria:Cs.maxCriteria};function hE(e,t){let r=dE.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||dE.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function pE(e){return O("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
|
|
205
|
-
`))}function YD(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(fE))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(fE))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=hE(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:pE(e.markdown)},markdown:e.markdown}}function XD(e,t){return mE(e.id,t.id)}function mE(e,t){return e<t?-1:e>t?1:0}function vE(e){let t=hE(e.briefSource??"brief.md","Native brief source"),r=e.specs.map(YD).sort((d,f)=>mE(d.snapshot.capability,f.snapshot.capability)),i=r.map(({snapshot:d})=>d.capability);if(new Set(i).size!==i.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...r.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=du(e.briefMarkdown,t,gc.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of r)f===null||d.source===null||(a.push(...fu(f,d.source,gc.maxAcceptanceCriteria-a.length)),a.push(...GN(f,d.source,gc.maxAcceptanceCriteria-a.length)));if(a.sort(XD),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>gc.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${gc.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:pE(e.briefMarkdown)},c=r.map(({snapshot:d})=>d),l=O(KD,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:O(UD,u)}}var md={maxSpecs:64,maxFileBytes:hs,maxTotalBytes:4*1024*1024};async function wo(e){if(e.specChanges.length>md.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await te({root:e.changeDir,ref:e.briefRef,maxBytes:md.maxFileBytes}),r=t.size,i=[];for(let n of e.specChanges){if(n.operation==="remove"){i.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 te({root:e.changeDir,ref:n.source,maxBytes:md.maxFileBytes});if(r+=a.size,r>md.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");i.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:vE({briefSource:t.ref,briefMarkdown:t.text,specs:i}),sourceCount:i.filter(n=>n.source!==null).length+1,totalBytes:r}}ri();Fn();Xi();uc();import{execFile as vL}from"node:child_process";vd();Km();ke();import{promisify as gL}from"node:util";ke();import{promises as nL}from"fs";ue();ke();hr();Q();yt();ds();Jn();import yo from"path";var an={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},No=/^[a-f0-9]{64}$/u;function gd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function wd(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function nn(e,t,r=2e3){if(typeof e!="string"||e.length===0||e.length>r)throw new Error(`${t} must be a non-empty string of at most ${r} characters`);return e}function gE(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ym(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function QD(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||yo.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let r=yo.posix.normalize(t);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return r}function Xm(e,t){return yo.join(M(e,t),"checkpoints","progress.json")}function on(e,t){return yo.join(M(e,t),"checkpoint-journal.json")}function Qm(e,t,r){if(!No.test(r))throw new Error("Native checkpoint manifest hash is invalid");return yo.join(M(e,t),"checkpoints","manifests",`${r}.json`)}function ZD(e){if(!No.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Zm(e,t,r){let i=await oe({root:e,file:t,maxBytes:an.maxDocumentBytes,label:r});return JSON.parse(i.bytes.toString("utf8"))}function eL(e,t){let r=gd(e,`checkpoint manifest artifact ${t}`);wd(r,["path","hash","size"],`checkpoint manifest artifact ${t}`);let i=QD(nn(r.path,`checkpoint artifact ${t} path`,4096)),n=kr(i);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${i}`);if(typeof r.hash!="string"||!No.test(r.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:i,hash:r.hash,size:Ym(r.size,`checkpoint artifact ${t} size`)}}function yd(e,t){let r=gd(e,"Native checkpoint manifest");if(wd(r,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),r.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(r.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(r.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(r.artifacts.length>an.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let i=r.artifacts.map(eL),n=[...i].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(i)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(i.map(o=>o.path)).size!==i.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Ym(r.totalBytes,"checkpoint manifest totalBytes");if(i.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>an.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:i,totalBytes:a}}function ev(e){return F(JSON.stringify(yd(e,e.change)))}function tv(e,t){let r=gd(e,"Native progress checkpoint");if(wd(r,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),r.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(r.change!==t)throw new Error("Native checkpoint change mismatch");let i=r.phase;if(i!=="shape"&&i!=="build"&&i!=="verify"&&i!=="archive")throw new Error("Native checkpoint phase is invalid");let n=gE(r.previousRevision,"Native checkpoint previousRevision"),a=gE(r.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=nn(r.manifestHash,"Native checkpoint manifestHash",64);if(!No.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=ZD(o);if(r.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=nn(r.inputHash,"Native checkpoint inputHash",64);if(!No.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=nn(r.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Ym(r.artifactCount,"Native checkpoint artifactCount");if(u>an.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=nn(r.summary,"Native checkpoint summary"),f=nn(r.nextAction,"Native checkpoint nextAction");if(Gt(d)!==d||Gt(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:nn(r.id,"Native checkpoint id",128),change:t,phase:i,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function tL(e,t){let r=gd(e,"Native checkpoint journal");if(wd(r,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),r.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(r.change!==t)throw new Error("Native checkpoint journal change mismatch");let i=wt(r.previousState),n=wt(r.nextState),a=tv(r.checkpoint,t),o=yd(r.manifest,t),s=nn(r.inputHash,"Native checkpoint journal inputHash",64),c=F(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!No.test(s)||s!==a.inputHash||s!==c||r.id!==a.id||r.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(i.name!==t||n.name!==t||n.revision!==i.revision+1||a.previousRevision!==i.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==ev(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:i,nextState:n,checkpoint:a,manifest:o}}async function rL(e,t,r){let i=yo.resolve(e.projectRoot,...t.split("/"));if(!D(e.projectRoot,i)||D(e.nativeRoot,i)||D(e.runtimeDir,i))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=np(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await oe({root:e.projectRoot,file:i,maxBytes:an.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>r?.afterParentChainCaptured?.(t),afterOpen:()=>r?.afterOpen?.(t),beforeRead:()=>r?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function iL(e,t){let r=Xm(e,t),i=$(e,r);await T(i,r);try{return tv(await Zm(i,r,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function rv(e,t,r){let i=Qm(e,t,r),n=$(e,i);await T(n,i);let a=await Zm(n,i,"Native checkpoint manifest"),o=yd(a,t);if(iv(e,o),ev(o)!==r)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function sn(e,t){let r=on(e,t),i=$(e,r);await T(i,r);try{let n=tL(await Zm(i,r,"Native checkpoint journal"),t);return iv(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function wE(e,t,r,i){let n=yd(r,t);iv(e,n);let a=ev(n),o=Qm(e,t,a),s=$(e,o);await T(s,o);try{let c=await rv(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 re(o,n,{containedRoot:s,beforeCommit:i?.beforeCommit}),a}function iv(e,t){for(let r of t.artifacts){let i=np(e,r.path);if(i)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${i}): ${r.path}`)}}async function yE(e,t){let r=tv(t,t.change),i=await rv(e,r.change,r.manifestHash),n=F(JSON.stringify({summary:r.summary,nextAction:r.nextAction,artifacts:i.artifacts}));if(r.inputHash!==n||r.artifactCount!==i.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=Xm(e,t.change),o=$(e,a);await T(o,a),await re(a,r,{containedRoot:o})}async function NE(e){let t;try{t=await iL(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:Xm(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let r=[],i=[];t.stateRevision!==e.stateRevision&&r.push("state-revision-changed");let n=null;try{n=await rv(e.paths,e.name,t.manifestHash);let a=F(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 rL(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&r.push(`artifact-changed:${o.path}`)}catch{r.push(`artifact-unavailable:${o.path}`)}}catch(a){r.push("checkpoint-manifest-invalid"),i.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:Qm(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:r.length===0?"fresh":"stale",reasons:r,findings:i}}et();async function bE(e,t,r){let i=await sn(e,t);if(!i)return null;if(await wE(e,i.change,i.manifest)!==i.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Qu(e,i.nextState,i.previousState.revision,{allowPendingCheckpointRecovery:!0}),await r?.afterStateWritten?.(i),await yE(e,i.checkpoint),await r?.afterProgressWritten?.(i),await nL.rm(on(e,t),{force:!0}),i}async function kE(e,t,r){return de(e,`continue checkpoint ${t}`,()=>Kn(e,t,`continue checkpoint ${t}`,async()=>(await pd(e,t),bE(e,t,r))))}ue();ad();Q();nr();import{constants as nv,promises as Ut}from"node:fs";import bo from"node:path";var aL=/^[a-f0-9]{64}$/u,oL=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,wc=512*1024;function sL(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Nd(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Rt(r,i)?J(r,i):J(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function cL(e,t){let r=bo.resolve(e),i=bo.resolve(t);if(!D(r,i))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=r;for(let o of["",...bo.relative(r,i).split(bo.sep).filter(Boolean)]){o&&(a=bo.join(a,o));let s=await Ut.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Ut.realpath(a);if(n.length>0&&!D(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 SE(e){for(let t of e){let r=await Ut.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!sL(t,r)||await Ut.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function lL(e){if(!aL.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function uL(e){let t=oL.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function dL(e,t,r){return Ii(M(e,t),lL(r))}async function fL(e,t,r){let i=await cL(r,bo.dirname(e)),n=await Ut.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>wc)throw new Error(`Native check receipt exceeds ${wc} bytes`);let[a,o]=await Promise.all([Ut.realpath(t),Ut.realpath(e)]);if(!D(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":nv.O_RDONLY|nv.O_NOFOLLOW|nv.O_NONBLOCK,c=await Ut.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(),Ut.lstat(e),Ut.realpath(e)]);if(await SE(i),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Nd(n,l)||!Nd(l,u))throw new Error("Native check receipt changed while opening");let f=[],h=0,m=Buffer.allocUnsafe(16*1024);for(;;){let N=wc+1-h,E=await c.read(m,0,Math.min(m.length,N),null);if(E.bytesRead===0)break;if(h+=E.bytesRead,h>wc)throw new Error(`Native check receipt exceeds ${wc} bytes`);f.push(Buffer.from(m.subarray(0,E.bytesRead)))}let[p,v,g]=await Promise.all([c.stat(),Ut.lstat(e),Ut.realpath(e)]);if(await SE(i),!v.isFile()||v.isSymbolicLink()||g!==o||!D(a,g)||!Nd(l,p)||!Nd(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,h).toString("utf8"))}finally{await c.close()}}async function EE(e,t,r){let i=uL(r),n=M(e,t),a=dL(e,t,i),o=$(e,a);await T(o,a);let s=nd(await fL(a,n,o));if(s.change!==t||s.receiptHash!==i)throw new Error("Native check receipt ref/hash/change mismatch");return s}ri();et();Jn();var yc=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Fn();ho();Xi();var HK=64*1024;var DK=3600*1e3;var LK=gL(vL);var wL=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function PE(e,t){let r=[];for(let i of wL){let n=e.bindings[i],a=t[i];n!==a&&r.push(`${i}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:r.length===0,mismatches:r}}async function RE(e){if(e.receipt.kind!=="static-inspection")return null;let t=await EE(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}ho();var cn=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};function NL(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 bL(e){let t=NL(e.bundle.baseline),r=await Qp(e.paths,t,{origin:"explicit",now:e.now});return Em({baseline:t,current:r,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function xE(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await fc(e.paths,e.state.name,e.state.implementation_scope),r=await wo({changeDir:se(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),i=await bL({paths:e.paths,bundle:t,now:e.now}),n=[];return r.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),i!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:r.contract,contractHash:r.contract.contractHash,acceptanceHash:r.contract.acceptanceHash,findingCodes:n}}async function AE(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await xE(e),r=[...new Set(t.findingCodes)].sort();return{freshness:r.length===0?"fresh":"stale",findingCodes:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function kL(e){let t=await te({root:se(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:KN(t.text)}}function SL(e){let{receipt:t,implementationScope:r}=e,i=[],n=Sm({baseline:r.baseline,current:r.current,declaredArtifacts:r.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!==r.scope.scopeHash||t.implementation.expectedSnapshotHash!==r.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==r.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==r.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&i.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&i.push("verification-receipt-outcome-mismatch"),i}function EL(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:Im(e.implementationScope.scope.declaredArtifacts)}}async function CE(e){let t=await hc(e.paths,e.state.name,e.ref),r=[];t.role!==e.role&&r.push(`role: expected ${e.role}, got ${t.role}`);let i=PE(t,e.expectedBindings);if(r.push(...i.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&r.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),r.length>0)throw new cn([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:r}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await RE({paths:e.paths,state:e.state,receipt:t});if(n){let a=SL({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 PL(e){let t=EL({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),r=[];for(let i of e.requiredReceiptRefs){let n=await CE({...e,ref:i,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof cn)return r.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 i of e.trace.entries)if(i.status!=="missing")for(let n of i.evidenceRefs){let a=await CE({...e,result:i.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:i.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof cn)return r.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(i.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(r.length>0)throw new cn(r)}function av(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function bd(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:av(e.state.verification_result,"missing"),envelope:null};try{let[t,r]=await Promise.all([xE(e),vo(e.paths,e.state.name,e.state.verification_evidence)]);if(r.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:av(e.state.verification_result,"stale"),envelope:null};let i=await kL({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(i.hash!==r.reportHash||i.ref!==r.reportRef)&&n.push("verification-report-stale"),(r.result!==e.state.verification_result||r.implementationScopeRef!==e.state.implementation_scope||r.partialAllowanceRef!==e.state.partial_allowance||r.sourceRevision>=e.state.revision||r.contractHash!==t.bundle.scope.contractHash||r.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await PL({paths:e.paths,state:e.state,result:r.result,trace:r.acceptanceTrace,requiredReceiptRefs:r.requiredReceiptRefs,contractHash:r.contractHash,implementationScope:t.bundle,sourceRevision:r.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":r.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:r.contractHash,acceptanceHash:r.acceptanceCriteriaHash,implementationScopeHash:r.implementationScopeHash,reportHash:r.reportHash,envelopeHash:r.envelopeHash,partialAllowanceHash:r.partialAllowanceHash,skippedAcceptanceCount:r.acceptanceTrace.skipped},envelope:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:av(e.state.verification_result,"invalid"),envelope:null}}}Ar();function CL(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function IE(e){try{return await RL.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function xL(e,t){try{return(await te({root:e,ref:t})).hash}catch(r){if(r.code==="ENOENT")return null;throw r}}async function AL(e,t,r){let i=Zu(e,r.capability);if(!D(e.nativeRoot,i))throw new Error(`Native canonical spec escapes its root: ${r.capability}`);let n=_E.relative(e.nativeRoot,i).replaceAll("\\","/"),a=await xL(e.nativeRoot,n),o=null;if(r.operation!=="remove"){if(!r.source)throw new Error(`Native proposed spec is missing: ${r.capability}`);o=(await te({root:se(e,t),ref:r.source})).hash}return{capability:r.capability,operation:r.operation,expectedBaseHash:r.operation==="create"?null:r.base_hash,actualBaseHash:a,proposedHash:o}}async function _L(e,t){return IE(it(e,t))}async function kd(e){let t=e.now??new Date,r=await We(e.paths,e.name),i=await Tt(e.paths,e.name),n=await Ee(e.paths.projectRoot),a=CL(r.name,t),o=_E.resolve(e.paths.nativeRoot,...a.split("/"));if(!D(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(r.spec_changes.map(m=>AL(e.paths,r.name,m))),bd({paths:e.paths,state:r,now:t}),ld(e.paths,r.name),io(e.paths,r.name),no(e.paths,r.name),_L(e.paths,r.name),IE(o)]);return Yk({change:r.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:r.schema,revision:r.revision,phase:r.phase,archived:r.archived,pendingJournal:u||d||f,targetRef:a,targetExists:h,specs:s,evidence:c.evidence,workspace:i?.schema==="comet.native.workspace.v3"?{schema:i.schema,isolation:i.isolation,changeBranch:i.changeBranch,targetBranch:i.targetBranch,finish:i.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}hr();yt();import{promises as ov}from"node:fs";import ni from"node:path";var IL="comet.native.archive-tree.v1",TL={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function $E(e){let t={...TL,...e};for(let[r,i]of Object.entries(t))if(!Number.isSafeInteger(i)||i<=0)throw new Error(`Native Archive content limit ${r} must be a positive safe integer`);return t}function TE(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,r)=>t.name.localeCompare(r.name)))}function jE(e,t,r,i){if(r.entryCount+=1,r.entryCount>i.maxEntries)throw new Error(`Native Archive content exceeds ${i.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>i.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${i.maxRefBytes} bytes: ${t.ref}`);let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(r.manifestBytes+=n+(e.length===0?0:1),r.manifestBytes+2>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);e.push(t)}async function OE(e,t,r,i,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await xt({root:e,directory:t,label:`Native Archive content directory ${ni.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=TE(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=ni.join(t,u.name),f=ni.relative(e,d).replaceAll("\\","/"),h=await ov.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()){jE(r,{ref:f,kind:"directory"},i,n),await OE(e,d,r,i,n,a+1);continue}if(!u.isFile()||!h.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let m=await oe({root:e,file:d,maxBytes:n.maxFileBytes,label:`Native Archive content file ${f}`});if(i.totalBytes+=m.size,i.totalBytes>n.maxTotalBytes)throw new Error(`Native Archive content exceeds ${n.maxTotalBytes} total file bytes`);jE(r,{ref:f,kind:"file",hash:m.hash,size:m.size},i,n),await o.verify()}await o.verify();let l=await xt({root:e,directory:t,label:`Native Archive content directory ${ni.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(TE(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${ni.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function HE(e,t={}){let r=$E(t);e=ni.resolve(e);let i=await ov.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await OE(e,e,n,{entryCount:0,totalBytes:0,manifestBytes:0},r,0);let o=JSON.stringify(n);if(Buffer.byteLength(o,"utf8")>r.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${r.maxManifestBytes} bytes`);return F(`${IL}\0${o}`)}async function wr(e,t={}){let r=$E(t);e=ni.resolve(e);let i;try{i=await ov.lstat(e)}catch(n){if(n.code==="ENOENT")return null;throw n}if(i.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(i.isFile())return{kind:"file",hash:(await oe({root:ni.dirname(e),file:e,maxBytes:r.maxFileBytes,label:`Native Archive transaction file ${ni.basename(e)}`})).hash};if(i.isDirectory())return{kind:"directory",hash:await HE(e,r)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}ue();nr();import{promises as ft}from"node:fs";import Oe from"node:path";Q();yt();Mn();var cv=16*1024*1024,jL=256*1024,$L=16*1024,Nc="comet.native.archive-cas.v1";function OL(e,t){let r="runtime/",i=t.startsWith(r),n=i?e.runtimeDir:e.nativeRoot,a=i?t.slice(r.length):t,o=Oe.resolve(n,...a.split("/"));if(!D(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function ze(e,t){let r=OL(e,t);return T($(e,r),r)}function ln(e,t,r="file"){return t===null?e===null:e?.kind===r&&e.hash===t}function ko(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function kt(e){let t=await wr(e.target);if(!ln(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${ko(t)}`);return t}async function lv(e,t){let r=await Cr(e,t),i=await oe({root:e.runtimeDir,file:r.journal,maxBytes:jL,label:`Native Archive transaction journal ${t}`}),n=Cu(JSON.parse(i.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function Sd(e,t,r){let i=Cu({...t,status:r}),n=await Cr(e,i.id);return await re(n.journal,i,{containedRoot:e.runtimeDir}),i}function Ed(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function DE(e){return{...Ed(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function un(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function HL(e,t){return un(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function ne(e){try{return await ft.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Dr(e){let t=await ft.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let r=DE(t),i=await oe({root:$(e.paths,e.file),file:e.file,maxBytes:cv,label:e.label}),n=await ft.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!HL(r,DE(n))||i.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:Ed(n),size:i.size}}function DL(e,t,r,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${r} 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} ${r} record has an invalid shape`);let o=n.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${r} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${r} 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} ${r} identity ${c} is invalid`);if(n.schema!==Nc||n.operationId!==t.id||n.role!==r||n.hash!==i)throw new Error(`Archive CAS ${t.id} ${r} record is not transaction-bound`);return{schema:Nc,operationId:t.id,role:r,hash:i,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function Lr(e,t,r,i){let n=await Cr(e,t.id),a=Oe.join(n.backups,".cas"),o=`.${Oe.basename(i)}.comet-archive-cas-${t.id}-${r.id}`,s={directory:a,originalRecord:Oe.join(a,`${r.id}.original.json`),postRecord:Oe.join(a,`${r.id}.post.json`),candidate:Oe.join(a,`${r.id}.candidate`),originalQuarantine:Oe.join(Oe.dirname(i),`${o}.original`),rollbackQuarantine:Oe.join(Oe.dirname(i),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>T($(e,c),c))),s}async function Kt(e){if(!await ne(e.file))return null;let t=await oe({root:e.paths.runtimeDir,file:e.file,maxBytes:$L,label:`Archive CAS ${e.operation.id} ${e.role} record`});return DL(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function Pd(e){let t=await Kt(e);if(t){if(!un(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await Rr({root:e.paths.runtimeDir,directory:Oe.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let r={schema:Nc,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await re(e.file,r,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let i=await Kt(e);if(!i||!un(i.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return i}async function Te(e){let t=await Dr({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!un(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function LL(e){let t=await Dr({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),r=await Pd({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Te({paths:e.paths,file:e.file,operation:e.operation,record:r,label:e.label}),r}async function ML(e){if(!await ne(e.quarantine)||await ne(e.target))return;let t=await dr({root:$(e.paths,e.target),directory:Oe.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await ft.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[r,i]=await Promise.all([ft.lstat(e.quarantine),ft.lstat(e.target)]);if(!un(Ed(r),Ed(i)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await ft.unlink(e.quarantine),await t.verify()}async function BE(e){if(await ne(e.quarantine)){await Te({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await dr({root:$(e.paths,e.target),directory:Oe.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Te({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 Te({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await ft.rename(e.target,e.quarantine),await t.verify(),await Te({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(r){throw await ML(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:r})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function Yn(e){if(!await ne(e.file))return;await Te(e);let t=await dr({root:$(e.paths,e.file),directory:Oe.dirname(e.file),label:e.label});await t.verify(),await Te(e),await ft.unlink(e.file),await t.verify()}async function LE(e,t,r){if(!t.backup||t.expectedTargetHash===null)return;let i=await ze(e,t.target),n=await ze(e,t.backup),a=await wr(n);if(a!==null){if(!ln(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await kt({target:i,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await Bi({sourceRoot:$(e,i),source:i,targetRoot:$(e,n),target:n,maxBytes:cv,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>r?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await kt({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function VE(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let r=await Lr(e.paths,e.journal,e.operation,e.target),i=await Kt({paths:e.paths,file:r.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await ne(r.originalQuarantine)){if(!i)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Te({paths:e.paths,file:r.originalQuarantine,operation:e.operation,record:i,label:`Archive apply quarantine ${e.operation.target}`}),await LE(e.paths,e.operation,e.hooks),{record:i,quarantine:r.originalQuarantine}}if(!await ne(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return i??=await LL({paths:e.paths,file:e.target,recordFile:r.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Te({paths:e.paths,file:e.target,operation:e.operation,record:i,label:`Archive apply target ${e.operation.target}`}),await LE(e.paths,e.operation,e.hooks),await BE({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:r.originalQuarantine,record:i,hooks:e.hooks}),{record:i,quarantine:r.originalQuarantine}}async function ME(e){let t=await Lr(e.paths,e.journal,e.operation,e.target);return await ne(t.candidate)?(await Dr({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await Rr({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await Bi({sourceRoot:$(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:cv,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 FL(e){let t=e.operation.stagedHash,r=await Lr(e.paths,e.journal,e.operation,e.target),i=await Kt({paths:e.paths,file:r.postRecord,operation:e.operation,role:"post",expectedHash:t});if(i&&await ne(e.target))return await Te({paths:e.paths,file:e.target,operation:e.operation,record:i,label:`Archive write target ${e.operation.target}`}),await ne(r.candidate)&&await Yn({paths:e.paths,file:r.candidate,operation:e.operation,record:i,label:`Archive write candidate ${e.operation.target}`}),i;if(await ne(e.target)){let c=await ME(e),l=await Dr({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await Dr({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!un(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return i=await Pd({paths:e.paths,file:r.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await Yn({paths:e.paths,file:c,operation:e.operation,record:i,label:`Archive write candidate ${e.operation.target}`}),i}let n=await ME(e),a=await Dr({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await Rr({root:$(e.paths,e.target),directory:Oe.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await dr({root:$(e.paths,e.target),directory:Oe.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Te({paths:e.paths,file:n,operation:e.operation,record:{schema:Nc,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await ft.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 Dr({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!un(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return i=await Pd({paths:e.paths,file:r.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await Yn({paths:e.paths,file:n,operation:e.operation,record:i,label:`Archive write candidate ${e.operation.target}`}),i}async function BL(e,t,r,i){let n=await ze(e,r.target),a=await ze(e,r.staged);if(await kt({target:a,expectedHash:r.stagedHash,label:`Archive transaction staged file ${r.staged}`}),r.expectedTargetHash!==null){let o=await Lr(e,t,r,n);(!await Kt({paths:e,file:o.postRecord,operation:r,role:"post",expectedHash:r.stagedHash})||!await ne(n))&&await VE({paths:e,journal:t,operation:r,target:n,hooks:i})}else{let o=await wr(n);if(o!==null&&!ln(o,r.stagedHash))throw new Error(`Archive transaction target ${r.target} changed before create: ${ko(o)}`)}await FL({paths:e,journal:t,operation:r,staged:a,target:n,hooks:i}),await kt({target:n,expectedHash:r.stagedHash,label:`Archive transaction target ${r.target}`})}async function VL(e,t,r,i){let n=await ze(e,r.target);await VE({paths:e,journal:t,operation:r,target:n,hooks:i}),await kt({target:n,expectedHash:null,label:`Archive transaction target ${r.target}`})}async function qL(e,t){let r=await ze(e,t.source),i=await ze(e,t.target),[n,a]=await Promise.all([wr(r),wr(i)]);if(!(n===null&&ln(a,t.expectedSourceHash,"directory"))){if(!ln(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${ko(n)}, target=${ko(a)}`);await ft.mkdir(Oe.dirname(i),{recursive:!0}),await ft.rename(r,i),await kt({target:i,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function WL(e,t,r,i){return r.type==="write"?BL(e,t,r,i):r.type==="remove"?VL(e,t,r,i):qL(e,r)}function zL(e){let t=0,r=!1,i=[];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"){r=!0;continue}if(!r)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);i.push(a.id),t+=1,r=!1}return i}async function JL(e,t,r,i){let n=await ze(e,r.target);if(r.type==="write"){let a=await ze(e,r.staged);await kt({target:a,expectedHash:r.stagedHash,label:`Completed Archive staged file ${r.staged}`});let o=await Lr(e,t,r,n),s=await Kt({paths:e,file:o.postRecord,operation:r,role:"post",expectedHash:r.stagedHash});if(!s)throw new Error(`Completed Archive target ${r.target} has no CAS identity`);if(await Te({paths:e,file:n,operation:r,record:s,label:`Completed Archive target ${r.target}`}),r.expectedTargetHash!==null){await kt({target:await ze(e,r.backup),expectedHash:r.expectedTargetHash,label:`Completed Archive backup ${r.backup}`});let c=await Kt({paths:e,file:o.originalRecord,operation:r,role:"original",expectedHash:r.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${r.target} has no original CAS identity`);if(await ne(o.originalQuarantine))await Te({paths:e,file:o.originalQuarantine,operation:r,record:c,label:`Completed Archive original quarantine ${r.target}`});else if(!i)throw new Error(`Completed Archive original quarantine ${r.target} disappeared`)}return}if(r.type==="remove"){await kt({target:n,expectedHash:null,label:`Completed Archive target ${r.target}`}),await kt({target:await ze(e,r.backup),expectedHash:r.expectedTargetHash,label:`Completed Archive backup ${r.backup}`});let a=await Lr(e,t,r,n),o=await Kt({paths:e,file:a.originalRecord,operation:r,role:"original",expectedHash:r.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${r.target} has no original CAS identity`);if(await ne(a.originalQuarantine))await Te({paths:e,file:a.originalQuarantine,operation:r,record:o,label:`Completed Archive original quarantine ${r.target}`});else if(!i)throw new Error(`Completed Archive original quarantine ${r.target} disappeared`);return}i||(await kt({target:await ze(e,r.source),expectedHash:null,label:`Completed Archive move source ${r.source}`}),await kt({target:n,expectedHash:r.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${r.target}`}))}async function qE(e,t,r){let i=t.status==="prepared"?await Sd(e,t,"applying"):t;if(i.status!=="applying")throw new Error(`Native Archive transaction ${i.id} cannot apply from ${i.status}`);let n=await qi(e,i.id),a=zL({journal:i,events:n}),o=new Set(a),s=n.some(l=>l.type==="archive-finalization-started");for(let l of i.operations.slice(0,a.length))await JL(e,i,l,s);let c=o.size;for(let l of i.operations)o.has(l.id)||(l.id==="archive-change"&&await r?.beforeArchiveChangeMove?.(l),await Wt(e,i.id,"operation-started",l.id),await WL(e,i,l,r),await Wt(e,i.id,"operation-completed",l.id),c+=1,await r?.afterOperation?.(l,c));return i=await lv(e,i.id),i}async function GL(e){try{return await Te(e),!0}catch{return!1}}async function UL(e){await Te({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await dr({root:$(e.paths,e.target),directory:Oe.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Te({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await ft.link(e.quarantine,e.target)}catch(r){throw r.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:r}):r}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await Te({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function sv(e){if(e.operation.type!=="write")return;let t=await Lr(e.paths,e.journal,e.operation,e.target);if(!await ne(t.candidate))return;let r=await Dr({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await Yn({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:Nc,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:r.identity},label:`Archive write candidate ${e.operation.target}`})}async function KL(e,t,r,i){let n=await ze(e,r.target),a=await Lr(e,t,r,n),o=r.expectedTargetHash,s=o===null?null:await Kt({paths:e,file:a.originalRecord,operation:r,role:"original",expectedHash:o}),c=r.type==="write"?await Kt({paths:e,file:a.postRecord,operation:r,role:"post",expectedHash:r.stagedHash}):null;if(r.type==="write"&&!c&&await ne(a.candidate)&&await ne(n)){let l=await Dr({paths:e,file:a.candidate,expectedHash:r.stagedHash,label:`Archive write candidate ${r.target}`}),u=await Dr({paths:e,file:n,expectedHash:r.stagedHash,label:`Archive rollback target ${r.target}`});un(l.identity,u.identity)&&(c=await Pd({paths:e,file:a.postRecord,operation:r,role:"post",expectedHash:r.stagedHash,identity:u.identity}))}if(await ne(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${r.target} has no CAS identity`);await Te({paths:e,file:a.rollbackQuarantine,operation:r,record:c,label:`Archive rollback quarantine ${r.target}`})}if(await ne(n)&&!(s!==null&&await GL({paths:e,file:n,operation:r,record:s,label:`Archive rollback target ${r.target}`}))){if(!c){if(!s){let u=await wr(n);if(ln(u,o)){await sv({paths:e,journal:t,operation:r,target:n});return}}throw new Error(`Archive rollback target ${r.target} is occupied by an external object`)}await BE({paths:e,operation:r,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:i})}if(o===null){if(await ne(n))throw new Error(`Archive rollback create target ${r.target} could not be removed`)}else if(!await ne(n)){if(!s||!await ne(a.originalQuarantine))throw new Error(`Archive rollback original target ${r.target} cannot be recovered safely`);await UL({paths:e,operation:r,target:n,quarantine:a.originalQuarantine,record:s,hooks:i})}s&&await ne(a.originalQuarantine)&&await Yn({paths:e,file:a.originalQuarantine,operation:r,record:s,label:`Archive rollback original quarantine ${r.target}`}),c&&await ne(a.rollbackQuarantine)&&await Yn({paths:e,file:a.rollbackQuarantine,operation:r,record:c,label:`Archive rollback quarantine ${r.target}`}),await sv({paths:e,journal:t,operation:r,target:n}),await kt({target:n,expectedHash:o,label:`Archive rollback target ${r.target}`})}async function YL(e,t){let r=await ze(e,t.source),i=await ze(e,t.target),[n,a]=await Promise.all([wr(r),wr(i)]);if(!(ln(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!ln(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${ko(n)}, target=${ko(a)}`);await ft.mkdir(Oe.dirname(r),{recursive:!0}),await ft.rename(i,r)}}async function WE(e,t,r){let i=await qi(e,t.id);if(i.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 Sd(e,t,"rolling-back");await Wt(e,n.id,"rollback-started");let a=new Set(i.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 YL(e,o):await KL(e,n,o,r));return await Wt(e,n.id,"rollback-completed"),n=await Sd(e,n,"rolled-back"),n}async function FE(e,t,r){let i=await ze(e,r.target);if(r.type==="write"){let n=await Lr(e,t,r,i),a=await Kt({paths:e,file:n.postRecord,operation:r,role:"post",expectedHash:r.stagedHash});if(!a)throw new Error(`Archive commit target ${r.target} has no CAS identity`);await Te({paths:e,file:i,operation:r,record:a,label:`Archive commit target ${r.target}`});return}await kt({target:i,expectedHash:null,label:`Archive commit target ${r.target}`})}async function XL(e,t){for(let r of t.operations){if(r.type==="move")continue;let i=await ze(e,r.target),n=await Lr(e,t,r,i);if(await ne(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${r.target}`);if(await FE(e,t,r),r.expectedTargetHash!==null){let a=await Kt({paths:e,file:n.originalRecord,operation:r,role:"original",expectedHash:r.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${r.target} has no original CAS identity`);await ne(n.originalQuarantine)&&await Yn({paths:e,file:n.originalQuarantine,operation:r,record:a,label:`Archive commit original quarantine ${r.target}`})}await sv({paths:e,journal:t,operation:r,target:i})}for(let r of t.operations)r.type!=="move"&&await FE(e,t,r)}async function Rd(e,t,r){return r==="commit"&&await XL(e,t),await Wt(e,t.id,r),r==="commit"?Sd(e,t,"committed"):t}ke();ue();Nn();ke();ri();var IY=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});hr();Tn();et();Q();yt();ys();import{promises as QL}from"fs";import ZL from"path";var uv="comet.selection.v2",eM=16*1024;function Cd(e){return ZL.join(e,".comet","current-change.json")}function tM(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function zE(e){return e===null||typeof e=="string"}function rM(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!tM(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&&!zE(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:uv,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==uv)throw new Error(`current change selection schema must be ${uv}`);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(!zE(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 dv(e){let t;try{let i=Cd(e),{bytes:n}=await An(i,eM,{label:"current change selection"});t=n.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...rM(t)}}async function JE(e){await QL.rm(Cd(e),{force:!0})}async function GE(e,t,r){let i=await dv(e);return i.status!=="selected"||i.selection.workflow!==t||i.selection.change!==r?!1:(await JE(e),!0)}ke();ot();et();Lt();ue();import{promises as ra}from"node:fs";import pn from"node:path";Ft();Xe();Eo();So();ke();mv();Er();js();Sc();_d();function jM(e){return e.state_version+1}function $M(e){return e.map(t=>({...t,result:"pending",reason:null}))}function OM(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:Jr(e.summary),completed_at:e.completedAt}}function xv(e){let t=Qe(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=(e.now??new Date).toISOString(),i=Oi(t,OM({state:t,outcome:"recovery",summary:e.reason,completedAt:r})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?$M(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return Qe({...i,phase:"build",status:"active",state_version:jM(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"}})}ue();_s();import{promises as RP}from"node:fs";import Rc from"node:path";function Fd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Bd(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Mr(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function PP(e,t){return e===null?null:Mr(e,t)}function qd(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function HM(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 DM(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Vd(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Av(e,t){if(e===null)return null;let r=Mr(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function _v(e,t){let r=Mr(e,t);if(!Rc.isAbsolute(r))throw new Error(`${t} must be absolute`);return Rc.resolve(r)}function LM(e,t){let r=`Native local checks[${t}]`,i=Fd(e,r);if(Bd(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((l,u)=>Mr(l,`${r}.argv[${u}]`,!0)),a=Vd(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Av(i.startedAt,`${r}.startedAt`),s=Av(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=qd(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:Mr(i.id,`${r}.id`),name:Mr(i.name,`${r}.name`),operationId:Mr(i.operationId,`${r}.operationId`),status:a,repeatable:DM(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:qd(i.executionCount,`${r}.executionCount`),argv:n,cwd:_v(i.cwd,`${r}.cwd`),exitCode:HM(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Mr(i.log,`${r}.log`)}}function Iv(e){let t="Native local execution state",r=Fd(e,t);if(Bd(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==As)throw new Error(`Native local execution schema must be ${As}`);let i=Fd(r.workspace,"Native local workspace");Bd(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Fd(r.execution,"Native local execution");Bd(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Av(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Mr(o.operationId,"Native local execution.operationId"),stage:Vd(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Vd(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:PP(o.executionId,"Native local execution.executionId"),status:Vd(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:qd(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(LM);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:As,change:Mr(r.change,"Native local change"),basedOnStateVersion:qd(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:_v(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:_v(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:PP(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function fn(e){return Iv({schema:As,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:Rc.resolve(e.projectRoot),worktreeRoot:Rc.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Wd(e){let t;try{t=await RP.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return Iv(r)}async function ai(e,t,r={}){let i=Iv(t);await RP.mkdir(Rc.dirname(e),{recursive:!0}),await re(e,i,r)}et();pu();Er();La();js();Sc();_d();ue();Nn();Sc();import{promises as MM}from"node:fs";function hn(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(hn).join(" ");return`| ${
|
|
201
|
+
`),e.omissionOverflow&&Ki(a,"existing-overflow",e.omissionOverflow);let o=(f,h)=>{h||(i+=1),n+=1,Ki(a,"omission",f)},s=f=>{i+=1,n+=1,Ki(a,"entry",f)},c=()=>{for(let f=r.length-1;f>=0;f-=1){let h=r[f];if(!(h.reason==="git-enumeration-limit"||h.reason==="git-selection-changed"||h.reason==="physical-enumeration-limit"||h.reason==="physical-selection-changed"))return r.splice(f,1),h}return null},l=()=>({...e,complete:i===0,entries:t,omitted:r,omittedCount:i,omissionOverflow:{ref:`native-snapshot://omitted-overflow/${"0".repeat(64)}`,hash:"0".repeat(64),count:n}}),u=l();for(;nc(u)>zn;){if(r.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(r.length/4));for(let m=0;m<h;m+=1){let p=c();if(p===null)break;o(p,!0)}}else if(t.length>0){let h=Math.max(1,Math.ceil(t.length/4));for(let m of t.splice(-h))s(m)}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 ym(e){let t=Kr(e),r=t.entries.map((n,a)=>iH(n,`Snapshot entry ${a}`));if(r.sort(aH),new Set(r.map(n=>n.path)).size!==r.length)throw new Error("Snapshot entries must not contain duplicate paths");let i=t.omitted.map((n,a)=>nH(n,`Snapshot omission ${a}`));return i.sort(oH),sH({schema:dS,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:r,omitted:i,omittedCount:t.omittedCount,...t.omissionOverflow?{omissionOverflow:{ref:t.omissionOverflow.ref,hash:t.omissionOverflow.hash,count:t.omissionOverflow.count}}:{}})}function ac(e){let t=new Map;for(let[r,i]of e.entries()){if(i.kind!=="file"&&i.kind!=="directory")throw new Error(`Declared artifact ${r} kind is invalid`);let n={path:Yi(i.path,`Declared artifact ${r} path`),kind:i.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((r,i)=>rt(r.path,i.path)||rt(r.kind,i.kind))}function oc(e,t){return e.kind==="file"?e.path===t:t===e.path||t.startsWith(`${e.path}/`)}function nS(e){return e?{hash:e.hash,size:e.size}:null}function km(e,t,r){let i=0,n=0;for(;i<e.entries.length||n<t.entries.length;){let a=e.entries[i],o=t.entries[n],s=a===void 0?1:o===void 0?-1:rt(a.path,o.path),c=s<=0?a:void 0,l=s>=0?o:void 0;if(s<=0&&(i+=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&&r({path:u,kind:c?l?"modified":"removed":"added",before:nS(c),after:nS(l)})}}function pS(e,t){return{...e,attributedTo:t.filter(r=>oc(r,e.path))}}function Sm(e){let t=ac(e.declaredArtifacts),r=[];return km(e.baseline,e.current,i=>{r.push(pS(i,t))}),r}function Zr(e,t){return{id:`scope:${O(X0,e)}`,kind:e.kind,source:e.source,path:e.path,reason:t}}function cH(e,t){let r=t.omitted.map(i=>Zr({kind:"snapshot-omission",source:e,path:i.path,evidence:{reason:i.reason,size:i.size,type:i.type}},`${e} snapshot omitted ${i.path}: ${i.reason}`));return t.complete||r.push(Zr({kind:"snapshot-incomplete",source:e,path:null,evidence:{omittedCount:t.omittedCount}},`${e} snapshot is incomplete`)),t.omissionOverflow&&r.push(Zr({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`)),r}function aS(e,t){return cH(e,{...t,omitted:[]}).filter(r=>r.kind!=="snapshot-omission")}function Nm(e,t){return rt(e.kind,t.kind)||rt(e.source,t.source)||rH(e.path,t.path)||rt(e.id,t.id)}function lH(e){return[...new Map(e.map(r=>[r.id,r])).values()].sort(Nm)}function mS(e){return[...new Set(e.map((t,r)=>Yi(t,`Git path ${r}`)))].sort(rt)}function oS(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 uH(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 vS(e){if(!e||e.provider!=="git")throw new Error("Native external drift provider is invalid");let t=mS(e.paths);if(t.length===0)throw new Error("Native external drift requires at least one path");return{provider:"git",baseCommit:oS(e.baseCommit,"Native external drift base commit"),targetBranch:uH(e.targetBranch,"Native external drift target branch"),targetCommit:oS(e.targetCommit,"Native external drift target commit"),paths:t}}function gS(e){if(typeof e.contractHash!="string"||!bm.test(e.contractHash))throw new Error("Contract hash must be a SHA-256 hash");return{contractHash:e.contractHash,declaredArtifacts:ac(e.declaredArtifacts),noCodeReason:e.noCodeReason?.trim()||null,...e.gitChangedPaths===void 0?{}:{gitChangedPaths:mS(e.gitChangedPaths)},...e.externalDrift===void 0?{}:{externalDrift:vS(e.externalDrift)}}}function dH(e,t,r,i,n){let a=[],o=i===void 0?null:new Set(i),s=[],c=[],l=0,u=!1,d=0,f=0;return km(e,t,h=>{let m=r.some(p=>oc(p,h.path));if(d+=1,c.push(h.path),!m&&!n?.has(h.path)&&(f+=1),o?.has(h.path)&&s.push(h.path),!u&&a.length<eH){let p=pS(h,r),v=nc(p);l+v<=zn?(a.push(p),l+=v):u=!0}}),{candidates:a,gitPathsPresentInChanges:s,changePaths:c,totalChanges:d,totalUnattributed:f}}function wS(e,t){return Zr({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 fH(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 r={changes:oo(Number(t[1]),"Scope overflow change count"),unresolved:oo(Number(t[2]),"Scope overflow unresolved count"),unattributed:oo(Number(t[3]),"Scope overflow unattributed count")},i=Wn(t[4],"Scope detail overflow hash");if(JSON.stringify(e)!==JSON.stringify(wS(i,r)))throw new Error("Implementation scope detail overflow is inconsistent");return{...r,hash:i}}function hH(e){let t=uS("sha256");t.update(`${Q0}
|
|
202
|
+
`);let r=0;km(e.baseline,e.current,n=>{if(r>=e.detailedChangeCount){Ki(t,"change",n);let a=0;for(let o of e.declaredArtifacts)oc(o,n.path)&&(a+=1,Ki(t,"change-attribution",o));Ki(t,"change-end",{attributionCount:a}),a===0&&Ki(t,"unattributed-change",{after:n.after,before:n.before,changeKind:n.kind,path:n.path})}r+=1});let i=0;for(let[n,a]of[["baseline",e.baseline],["current",e.current]])for(let o of a.omitted)i>=e.detailedOmissionCount&&Ki(t,"snapshot-omission",{source:n,...o}),i+=1;return t.digest("hex")}function yS(e,t,r){let{contractHash:i,declaredArtifacts:n,noCodeReason:a}=r,o=dH(e,t,n,r.gitChangedPaths,r.externalDrift?new Set(r.externalDrift.paths):void 0);if(r.externalDrift){let R=new Set(r.externalDrift.paths),b=new Set(o.changePaths),y=r.externalDrift.paths.filter(P=>!b.has(P)||n.some(L=>oc(L,P)));if(y.length>0)throw new Error(`Native external drift contains paths outside the unowned change set: ${y.slice(0,8).join(", ")}`);if(R.size!==r.externalDrift.paths.length)throw new Error("Native external drift paths must be unique")}let s=O(rc,e),c=O(rc,t),l=[],u=new Set(r.externalDrift?.paths??[]);for(let[R,b]of[["baseline",e],["current",t]])for(let y of b.omitted){if(l.length>=tH)break;l.push(Zr({kind:"snapshot-omission",source:R,path:y.path,evidence:{reason:y.reason,size:y.size,type:y.type}},`${R} snapshot omitted ${y.path}: ${y.reason}`))}let d=e.omitted.length+t.omitted.length,f=[...aS("baseline",e),...aS("current",t),...o.totalChanges===0&&a===null?[Zr({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(r.gitChangedPaths===void 0)return;let R=new Set(o.gitPathsPresentInChanges);return{advisoryOnly:!0,changedPaths:r.gitChangedPaths,pathsPresentInSnapshotChanges:r.gitChangedPaths.filter(b=>R.has(b)),pathsAbsentFromSnapshotChanges:r.gitChangedPaths.filter(b=>!R.has(b))}},m=R=>{let b=o.candidates.slice(0,R.detailedChangeCount),y=b.filter(tr=>tr.attributedTo.length===0&&!u.has(tr.path)),P=o.totalChanges-b.length,L=o.totalUnattributed-y.length,H=d-R.detailedOmissionCount,je=L+H,me=[...y.map(tr=>Zr({kind:"unattributed-change",source:"implementation-scope",path:tr.path,evidence:{after:tr.after,before:tr.before,changeKind:tr.kind}},`Changed path is not covered by a declared artifact: ${tr.path}`)),...l.slice(0,R.detailedOmissionCount),...f,...je>0?[wS(R.overflowHash,{changes:P,unattributed:L,unresolved:je})]:[]],ie=lH(me),Nr=R.includeGitAdvisory?h():void 0;return{schema:gm,contractHash:i,baselineProjectionRef:wm(s),baselineProjectionHash:s,currentProjectionRef:wm(c),currentProjectionHash:c,complete:ie.length===0,declaredArtifacts:n,changes:b,unattributed:y,unresolvedScopes:ie,noCodeReason:a,...Nr?{gitAdvisory:Nr}:{},...r.externalDrift?{externalDrift:r.externalDrift}:{}}},p=o.candidates.length,v=l.length,g=r.gitChangedPaths!==void 0,N="0".repeat(64);for(;;){let R=m({detailedChangeCount:p,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:N});if(nc({...R,scopeHash:N})<=zn)break;if(g){g=!1;continue}if(v>0){v-=Math.max(1,Math.ceil(v/4));continue}if(p>0){p-=Math.max(1,Math.ceil(p/4));continue}throw new Error("Native implementation scope metadata exceeds its evidence byte budget")}let w=o.totalChanges>p||d>v?hH({baseline:e,current:t,declaredArtifacts:n,detailedChangeCount:p,detailedOmissionCount:v}):N,S=m({detailedChangeCount:p,detailedOmissionCount:v,includeGitAdvisory:g,overflowHash:w}),k={...S,scopeHash:O(fS,S)};if(nc(k)>zn)throw new Error("Native implementation scope exceeded its evidence byte budget after fitting");return k}function Em(e){let t=ym(e.baseline),r=ym(e.current),i=gS(e);return{authority:i,baseline:t,current:r,scope:yS(t,r,i)}}function jr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function $r(e,t,r,i){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 Wn(e,t){if(typeof e!="string"||!bm.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function sS(e,t,r){let i=wm(t);if(e!==i)throw new Error(`${r} ref/hash mismatch`);return i}function so(e,t){let r=jr(e,"Native snapshot projection");if($r(r,["schema","origin","complete","limits","entries","omitted","omittedCount"],["capture","omissionOverflow","policy"],"Native snapshot projection"),r.schema!==dS)throw new Error("Native snapshot projection schema is invalid");let i=Kr({schema:"comet.native.content-snapshot.v1",origin:r.origin,...r.capture===void 0?{}:{capture:r.capture},createdAt:"1970-01-01T00:00:00.000Z",complete:r.complete,limits:r.limits,...r.policy===void 0?{}:{policy:r.policy},entries:r.entries,omitted:r.omitted,omittedCount:r.omittedCount,...r.omissionOverflow===void 0?{}:{omissionOverflow:r.omissionOverflow}}),n=ym(i);if(O(rc,r)!==O(rc,n))throw new Error("Native snapshot projection is not canonical");let a=O(rc,n);if(t!==void 0&&Wn(t,"Snapshot projection hash")!==a)throw new Error("Native snapshot projection content hash mismatch");return n}function Pm(e,t){let r=jr(e,`Declared artifact ${t}`);if($r(r,["path","kind"],[],`Declared artifact ${t}`),r.kind!=="file"&&r.kind!=="directory")throw new Error(`Declared artifact ${t} kind is invalid`);return{path:Yi(r.path,`Declared artifact ${t} path`),kind:r.kind}}function cS(e,t){if(e===null)return null;let r=jr(e,t);return $r(r,["hash","size"],[],t),{hash:Wn(r.hash,`${t} hash`),size:oo(r.size,`${t} size`)}}function lS(e,t){let r=jr(e,`Implementation change ${t}`);if($r(r,["path","kind","before","after","attributedTo"],[],`Implementation change ${t}`),r.kind!=="added"&&r.kind!=="modified"&&r.kind!=="removed")throw new Error(`Implementation change ${t} kind is invalid`);if(!Array.isArray(r.attributedTo))throw new Error(`Implementation change ${t} attributedTo must be an array`);let i=r.attributedTo.map(Pm),n=ac(i);if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Implementation change ${t} attribution must be sorted and unique`);let a=cS(r.before,`Implementation change ${t} before`),o=cS(r.after,`Implementation change ${t} after`);if(r.kind==="added"&&(a!==null||o===null)||r.kind==="removed"&&(a===null||o!==null)||r.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:Yi(r.path,`Implementation change ${t} path`),kind:r.kind,before:a,after:o,attributedTo:i}}function mH(e,t){let r=jr(e,`Unresolved scope ${t}`);$r(r,["id","kind","source","path","reason"],[],`Unresolved scope ${t}`);let i=new Set(["unattributed-change","snapshot-omission","snapshot-incomplete","snapshot-omission-overflow","scope-detail-overflow","missing-no-code-reason"]);if(typeof r.kind!="string"||!i.has(r.kind))throw new Error(`Unresolved scope ${t} kind is invalid`);if(r.source!=="baseline"&&r.source!=="current"&&r.source!=="implementation-scope")throw new Error(`Unresolved scope ${t} source is invalid`);if(typeof r.id!="string"||!/^scope:[a-f0-9]{64}$/u.test(r.id))throw new Error(`Unresolved scope ${t} id is invalid`);if(r.path!==null&&typeof r.path!="string")throw new Error(`Unresolved scope ${t} path is invalid`);if(typeof r.reason!="string"||r.reason.length===0||r.reason.trim()!==r.reason)throw new Error(`Unresolved scope ${t} reason is invalid`);return{id:r.id,kind:r.kind,source:r.source,path:r.path===null?null:r.kind==="snapshot-omission"?hS(r.path,`Unresolved scope ${t} path`):Yi(r.path,`Unresolved scope ${t} path`),reason:r.reason}}function ic(e,t){if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error(`${t} must be an array of paths`);let r=e.map((n,a)=>Yi(n,`${t} ${a}`)),i=[...new Set(r)].sort(rt);if(JSON.stringify(r)!==JSON.stringify(i))throw new Error(`${t} must be sorted and unique`);return r}function NS(e){let t=jr(e,"Native implementation external drift");if($r(t,["provider","baseCommit","targetBranch","targetCommit","paths"],[],"Native implementation external drift"),t.provider!=="git")throw new Error("Native implementation external drift provider is invalid");let r=ic(t.paths,"Native external drift paths");return vS({provider:"git",baseCommit:t.baseCommit,targetBranch:t.targetBranch,targetCommit:t.targetCommit,paths:r})}function co(e){let t=jr(e,"Native implementation scope"),r=[...pH].filter(y=>y!=="gitAdvisory"&&y!=="externalDrift");if($r(t,r,["gitAdvisory","externalDrift"],"Native implementation scope"),t.schema!==gm)throw new Error("Native implementation scope schema is invalid");let i=Wn(t.contractHash,"Implementation scope contractHash"),n=Wn(t.baselineProjectionHash,"Implementation scope baselineProjectionHash"),a=sS(t.baselineProjectionRef,n,"Implementation scope baseline projection"),o=Wn(t.currentProjectionHash,"Implementation scope currentProjectionHash"),s=sS(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(Pm);if(JSON.stringify(c)!==JSON.stringify(ac(c)))throw new Error("Implementation scope declared artifacts must be sorted and unique");let l=t.changes.map(lS),u=[...l].sort((y,P)=>rt(y.path,P.path));if(JSON.stringify(l)!==JSON.stringify(u)||new Set(l.map(y=>y.path)).size!==l.length)throw new Error("Implementation scope changes must be sorted and unique");let d=new Set(c.map(y=>`${y.kind}:${y.path}`));if(l.some(y=>y.attributedTo.some(P=>!d.has(`${P.kind}:${P.path}`))))throw new Error("Implementation scope change references an undeclared artifact");if(l.some(y=>JSON.stringify(y.attributedTo)!==JSON.stringify(c.filter(P=>oc(P,y.path)))))throw new Error("Implementation scope change attribution is inconsistent");let f=t.unattributed.map(lS),h=t.externalDrift===void 0?void 0:NS(t.externalDrift),m=new Set(h?.paths??[]),p=l.filter(y=>y.attributedTo.length===0&&!m.has(y.path));if(JSON.stringify(f)!==JSON.stringify(p))throw new Error("Implementation scope unattributed changes are inconsistent");let v=t.unresolvedScopes.map(mH),g=v.filter(y=>y.kind==="scope-detail-overflow");if(g.length>1)throw new Error("Implementation scope has multiple detail overflow records");let N=g[0]===void 0?null:fH(g[0]);if(N&&(N.changes+N.unresolved===0||N.unattributed>N.changes||N.unattributed>N.unresolved))throw new Error("Implementation scope detail overflow counts are inconsistent");let E=t.noCodeReason,w=[...p.map(y=>Zr({kind:"unattributed-change",source:"implementation-scope",path:y.path,evidence:{after:y.after,before:y.before,changeKind:y.kind}},`Changed path is not covered by a declared artifact: ${y.path}`)),...l.length+(N?.changes??0)===0&&E===null?[Zr({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")]:[]],S=v.filter(y=>y.kind==="unattributed-change"||y.kind==="missing-no-code-reason");if(JSON.stringify(v)!==JSON.stringify([...v].sort(Nm))||new Set(v.map(y=>y.id)).size!==v.length||JSON.stringify(S)!==JSON.stringify(w.sort(Nm))||t.complete!==(v.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 k;if(t.gitAdvisory!==void 0){let y=jr(t.gitAdvisory,"Implementation scope Git advisory");if($r(y,["advisoryOnly","changedPaths","pathsPresentInSnapshotChanges","pathsAbsentFromSnapshotChanges"],[],"Implementation scope Git advisory"),y.advisoryOnly!==!0)throw new Error("Implementation scope Git advisory must remain advisory-only");let P=ic(y.changedPaths,"Git changed paths"),L=ic(y.pathsPresentInSnapshotChanges,"Git present paths"),H=ic(y.pathsAbsentFromSnapshotChanges,"Git absent paths"),je=[...L,...H].sort(rt);if(JSON.stringify(je)!==JSON.stringify(P)||H.some(me=>l.some(ie=>ie.path===me)))throw new Error("Implementation scope Git advisory partition is invalid");k={advisoryOnly:!0,changedPaths:P,pathsPresentInSnapshotChanges:L,pathsAbsentFromSnapshotChanges:H}}let R={schema:gm,contractHash:i,baselineProjectionRef:a,baselineProjectionHash:n,currentProjectionRef:s,currentProjectionHash:o,complete:t.complete,declaredArtifacts:c,changes:l,unattributed:f,unresolvedScopes:v,noCodeReason:E,...k?{gitAdvisory:k}:{},...h?{externalDrift:h}:{}},b=Wn(t.scopeHash,"Implementation scope scopeHash");if(O(fS,R)!==b)throw new Error("Implementation scope content hash mismatch");return{...R,scopeHash:b}}function vH(e){let t=jr(e,"Native implementation scope authority");if($r(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 r=t.declaredArtifacts.map(Pm);if(JSON.stringify(r)!==JSON.stringify(ac(r)))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 i;t.gitChangedPaths!==void 0&&(i=ic(t.gitChangedPaths,"Native implementation scope authority Git paths"));let n=t.externalDrift===void 0?void 0:NS(t.externalDrift),a=gS({contractHash:t.contractHash,declaredArtifacts:r,noCodeReason:t.noCodeReason,...i===void 0?{}:{gitChangedPaths:i},...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 sc(e){let t=jr(e,"Native implementation scope bundle");$r(t,["authority","baseline","current","scope"],[],"Native implementation scope bundle");let r=vH(t.authority),i=so(t.baseline),n=so(t.current),a=co(t.scope),o=yS(i,n,r);if(JSON.stringify(a)!==JSON.stringify(o))throw new Error("Native implementation scope does not match its authoritative bundle");return{authority:r,baseline:i,current:n,scope:o}}function bS(e){let t=co(e.scope);return sc({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})}var gm,dS,rc,fS,X0,Q0,Z0,bm,zn,eH,tH,pH,Xi=A(()=>{"use strict";Xe();Fn();gm="comet.native.implementation-scope.v2",dS="comet.native.content-snapshot-projection.v1",rc="comet.native.content-snapshot-projection.v1",fS="comet.native.implementation-scope.v2",X0="comet.native.unresolved-scope-id.v1",Q0="comet.native.scope-detail-overflow.v1",Z0="comet.native.snapshot-projection-overflow.v2",bm=/^[a-f0-9]{64}$/u,zn=1024*1024,eH=128,tH=128;pH=new Set(["schema","contractHash","baselineProjectionRef","baselineProjectionHash","currentProjectionRef","currentProjectionHash","complete","declaredArtifacts","changes","unattributed","unresolvedScopes","noCodeReason","gitAdvisory","externalDrift","scopeHash"])});function Gt(e){return e.replace(gH,"$1 [REDACTED]").replace(wH,"[REDACTED PRIVATE KEY]").replace(yH,"$1[REDACTED]@").replace(NH,"[REDACTED TOKEN]").replace(bH,'$1"[REDACTED]"').replace(kH,"$1$2$1$3$4[REDACTED]$4").replace(SH,"$1$2[REDACTED]")}var gH,wH,yH,NH,bH,kH,SH,Jn=A(()=>{"use strict";gH=/\b(Bearer|Basic)\s+[^\s"']+/giu,wH=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,yH=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,NH=/\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,bH=/("(?:[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,kH=/(["'])((?:[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,SH=/\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});import kS from"node:path";function ei(e,t){if(!ES.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function PS(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native evidence source revision must be a positive integer");return e}function RS(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 Rm(e,t,r=2e3){let i=Gt(e).trim();if(i.length===0||i.length>r)throw new Error(`${t} must be between 1 and ${r} characters`);return i}function cc(e,t){let r=kS.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||kS.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized relative ref`);return e}function CH(e,t,r){let i=cc(e,t);if(/^runtime\/evidence\/check-receipts\/[a-f0-9]{64}\.json$/u.test(i))return i;let n=Sr(i),a=i.toLowerCase(),o=r?cc(r,"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"}): ${i}`);return i}function Cm(e){let t=cc(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 lo(e,t){return e<t?-1:e>t?1:0}function td(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function rd(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function CS(e,t){if(typeof e!="string")throw new Error(`${t} is invalid`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} is invalid`);return e}function SS(e,t,r){if(typeof e!="string")throw new Error(`Native ${t} evidence ref is invalid`);let i=`runtime/evidence/${t}/${r}.json`;if(e!==i)throw new Error(`Native ${t} evidence ref/hash mismatch`);return e}function xH(e){let t=td(e,"Native acceptance trace");if(rd(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"||!ES.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 r=cc(t.nativeRootRef,"Native root ref"),i=t.entries.map((o,s)=>{let c=td(o,`Native acceptance trace entry ${s}`);if(rd(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=>Cm(d)),u=c.status;if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(lo))||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:cc(c.source,`Native acceptance trace entry ${s} source`),evidenceRefs:l,skippedReason:c.skippedReason===null?null:Rm(c.skippedReason,`Native acceptance trace entry ${s} skipped reason`)}});if(JSON.stringify(i)!==JSON.stringify([...i].sort((o,s)=>lo(o.acceptanceId,s.acceptanceId)))||new Set(i.map(o=>o.acceptanceId)).size!==i.length||t.total!==i.length||t.evidenced!==i.filter(o=>o.evidenceRefs.length>0).length||t.skipped!==i.filter(o=>o.skippedReason!==null).length)throw new Error("Native acceptance trace entries are inconsistent");let n={schema:"comet.native.acceptance-trace.v2",nativeRootRef:r,criteriaHash:t.criteriaHash,total:t.total,evidenced:t.evidenced,skipped:t.skipped,entries:i},a=ei(t.traceHash,"Native acceptance trace hash");if(O(EH,n)!==a)throw new Error("Native acceptance trace content hash mismatch");return{...n,traceHash:a}}function id(e){let t=td(e,"Native partial allowance");if(rd(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(lo))||typeof t.reason!="string"||typeof t.confirmedSummary!="string")throw new Error("Native partial allowance is invalid");let r={schema:"comet.native.partial-allowance.v1",change:RS(t.change),scopeHash:ei(t.scopeHash,"Native partial allowance scopeHash"),scopeIds:t.scopeIds,reason:Rm(t.reason,"Partial allowance reason"),confirmedSummary:Rm(t.confirmedSummary,"Partial allowance confirmation"),sourceRevision:PS(t.sourceRevision),confirmedAt:CS(t.confirmedAt,"Native partial allowance timestamp")};if(r.reason!==t.reason||r.confirmedSummary!==t.confirmedSummary)throw new Error("Native partial allowance text is not canonical");let i=ei(t.allowanceHash,"Native partial allowance hash");if(O(PH,r)!==i)throw new Error("Native partial allowance content hash mismatch");return{...r,allowanceHash:i}}function lc(e){let t=td(e,"Native verification evidence");if(rd(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 r=ei(t.implementationScopeHash,"Native verification implementation scope hash"),i=xH(t.acceptanceTrace),n=ei(t.acceptanceCriteriaHash,"Native verification acceptance criteria hash");if(i.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:ei(t.partialAllowanceHash,"Native verification allowance hash"),s=t.receiptRefs.map(f=>Cm(f));if(JSON.stringify(s)!==JSON.stringify([...new Set(s)].sort(lo)))throw new Error("Native verification receipt refs must be canonical");let c=[...new Set(i.entries.flatMap(f=>f.evidenceRefs))].sort(lo);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=>Cm(f));if(JSON.stringify(l)!==JSON.stringify([...new Set(l)].sort(lo)))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:RS(t.change),sourceRevision:PS(t.sourceRevision),result:t.result,freshness:t.freshness,contractHash:ei(t.contractHash,"Native verification contract hash"),acceptanceCriteriaHash:n,implementationScopeRef:SS(t.implementationScopeRef,"scopes",r),implementationScopeHash:r,reportRef:CH(t.reportRef,"Native verification report ref"),reportHash:ei(t.reportHash,"Native verification report hash"),acceptanceTrace:i,partialAllowanceRef:o===null?null:SS(t.partialAllowanceRef,"allowances",o),partialAllowanceHash:o,requiredReceiptRefs:l,receiptRefs:s,createdAt:CS(t.createdAt,"Native verification timestamp")},d=ei(t.envelopeHash,"Native verification envelope hash");if(O(RH,u)!==d)throw new Error("Native verification evidence content hash mismatch");return{...u,envelopeHash:d}}var ES,EH,PH,RH,uc=A(()=>{"use strict";Xe();Jn();ds();Xi();ES=/^[a-f0-9]{64}$/u,EH="comet.native.acceptance-trace.v2",PH="comet.native.partial-allowance.v1",RH="comet.native.verification-evidence.v2"});import xS from"node:path";function Qi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Zi(e,t,r,i=[]){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 ti(e,t){if(typeof e!="string"||!_H.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function jt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function $S(e,t){let r=jt(e,t);if(r<1)throw new Error(`${t} must be a positive integer`);return r}function TS(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(!Number.isFinite(r.getTime())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function DH(e,t){if(typeof e!="string"||e.length===0||Buffer.byteLength(e,"utf8")>$H||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 r=xS.posix.normalize(e);if(r!==e||r==="."||r===".."||r.startsWith("../")||xS.posix.isAbsolute(r))throw new Error(`${t} must stay inside the project root`);return e}function LH(e){let t=Qi(e,"Native check receipt checker");Zi(t,["policy","version","hash","limits"],"Native check receipt checker");let r=Qi(t.limits,"Native check receipt limits");if(Zi(r,["maxFiles","maxFileBytes","maxTotalBytes","maxIssues"],"Native check receipt limits"),t.policy!==uo||t.version!==xm||t.hash!==_S||r.maxFiles!==bt.maxFiles||r.maxFileBytes!==bt.maxFileBytes||r.maxTotalBytes!==bt.maxTotalBytes||r.maxIssues!==bt.maxIssues)throw new Error("Native check receipt checker policy is unsupported");return{policy:uo,version:xm,hash:_S,limits:{...bt}}}function MH(e){let t=Qi(e,"Native check receipt contract");return Zi(t,["expectedHash","beforeHash","afterHash"],"Native check receipt contract"),{expectedHash:ti(t.expectedHash,"Native check expected contract hash"),beforeHash:ti(t.beforeHash,"Native check before contract hash"),afterHash:ti(t.afterHash,"Native check after contract hash")}}function FH(e){let t=Qi(e,"Native check receipt implementation");return Zi(t,["scopeHash","expectedSnapshotHash","beforeSnapshotHash","afterSnapshotHash"],"Native check receipt implementation"),{scopeHash:ti(t.scopeHash,"Native check scope hash"),expectedSnapshotHash:ti(t.expectedSnapshotHash,"Native check expected snapshot hash"),beforeSnapshotHash:ti(t.beforeSnapshotHash,"Native check before snapshot hash"),afterSnapshotHash:ti(t.afterSnapshotHash,"Native check after snapshot hash")}}function BH(e,t){let r=Qi(e,`Native check batch ${t}`);Zi(r,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],`Native check batch ${t}`);let i={filesSelected:jt(r.filesSelected,`Native check batch ${t} filesSelected`),filesScanned:jt(r.filesScanned,`Native check batch ${t} filesScanned`),binaryFilesSkipped:jt(r.binaryFilesSkipped,`Native check batch ${t} binaryFilesSkipped`),bytesScanned:jt(r.bytesScanned,`Native check batch ${t} bytesScanned`),issueCount:jt(r.issueCount,`Native check batch ${t} issueCount`),recordedIssueCount:jt(r.recordedIssueCount,`Native check batch ${t} recordedIssueCount`)};if(i.filesSelected>bt.maxFiles||i.filesScanned+i.binaryFilesSkipped>i.filesSelected||i.bytesScanned>bt.maxTotalBytes||i.recordedIssueCount>i.issueCount)throw new Error(`Native check batch ${t} accounting is invalid`);return i}function VH(e){let t=Qi(e,"Native check receipt counts");Zi(t,["filesSelected","filesScanned","binaryFilesSkipped","bytesScanned","issueCount","recordedIssueCount"],"Native check receipt counts",["batches"]);let r={filesSelected:jt(t.filesSelected,"Native check filesSelected"),filesScanned:jt(t.filesScanned,"Native check filesScanned"),binaryFilesSkipped:jt(t.binaryFilesSkipped,"Native check binaryFilesSkipped"),bytesScanned:jt(t.bytesScanned,"Native check bytesScanned"),issueCount:jt(t.issueCount,"Native check issueCount"),recordedIssueCount:jt(t.recordedIssueCount,"Native check recordedIssueCount"),...t.batches===void 0?{}:{batches:Array.isArray(t.batches)?t.batches.map(BH):(()=>{throw new Error("Native check receipt batches must be an array")})()}},i=r.batches;if(i!==void 0){if(i.length===0)throw new Error("Native check receipt batches must not be empty");let n=i.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({...r,batches:void 0}))throw new Error("Native check receipt batch totals are inconsistent")}if(r.filesScanned+r.binaryFilesSkipped>r.filesSelected||r.recordedIssueCount>r.issueCount||r.recordedIssueCount>bt.maxIssues||i===void 0&&(r.filesScanned+r.binaryFilesSkipped>bt.maxFiles||r.bytesScanned>bt.maxTotalBytes))throw new Error("Native check receipt count accounting is invalid");return r}function qH(e,t){return e.path.localeCompare(t.path,"en")||e.line-t.line||IS.indexOf(e.kind)-IS.indexOf(t.kind)}function WH(e){if(!Array.isArray(e)||e.length>bt.maxIssues)throw new Error("Native check receipt issues must be a bounded array");let t=e.map((i,n)=>{let a=Qi(i,`Native check issue ${n}`);if(Zi(a,["path","line","kind"],`Native check issue ${n}`),typeof a.kind!="string"||!OH.has(a.kind))throw new Error(`Native check issue ${n} kind is invalid`);return{path:DH(a.path,`Native check issue ${n} path`),line:$S(a.line,`Native check issue ${n} line`),kind:a.kind}}),r=[...t].sort(qH);if(JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt issues must be canonical");return t}function zH(e){if(!Array.isArray(e)||e.some(i=>typeof i!="string"||!HH.has(i)))throw new Error("Native check receipt stale reasons are invalid");let t=e,r=jS.filter(i=>t.includes(i));if(new Set(t).size!==t.length||JSON.stringify(r)!==JSON.stringify(t))throw new Error("Native check receipt stale reasons must be canonical");return[...t]}function JH(e){return O(jH,e)}function nd(e){let t=Qi(e,"Native check receipt");if(Zi(t,["schema","change","sourceRevision","checker","inputHash","status","startedAt","endedAt","contract","implementation","counts","issues","issuesTruncated","stale","staleReasons","receiptHash"],"Native check receipt"),t.schema!==AS)throw new Error("Native check receipt schema is invalid");if(typeof t.change!="string"||Buffer.byteLength(t.change,"utf8")>128||!IH.test(t.change))throw new Error("Native check receipt change name is invalid");let r=$S(t.sourceRevision,"Native check source revision"),i=LH(t.checker),n=MH(t.contract),a=FH(t.implementation),o=JH({change:t.change,sourceRevision:r,checkerHash:i.hash,contractHash:n.expectedHash,scopeHash:a.scopeHash,snapshotHash:a.expectedSnapshotHash});if(ti(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=TS(t.startedAt,"Native check receipt startedAt"),c=TS(t.endedAt,"Native check receipt endedAt");if(c<s)throw new Error("Native check receipt endedAt precedes startedAt");let l=VH(t.counts),u=WH(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=zH(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>bt.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>bt.maxFiles&&!u.some(p=>p.kind==="scan-limit"))throw new Error("Native check receipt exceeds its file budget without a scan-limit issue");let h={schema:AS,change:t.change,sourceRevision:r,checker:i,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},m=ti(t.receiptHash,"Native check receipt content hash");if(O(AH,h)!==m)throw new Error("Native check receipt content hash mismatch");return{...h,receiptHash:m}}var AS,AH,uo,xm,bt,_H,IH,TH,jH,$H,_S,OH,IS,jS,HH,ad=A(()=>{"use strict";Xe();AS="comet.native.check-receipt.v1",AH="comet.native.check-receipt.v1",uo="scoped-text-safety",xm=1,bt=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),_H=/^[a-f0-9]{64}$/u,IH=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,TH="comet.native.checker-policy.v1",jH="comet.native.check-input.v1",$H=2048,_S=O(TH,{policy:uo,version:xm,limits:bt,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),OH=new Set(["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"]),IS=["conflict-marker","trailing-whitespace","space-before-tab","scope-mismatch","unsafe-file","binary-skipped","scan-limit"],jS=["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"],HH=new Set(jS)});function fo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function en(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function ri(e,t){if(typeof e!="string"||!KH.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function gr(e,t){if(typeof e!="string")throw new Error(`${t} must be text`);let r=Gt(e).trim();if(!r||r.length>ZH||r!==e.trim())throw new Error(`${t} is invalid`);return r}function Am(e,t){let r=gr(e,t),i=new Date(r);if(Number.isNaN(i.getTime())||i.toISOString()!==r)throw new Error(`${t} must be a canonical timestamp`);return r}function dc(e,t,r=gr,i=!1,n=eD){if(!Array.isArray(e)||e.length>n||!i&&e.length===0)throw new Error(`${t} must be a bounded non-empty array`);let a=e.map((o,s)=>r(o,`${t} ${s}`));if(new Set(a).size!==a.length)throw new Error(`${t} has duplicates`);return a}function rD(e,t){if(typeof e!="string"||!YH.test(e))throw new Error(`${t} is invalid`);return e}function iD(e){let t=fo(e,"Native verification receipt bindings");if(en(t,["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"],"Native verification receipt bindings"),typeof t.change!="string"||!XH.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:ri(t.contractHash,"Native verification receipt contract hash"),scopeHash:ri(t.scopeHash,"Native verification receipt scope hash"),snapshotHash:ri(t.snapshotHash,"Native verification receipt snapshot hash"),artifactHash:ri(t.artifactHash,"Native verification receipt artifact hash")}}function nD(e){if(typeof e!="string")throw new Error("Native static check receipt ref is invalid");let t=QH.exec(e);if(!t)throw new Error("Native static check receipt ref is invalid");return{ref:e,hash:t[1]}}function aD(e,t,r,i){let n=fo(t,`Native ${e} evidence`);if(e==="automated-check"){if(en(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=Am(n.startedAt,"Native automated-check start time"),o=Am(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(r==="passed"&&n.exitCode!==0||r==="failed"&&n.exitCode===0||r==="passed"&&(n.timedOut||n.signal!==null))throw new Error("Native automated-check status does not match its exit code");let s=fo(n.worktree,"Native automated-check worktree");if(en(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=fo(n.afterFence,"Native automated-check after fence");if(en(c,["snapshotHash","scopeHash","matched"],"Native automated-check after fence"),typeof c.matched!="boolean")throw new Error("Native automated-check after fence is invalid");if(r==="passed"&&c.matched!==!0)throw new Error("Native automated-check pass requires a matching after fence");return{executable:gr(n.executable,"Native automated-check executable"),args:dc(n.args,"Native automated-check arguments",gr,!0),cwd:gr(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:gr(s.root,"Native automated-check worktree root"),beforeCommit:s.beforeCommit,afterCommit:s.afterCommit},afterFence:{snapshotHash:ri(c.snapshotHash,"Native automated-check after snapshot hash"),scopeHash:ri(c.scopeHash,"Native automated-check after scope hash"),matched:c.matched},outputHash:ri(n.outputHash,"Native automated-check output hash"),outputSummary:gr(n.outputSummary,"Native automated-check output summary"),outputTruncated:n.outputTruncated}}if(e==="static-inspection"){en(n,["subjects","rule","resultSummary","checkReceiptRef","checkReceiptHash"],"Native static-inspection evidence");let a=nD(n.checkReceiptRef);if(ri(n.checkReceiptHash,"Native static check receipt hash")!==a.hash)throw new Error("Native static check receipt ref/hash mismatch");return{subjects:dc(n.subjects,"Native static inspection subjects",gr,i==="required-check"),rule:gr(n.rule,"Native static inspection rule"),resultSummary:gr(n.resultSummary,"Native static inspection result"),checkReceiptRef:a.ref,checkReceiptHash:a.hash}}if(e==="manual-evidence")return en(n,["steps","observations"],"Native manual-evidence evidence"),{steps:dc(n.steps,"Native manual evidence steps"),observations:dc(n.observations,"Native manual evidence observations")};throw new Error(`Native verification receipt kind is unsupported: ${e}`)}function oD(e){let t=fo(e,"Native verification receipt");if(en(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 r=t.kind,i=t.role,n=t.status,a=gr(t.actor,"Native verification receipt actor"),o=dc(t.acceptanceIds,"Native receipt acceptance IDs",rD,i==="required-check",tD).sort();if(i==="required-check"&&o.length!==0||i==="acceptance-evidence"&&o.length===0)throw new Error("Native verification receipt role/acceptance coverage is invalid");if(i==="required-check"&&r!=="static-inspection")throw new Error("Native required check must be the built-in static inspection");let s={schema:_m,kind:r,role:i,status:n,bindings:iD(t.bindings),acceptanceIds:o,actor:a,issuedAt:Am(t.issuedAt,"Native verification receipt issue time"),evidence:aD(r,t.evidence,n,i)};if(i==="required-check"&&s.kind==="static-inspection"&&(s.evidence.rule!==uo||s.actor!==`native-runtime:${uo}`))throw new Error("Native required check policy identity is invalid");return s}function od(e){let t=fo(e,"Native verification receipt");if(en(t,["schema","kind","role","status","bindings","acceptanceIds","actor","issuedAt","evidence","receiptHash"],"Native verification receipt"),t.schema!==_m)throw new Error("Native verification receipt schema is invalid");let{receiptHash:r,...i}=t,n=oD(i),a=ri(t.receiptHash,"Native verification receipt hash");if(O(GH,n)!==a)throw new Error("Native verification receipt content hash mismatch");return{...n,receiptHash:a}}function Im(e){return O(UH,[...e].map(t=>({path:t.path,kind:t.kind})).sort((t,r)=>t.path.localeCompare(r.path)||t.kind.localeCompare(r.kind)))}var _m,GH,UH,KH,YH,XH,QH,ZH,eD,tD,ho=A(()=>{"use strict";Xe();ad();Jn();_m="comet.native.verification-receipt.v3",GH=_m,UH="comet.native.declared-artifacts.v1",KH=/^[a-f0-9]{64}$/u,YH=/^acceptance-[a-f0-9]{64}$/u,XH=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,QH=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,ZH=4096,eD=256,tD=1024});import{createHash as sD}from"node:crypto";import{promises as wr}from"node:fs";import Or from"node:path";function Tm(e,t){let r=Or.relative(e,t);return r===""||!Or.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Or.sep}`)}function cD(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function sd(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Rt(r,i)?J(r,i):J(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function OS(e){let t=await wr.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native evidence parent must be a real directory: ${e}`);return{path:e,realPath:await wr.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function lD(e,t){let r=Or.resolve(e),i=Or.resolve(t);if(!Tm(r,i))throw new Error("Native evidence path is outside its change");let n=[await OS(r)],a=r;for(let o of Or.relative(r,i).split(Or.sep).filter(Boolean)){a=Or.join(a,o);let s=await OS(a);if(!Tm(n[0].realPath,s.realPath))throw new Error(`Native evidence parent resolves outside its change: ${a}`);n.push(s)}return n}async function HS(e){for(let t of e){let r=await wr.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!cD(t,r)||await wr.realpath(t.path)!==t.realPath)throw new Error(`Native evidence parent changed while reading: ${t.path}`)}}async function uD(e,t,r={}){let i=await lD(t,Or.dirname(e));await r.afterParentChainCaptured?.();let n=await wr.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native evidence document must be a regular file");let a=await wr.realpath(e);if(!Tm(i[0].realPath,a))throw new Error("Native evidence document resolves outside its change");let o=await wr.open(e,"r");try{let[s,c,l]=await Promise.all([o.stat(),wr.lstat(e),wr.realpath(e)]);if(await HS(i),!s.isFile()||!c.isFile()||c.isSymbolicLink()||l!==a||!sd(s,n)||!sd(s,c))throw new Error("Native evidence document changed while opening");if(s.size>tn)throw new Error(`Native evidence document exceeds ${tn} bytes`);await r.afterOpen?.();let u=[],d=0,f=Buffer.allocUnsafe(64*1024);for(;;){let v=tn+1-d,g=await o.read(f,0,Math.min(f.length,v),null);if(g.bytesRead===0)break;if(d+=g.bytesRead,d>tn)throw new Error(`Native evidence document exceeds ${tn} bytes`);u.push(Buffer.from(f.subarray(0,g.bytesRead)))}await r.beforeFinalCheck?.();let[h,m,p]=await Promise.all([o.stat(),wr.lstat(e),wr.realpath(e)]);if(await HS(i),!m.isFile()||m.isSymbolicLink()||p!==a||!sd(s,h)||!sd(s,m))throw new Error("Native evidence document changed while reading");return JSON.parse(Buffer.concat(u,d).toString("utf8"))}finally{await o.close()}}function mo(e,t){if(!LS.test(t))throw new Error("Native evidence hash is invalid");return`runtime/evidence/${e}/${t}.json`}function MS(e){return mo("reports",e)}async function dD(e,t,r,i,n){if(!LS.test(r))throw new Error("Native report evidence hash is invalid");let a=await Gn({paths:e,name:t,kind:"reports",hash:r,hooks:i,changeDir:n});if(!a||typeof a!="object"||Array.isArray(a))throw new Error("Native report evidence must be an object");let o=a;if(Object.keys(o).sort().join(",")!=="content,reportHash,schema"||o.schema!=="comet.native.verification-report.v1"||o.reportHash!==r||typeof o.content!="string"||sD("sha256").update(Buffer.from(o.content,"utf8")).digest("hex")!==r)throw new Error("Native report evidence does not match its hash");return o.content}function po(e,t){let r=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts)\/([a-f0-9]{64})\.json$/u.exec(e);if(!r||r[1]!==t)throw new Error(`Native evidence ref is invalid for ${t}`);return r[2]}function fD(e,t,r,i,n){let a=mo(r,i);return n?Or.join(n,...a.split("/")):Ii(M(e,t),a)}async function Gn(e){let t=fD(e.paths,e.name,e.kind,e.hash,e.changeDir),r=e.changeDir??$(e.paths,t);return await T(r,t),uD(t,r,e.hooks)}function DS(e,t){return so(e,t)}function hD(e,t){let r=co(e);if(r.scopeHash!==t)throw new Error("Native implementation scope ref/hash mismatch");return r}function pD(e,t,r){let i=id(e);if(i.change!==t||i.allowanceHash!==r)throw new Error("Native partial allowance ref/hash/change mismatch");return i}function mD(e,t,r){let i=lc(e);if(i.change!==t||i.envelopeHash!==r)throw new Error("Native verification evidence ref/hash/change mismatch");return i}async function vD(e,t,r,i=!1,n){let a=await cd(e,t,r.implementationScopeRef,void 0,n);if(i&&await dD(e,t,r.reportHash,void 0,n),a.scopeHash!==r.implementationScopeHash||a.contractHash!==r.contractHash||(a.complete?"complete":"partial")!==r.freshness)throw new Error("Native verification evidence does not match its implementation scope");if(r.partialAllowanceRef===null)return;let o=await FS(e,t,r.partialAllowanceRef,void 0,n);if(o.allowanceHash!==r.partialAllowanceHash||o.scopeHash!==a.scopeHash||JSON.stringify(o.scopeIds)!==JSON.stringify(a.unresolvedScopes.map(s=>s.id).sort())||o.sourceRevision>=r.sourceRevision)throw new Error("Native verification evidence does not match its partial allowance")}async function fc(e,t,r,i,n){let a=po(r,"scopes"),o=hD(await Gn({paths:e,name:t,kind:"scopes",hash:a,hooks:i,changeDir:n}),a),s=po(o.baselineProjectionRef,"snapshots"),c=po(o.currentProjectionRef,"snapshots"),[l,u]=await Promise.all([Gn({paths:e,name:t,kind:"snapshots",hash:s,changeDir:n}).then(d=>DS(d,s)),Gn({paths:e,name:t,kind:"snapshots",hash:c,changeDir:n}).then(d=>DS(d,c))]);return bS({baseline:l,current:u,scope:o})}async function cd(e,t,r,i,n){return(await fc(e,t,r,i,n)).scope}async function FS(e,t,r,i,n){let a=po(r,"allowances");return pD(await Gn({paths:e,name:t,kind:"allowances",hash:a,hooks:i,changeDir:n}),t,a)}async function hc(e,t,r,i,n){let a=po(r,"receipts"),o=od(await Gn({paths:e,name:t,kind:"receipts",hash:a,hooks:i,changeDir:n}));if(o.bindings.change!==t||o.receiptHash!==a)throw new Error("Native verification receipt ref/hash/change mismatch");return o}async function vo(e,t,r,i,n){let a=po(r,"verifications"),o=mD(await Gn({paths:e,name:t,kind:"verifications",hash:a,hooks:i,changeDir:n}),t,a);return await vD(e,t,o,!1,n),o}var LS,tn,MG,ii=A(()=>{"use strict";ue();Q();ar();Xi();uc();ho();LS=/^[a-f0-9]{64}$/u,tn=zn,MG=3*tn});var BU,vd=A(()=>{"use strict";BU=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ")});var Km=A(()=>{"use strict"});import{execFileSync as iM}from"node:child_process";function UE(e,t){try{return iM("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:nM,maxBuffer:aM,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new fv(e,t,i)}}function Ce(e,t){return UE(e,t).trim()}function KE(e){let t=UE(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let r=t.split("\0").filter(Boolean),i=[];for(let n=0;n<r.length;n+=1){let a=r[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(i.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=r[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");i.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(i)].sort()}var nM,aM,fv,bc=A(()=>{"use strict";nM=3e4,aM=8*1024*1024,fv=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});import{createHash as oM}from"node:crypto";import{lstatSync as sM,readFileSync as YE,promises as cM}from"node:fs";import hv from"node:path";function XE(e){try{if(Ce(e,["ls-files","--",xd]))return!1;let t=hv.join(e,xd),r=sM(t);return!r.isFile()||r.isSymbolicLink()?!1:JSON.parse(YE(lM(e),"utf8")).hash===uM(YE(t))}catch{return!1}}function Ad(e,t=[]){return KE(e).every(r=>t.some(i=>r===i||r.startsWith(`${i}/`))||r===xd&&XE(e))}async function QE(e){XE(e)&&await cM.unlink(hv.join(e,xd))}var xd,lM,uM,pv=A(()=>{"use strict";bc();ue();xd=".comet/config.yaml",lM=e=>hv.join(e,".comet","runtime","native","workspace-config.json"),uM=e=>oM("sha256").update(e).digest("hex")});var mv=A(()=>{"use strict";vd();Km();Jn()});var kc,Sc=A(()=>{"use strict";kc="skill-coordinated"});var _d=A(()=>{"use strict";Sc()});import Id from"node:path";function ZE(...e){if(e.length===0)return Id.resolve();if(Id.win32.isAbsolute(e[0])){let t=Id.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return Id.resolve(...e)}var eP=A(()=>{"use strict"});var i4,tP=A(()=>{"use strict";vd();i4=8*1024*1024});var rP=A(()=>{"use strict";tP()});var Td,vv=A(()=>{"use strict";bc();Lt();ot();pv();Tn();Q();Td=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation}});import he from"node:path";import{promises as jd}from"node:fs";function mM(e,t){let r=he.relative(he.resolve(e),he.resolve(t));return r===""||!he.isAbsolute(r)&&!r.startsWith(`..${he.sep}`)}function vM(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 gM(e,t,r){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(r))throw new Error("Native Supervisor parent and child names are invalid");return ZE(e,".worktrees",`${t}-${r}`)}function oP(e,t){return he.join(Ye(e,t),"supervisor")}function $d(e,t){return he.join(oP(e,t),"state.json")}function sP(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!==wv)throw new Error(`Native Supervisor state schema must be ${wv}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if(dn(t.integration.targetCommit,"Native Supervisor target commit"),dn(t.integration.headCommit,"Native Supervisor integration head commit"),t.integration.checkExecution){let n=t.integration.checkExecution;if(!n.operationId||!n.key||!n.child||!["running","completed","interrupted"].includes(n.status)||!Number.isSafeInteger(n.ownerPid)||n.ownerPid<=0)throw new Error("Native Supervisor integration check execution is invalid");dn(n.candidateCommit,"Native Supervisor integration candidate commit"),dn(n.integrationCommit,"Native Supervisor integration check commit")}if(!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&dn(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(dn(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function Ot(e,t,r={}){try{let i=await jd.readFile($d(e,t),"utf8"),n=JSON.parse(i);if(sP(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativeChildrenContract:s,nativeChildrenAcceptanceValidation:c}=await Promise.resolve().then(()=>(Eo(),hP)),{readNativePortableState:l}=await Promise.resolve().then(()=>(Pr(),_p)),u=await l(he.join(o.changesDir,t,"comet-state.yaml")),d=await s({changeDir:he.join(o.changesDir,t),acceptanceIds:u.acceptance.map(({id:f})=>f),validation:c(u)});if(!d)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let f of n.children)d.contract.children.some(({name:h})=>h===f.name)&&(f.acceptanceScope=lP(d.contract,f.name),f.contractHash=O("comet.native.supervisor-contract.v1",d.contract),f.task&&(f.task.acceptance=structuredClone(f.acceptanceScope),f.task.contractHash=f.contractHash,f.task.verificationBoundary="child-scope-parent-reverifies-all",f.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=e;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(Pr(),_p)),s=await o(he.join(a.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(n.integration.targetBranch=s.workspace.change_branch)}catch(o){if(o.code!=="ENOENT")throw o}return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Xn(e,t){sP(t),await jd.mkdir(e.changesRuntimeDir,{recursive:!0}),await re($d(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function dn(e,t){if(!pM.test(e))throw new Error(`${t} must be a Git commit`)}function Ec(e){return structuredClone(e)}function yv(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function cP(e){dn(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:lP(e.contract,i.name),contractHash:O("comet.native.supervisor-contract.v1",e.contract)}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:wv,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function lP(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}async function Nv(e){let t=vM(e.parent),r=Wr(e.paths.projectRoot,t);if(!r)return null;let i=Wr(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=nr(e.paths.projectRoot).map(o=>he.resolve(o)).find(o=>ae(o).currentBranch===t);if(!n)return null;let a=cP({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return yv(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function Od(e){if(!Ad(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=Ce(e.integration.worktree,["rev-parse","--show-toplevel"]);if(he.resolve(t)!==he.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=Ce(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return Ce(e.integration.worktree,["rev-parse","HEAD"])}async function wM(e){let t=Wr(e.paths.projectRoot,e.state.integration.targetBranch);if(!t||t===e.state.integration.targetCommit)return null;let r=e.state;if(Od(r)!==r.integration.headCommit)throw new Error("Native Supervisor integration head changed before target refresh");try{Ce(r.integration.worktree,["merge","--no-edit",r.integration.targetBranch])}catch(o){throw new Error(`Native Supervisor target drift requires conflict resolution in ${r.integration.worktree}`,{cause:o})}let n=Ce(r.integration.worktree,["rev-parse","HEAD"]),a=Ec(r);return a.integration.headCommit=n,a.finalVerification={status:"pending",summary:null},yv(a,{kind:"target-refreshed",child:null,runId:null,summary:`Target ${r.integration.targetBranch} was refreshed before delivery`}),a.stateVersion+=1,await Xn(e.paths,a),a}function yM(e,t){if(dn(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=Ec(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function uP(e){let t=Od(e);if(t===e.integration.headCommit)return e;try{Ce(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let r=Ec(e);return r.integration.headCommit=t,yv(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function dP(e,t){let r=t.verification;if(r===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let i=Od(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=r.checks.length>0&&r.checks.every(({status:o})=>o==="passed");return yM(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}async function Pc(e){let r=await Ot(e.paths,e.state.parent)??e.state;if(r.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before delivery; reload status first");if(r.finalVerification.status!=="passed")throw new Error("Native Supervisor delivery requires a passed final verification");if(!r.children.every(({status:p})=>p==="integrated"||p==="archived"))throw new Error("Native Supervisor delivery requires every child to be integrated");let n=nr(e.paths.projectRoot).map(p=>he.resolve(p)).find(p=>ae(p).currentBranch===r.integration.targetBranch);if(!n)throw new Error(`Native Supervisor target branch worktree is unavailable: ${r.integration.targetBranch}`);let a=he.resolve(n)===he.resolve(e.paths.projectRoot)?[he.relative(n,he.join(e.paths.changesDir,r.parent)).replaceAll("\\","/"),".comet/current-change.json",...e.archiveOwnedPaths??[]]:[];if(!Ad(n,a))throw new Error(`Native Supervisor target worktree is not clean: ${n}`);let o=Ce(n,["rev-parse","HEAD"]);if((()=>{try{return Ce(n,["merge-base","--is-ancestor",r.integration.headCommit,o]),!0}catch{return!1}})()){let p=await nP({paths:e.paths,state:r,targetCommit:o});if(await aP({paths:e.paths,plan:p,targetRoot:n}),r.children.every(({status:g})=>g==="archived"))return await gv(e.paths,r.parent),{state:r,targetRoot:n,targetCommit:o};let v=Ec(r);for(let g of v.children)g.status="archived";return v.stateVersion+=1,await Xn(e.paths,v),await gv(e.paths,r.parent),{state:v,targetRoot:n,targetCommit:o}}let l=Od(r);if(l!==r.integration.headCommit)throw new Error("Native Supervisor integration head changed after final verification");let u=Wr(e.paths.projectRoot,r.integration.targetBranch),d=(()=>{if(!u)return!1;try{return Ce(r.integration.worktree,["merge-base","--is-ancestor",u,l]),!0}catch{return!1}})();if(u!==l&&!d&&u!==r.integration.targetCommit&&await wM({paths:e.paths,state:r}))throw new Error("Native Supervisor target changed; parent integration checks must be rerun before delivery");let f=await nP({paths:e.paths,state:r,targetCommit:l});u!==l&&Ce(n,["merge","--ff-only",r.integration.branch]);let h=Ce(n,["rev-parse","HEAD"]);if(h!==l)throw new Error("Native Supervisor target did not receive the verified integration head");let m=Ec(r);for(let p of m.children)p.status="archived";return await aP({paths:e.paths,plan:f,targetRoot:n}),m.stateVersion+=1,await Xn(e.paths,m),await gv(e.paths,r.parent),{state:m,targetRoot:n,targetCommit:h}}function fP(e,t){return he.join(oP(e,t),"cleanup.json")}function iP(e){let t=nr(e.paths.projectRoot).map(s=>he.resolve(s)),r=he.resolve(process.cwd()),i=[{root:e.state.integration.worktree,branch:e.state.integration.branch},...e.state.children.map(({name:s,projectRoot:c,task:l})=>({root:c??l?.projectRoot??gM(ae(e.paths.projectRoot).primaryWorktreeRoot??e.paths.projectRoot,e.state.parent,s),branch:`comet/supervisor/${e.state.parent}/${s}`}))].map(s=>({...s,root:he.resolve(s.root)})),n=e.targetCommit,a=[e.state.integration.branch,...e.state.children.map(({name:s})=>`comet/supervisor/${e.state.parent}/${s}`)],o=i.flatMap(s=>{let c=t.find(l=>l===s.root);return c?[{...s,root:c}]:[]});for(let s of o){if(mM(s.root,r))throw new Error(`Native Supervisor cannot clean the current worktree: ${s.root}`);if(!Ad(s.root))throw new Error(`Native Supervisor cleanup requires a clean worktree: ${s.root}`);let c=ae(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{Ce(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(us(e.paths.projectRoot,s))try{Ce(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 nP(e){let t=fP(e.paths,e.state.parent);try{let i=JSON.parse(await jd.readFile(t,"utf8"));if(i.parent===e.state.parent&&i.targetCommit===e.targetCommit&&Array.isArray(i.worktrees)&&i.expectedBranches&&typeof i.expectedBranches=="object"&&Array.isArray(i.branches)){let n=iP(e);return{parent:i.parent,targetCommit:i.targetCommit,worktrees:[...new Set([...i.worktrees,...n.worktrees])],expectedBranches:{...i.expectedBranches,...n.expectedBranches},branches:[...new Set([...i.branches,...n.branches])]}}}catch(i){if(i.code!=="ENOENT")throw i}let r=iP(e);return await re(t,r,{containedRoot:e.paths.changesRuntimeDir}),r}async function aP(e){for(let t of e.plan.worktrees){if(!nr(e.paths.projectRoot).map(a=>he.resolve(a)).includes(he.resolve(t)))continue;let i=e.plan.expectedBranches[t];if(!i)throw new Error(`Native Supervisor cleanup has no expected branch for ${t}`);let n=ae(t).currentBranch;if(n!==i)throw new Error(`Native Supervisor cleanup found unexpected branch ${n??"(detached)"} for ${t}; expected ${i}`);await QE(t),Ce(e.paths.projectRoot,["worktree","remove",t])}for(let t of e.plan.branches)us(e.paths.projectRoot,t)&&Ce(e.targetRoot,["branch","-d",t])}async function gv(e,t){await jd.rm(fP(e,t),{force:!0})}function bv(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:i.status==="ready"&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing"}));return{contractHash:null,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var wv,pM,So=A(()=>{"use strict";pv();ue();Xe();mv();_d();et();Q();ot();Lt();eP();bc();rP();vv();wv="comet.native.supervisor.v2",pM=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u});var hP={};cg(hP,{NATIVE_CHILDREN_FILE:()=>kv,NATIVE_CHILDREN_SCHEMA:()=>Qn,NATIVE_CHILDREN_SCHEMA_V2:()=>Rv,NATIVE_CHILDREN_V2_SCHEMA:()=>Zn,findNativeV1SupervisorParents:()=>EP,hasNativeSupervisorShapeIntent:()=>kP,hashNativeParentContract:()=>Md,inspectNativeChildren:()=>ta,nativeChildrenAcceptanceValidation:()=>Ld,nativeChildrenIndexDrift:()=>NP,parseNativeChildrenContract:()=>bP,readNativeChildrenContract:()=>ea,readNativeSupervisorShapeIntent:()=>Cv});import{promises as Ev}from"node:fs";import St from"node:path";function Dd(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Hd(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function mP(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function Sv(e,t){let r=St.normalize(St.resolve(e)),i=St.normalize(St.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function PM(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function vP(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function NP(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===Rv&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let u=s.get(l),d=e.acceptance_index[l];u&&d&&(d.source!==u.source||d.text!==u.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(u=>!c.has(u)));return i.uncovered=o.filter(l=>!gP(e.children,l)),wP(i)?i:null}if(e.schema===Qn&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!gP(e.children,a)),wP(i)?i:null}return null}function gP(e,t){return e.some(r=>r.covers.includes(t))}function wP(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Ld(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function RM(e){let t=Dd(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=Dd(n,`Native children acceptance_index.${i}`);if(Hd(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function CM(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let u=c.get(l);if(!u)continue;let d=e[l];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(h=>d[h]!==u[h]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function bP(e,t,r={}){let i=(0,Pv.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Dd(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Qn&&a!==Zn)throw Hd(n,pP,"Native children contract"),new Error(`Native children schema must be ${Qn} or ${Zn}`);let o=a===Qn?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Hd(n,o==="indexed-v2"?bM:pP,"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 m=Dd(f,`Native child ${h}`);if(Hd(m,o==="indexed-v2"?EM:o==="summary-v2"?SM:kM,`Native ${s} child fields (child ${h})`),typeof m.name!="string"||!NM.test(m.name))throw new Error(`Native child ${h} name is invalid`);let p=o==="summary-v2";if(p){if(typeof m.summary!="string"||m.summary.trim().length===0)throw new Error(`Native child ${m.name} summary must be a non-empty string`);if(m.summary.length>2e3)throw new Error(`Native child ${m.name} summary exceeds 2000 characters`)}return{name:m.name,summary:p?m.summary:null,depends_on:mP(m.depends_on,`Native child ${m.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?mP(m.covers,`Native child ${m.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(m=>!u.has(m));if(h.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${h.join(", ")}`)}PM(c);let d=r.policy==="advisory";if(a===Rv){if(o==="indexed-v2"){let f=RM(n.acceptance_index);d||CM(f,t,r);let h=Object.keys(f);return d||vP(c,h,h),{schema:Zn,acceptance_index:f,children:c}}return{schema:Zn,children:c}}return t&&!d&&vP(c,t),{schema:Qn,children:c}}async function ea(e){let t=St.join(e.changeDir,kv);try{await Ev.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await te({root:e.changeDir,ref:kv}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=bP(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?NP(a,e.acceptanceIds,e.validation??{}):null}}function xM(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function kP(e){let t=xM(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function Cv(e){try{let t=await te({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return kP(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Md(e){return O("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function SP(e){let t=nr(e.projectRoot);t.some(i=>Sv(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>St.resolve(n)))]){let n=await Ee(i);n&&r.push({projectRoot:i,paths:await Ke(i,n.native.artifact_root),parent:Sv(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function EP(e){let t=await SP(e.paths),r=[],i=[],n=new Map;for(let a of t){let o;try{o=await Ev.readdir(a.paths.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o){if(!s.isDirectory()||s.isSymbolicLink()||s.name===e.childName)continue;let c=St.join(a.paths.changesDir,s.name),l;try{l=await Be(St.join(c,"comet-state.yaml"))}catch{continue}if(l.phase!=="build"||l.status!=="active")continue;let u=await ea({changeDir:c,...l.acceptance.length>0?{acceptanceIds:l.acceptance.map(({id:d})=>d)}:{}});!u||u.contract.schema!==Qn||u.contract.children.some(({name:d})=>d===e.childName)&&n.set(l.name,[...n.get(l.name)??[],{source:a,state:l}])}}for(let[a,o]of n){let s=e.targetBranch===null?[]:o.filter(({state:h})=>h.workspace.target_branch===e.targetBranch);if(e.targetBranch===null){i.push(`Native Supervisor Child ${e.childName} has no target branch to match parent ${a}`);continue}let c=s.find(({source:h,state:m})=>ae(h.projectRoot).currentBranch===m.workspace.change_branch);if(!c){let h=o.find(({state:m})=>m.workspace.target_branch!==e.targetBranch);if(h)i.push(`Native Supervisor parent ${a} targets ${h.state.workspace.target_branch??"(missing)"}, not ${e.targetBranch}`);else{let m=s[0]?.state??o[0].state;i.push(`Native Supervisor parent ${a} is not bound to branch ${m.workspace.change_branch}`)}continue}let{source:l,state:u}=c,d=l.paths,f=await ta({paths:d,state:u});if(!f)i.push(`Native Supervisor parent ${a} has no readable Child inspection`);else if(!f.confirmed)i.push(`Native Supervisor parent ${a} requires Shape confirmation`);else if(f.allDone)r.push({paths:d,state:u,inspection:f});else{let h=f.children.filter(({status:m})=>m!=="done").map(({name:m,status:p,message:v})=>`${m}=${p}${v?` (${v})`:""}`).join(", ");i.push(`Native Supervisor parent ${a} is not ready to advance: ${h||"Child facts are incomplete"}`)}}return n.size===0&&i.push(`Native Supervisor Child ${e.childName} has no active v1 parent declaring it`),n.size>1&&i.push(`Native Supervisor Child ${e.childName} has multiple active parents: ${[...n.keys()].join(", ")}`),r.length===1&&i.length===0?{candidate:r[0],blockers:i}:(r.length>1&&i.push(`Native Supervisor Child ${e.childName} has multiple eligible parents: ${r.map(({state:a})=>a.name).join(", ")}`),{candidate:null,blockers:i})}async function AM(e,t){let r=St.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Be(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function _M(e,t){let r;try{r=await Ev.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=St.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Be(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function IM(e,t,r){let i=St.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${St.sep}`))return null;let n=i.split(St.sep).join("/");try{let a=(0,Pv.parseDocument)(Ce(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:Qe(a.toJS({mapAsMap:!1}))}catch{return null}}function TM(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function yP(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function ta(e){let t=St.join(e.paths.changesDir,e.state.name),r=await Cv(t),i=null,n;try{n=await ea({changeDir:t,validation:Ld(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:g})=>g)}:{},policy:"advisory"})}catch(g){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${g.message}`,n=null}if(!n){let g=await Ot(e.paths,e.state.name,{diagnostics:!0});if(g){let N=bv(g);return{...N,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:N.children.map(E=>({...E,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=Md({acceptance:e.state.acceptance,children:n.contract}),o=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&e.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===Zn){let g=await Ot(e.paths,e.state.name,{diagnostics:!0});if(!g){let w=e.state.workspace.change_branch??e.state.workspace.target_branch;if(w){let S=await Nv({paths:e.paths,parent:e.state.name,targetBranch:w,contract:n.contract});S&&(g=S,await Xn(e.paths,S))}}if(g){let w=bv(g);return e.state.children_contract_hash!==a||n.drift?{...w,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(S=>({...S,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...w,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&w.confirmed}}let N=new Map(n.contract.children.map(w=>[w.name,w])),E=n.contract.children.map(w=>({name:w.name,summary:w.summary,dependsOn:[...w.depends_on],covers:[],status:s&&w.depends_on.every(S=>n.contract.children.filter(({name:k})=>k!==w.name).every(({name:k})=>k!==S))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let w of E){if(w.status!=="ready")continue;N.get(w.name).depends_on.length>0&&(w.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:E,readyChildren:E.filter(({status:w})=>w==="ready").map(({name:w})=>w),allDone:!1}}let c=await SP(e.paths),l=new Set(n.contract.children.map(({name:g})=>g)),u=new Map,d=new Map;for(let g of c){let N=g.parent&&o?`refs/heads/${o}`:"HEAD";for(let E of await _M(g,l)){let w={...E,source:g,committedState:IM(g,E.file,N)};u.set(E.state.name,[...u.get(E.state.name)??[],w])}for(let E of l){let w=await AM(g,E);w&&d.set(E,[...d.get(E)??[],{source:g,state:w}])}}let f=new Map;for(let g of n.contract.children){let N=(u.get(g.name)??[]).find(({source:S,committedState:k})=>S.parent&&k?.name===g.name&&yP(k,o));if(N){f.set(g.name,{kind:"done",phase:N.state.phase,projectRoot:N.source.projectRoot,message:null});continue}let E=u.get(g.name)?.[0];if(E){f.set(g.name,{kind:"blocked",phase:E.state.phase,projectRoot:E.source.projectRoot,message:`Native child ${g.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let w=d.get(g.name)??[];w.length>1?f.set(g.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${g.name} has multiple active workspace owners`}):w[0]&&f.set(g.name,TM(w[0].state,w[0].source,o))}let h=new Map(n.contract.children.map(g=>[g.name,g])),m=new Map,p=g=>{let N=m.get(g);if(N)return N;let E=h.get(g),S=E.depends_on.map(p).every(({status:L})=>L==="done"),k=f.get(g),R=k?.kind==="active"&&S?E.depends_on.filter(L=>!(u.get(L)??[]).some(({source:H,committedState:je})=>Sv(H.projectRoot,k.projectRoot)&&je?.name===L&&yP(je,o))):[],b,y=k?.message??null;k?.kind==="done"?(b=S?"done":"blocked",S||(y=`Native child ${g} was merged before its dependencies`)):k?.kind==="active"?(b=S&&R.length===0?"active":"blocked",S?R.length>0&&(y=`Native child ${g} does not include merged dependencies: ${R.join(", ")}`):y=`Native child ${g} started before its dependencies merged`):k?.kind==="blocked"?b="blocked":(b=s&&S?"ready":"pending",s||(y="Parent Shape confirmation is required"));let P={name:g,summary:E.summary,dependsOn:[...E.depends_on],covers:[...E.covers],status:b,phase:k?.phase??null,projectRoot:k?.projectRoot??null,message:y};return m.set(g,P),P},v=n.contract.children.map(({name:g})=>p(g));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:v,readyChildren:v.filter(({status:g})=>g==="ready").map(({name:g})=>g),allDone:v.every(({status:g})=>g==="done")}}var Pv,kv,Qn,Zn,Rv,NM,pP,bM,kM,SM,EM,Eo=A(()=>{"use strict";Pv=da(Cn(),1);Lt();bc();Ft();Xe();ot();Q();Pr();So();kv="children.yaml",Qn="comet.native.children.v1",Zn="comet.native.children.v2",Rv=Zn,NM=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,pP=new Set(["schema","children"]),bM=new Set(["schema","acceptance_index","children"]),kM=new Set(["name","depends_on","covers"]),SM=new Set(["name","summary","depends_on"]),EM=new Set(["name","depends_on","covers"])});import{promises as nC}from"node:fs";import mf from"node:path";import{promises as cf}from"fs";import Me from"path";import{promises as OP}from"fs";import Po from"path";import{isDeepStrictEqual as XM}from"util";import{createHash as hC}from"crypto";function lg(e,t,r,i){return t.iteration>=r.maxIterations?{allowed:!1,reason:`Iteration budget exhausted: ${r.maxIterations}`}:e.type==="invoke_skill"&&!r.allowedSkills.includes(e.ref??"")?{allowed:!1,reason:`Skill is not allowed: ${e.ref??"(missing)"}`}:e.type==="call_tool"&&!r.allowedTools.includes(e.ref??"")?{allowed:!1,reason:`Tool is not allowed: ${e.ref??"(missing)"}`}:e.type==="handoff"&&!r.allowedAgents.includes(e.ref??"")?{allowed:!1,reason:`Agent is not allowed: ${e.ref??"(missing)"}`}:e.ref&&r.confirmationRequiredFor.includes(e.ref)&&!i.has(e.ref)?{allowed:!1,reason:`User confirmation required for: ${e.ref}`}:(t.retries[e.id]??0)>r.maxRetriesPerAction?{allowed:!1,reason:`Retry budget exhausted for action: ${e.id}`}:{allowed:!0}}function ug(e){if(e===null||typeof e!="object"||Object.isFrozen(e))return e;for(let t of Reflect.ownKeys(e))ug(e[t]);return Object.freeze(e)}function hi(e){return ug(structuredClone(e))}function wf(e,t,r,i){return e.resolveStep({pkg:hi(t),state:hi(r),context:hi(i)})}function dg(e,t,r,i,n,a){return e.resolveNext({pkg:hi(t),state:hi(r),step:hi(i),outcome:hi(n),context:hi(a)})}function pC(e,t,r){return hC("sha256").update(`${e}:${t}:${r??"adaptive"}`).digest("hex").slice(0,16)}function yf(e,t){return e.definition.orchestration.steps?.find(r=>r.id===t)}function fg(e,t,r,i,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=wf(i,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=yf(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:pC(s.runId,s.iteration,o.id),stepId:o.id};return mC(e,s,c,r)}function mC(e,t,r,i){let n=lg(r,t,e.guardrails,i);return n.allowed?{state:{...t,pending:r.id,status:"waiting"},action:r}:{state:t,action:null,reason:n.reason}}function hg(e,t,r,i,n){if(!t.pending||t.pending!==r.actionId)throw new Error(`Outcome does not match pending action: ${r.actionId}`);let a=t.orchestration==="deterministic"?wf(i,e,t,n):void 0,o=a?yf(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(r.status==="failed"){let c={...t.retries,[r.actionId]:(t.retries[r.actionId]??0)+1};return{...t,pending:null,status:"running",retries:c}}let s=t.orchestration==="deterministic"?dg(i,e,t,o,r,n):t.currentStep;if(s!==null&&t.orchestration==="deterministic"&&!yf(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"}}Nn();ke();Ft();pr();Q();import{promises as um}from"fs";import qk from"path";var Wk=["outcome","scope","nonGoals","acceptanceExamples"],g0=[...Wk,"constraints","decisions","openQuestions","verificationExpectations"],w0=["acceptanceEvidence","commandsAndResults","skippedChecks","specConsistency","knownLimitationsAndRisks","conclusion"],zk={maxFileBytes:hs};function Jk(e){let t=new Map,r=null,i=[],n=()=>{r!==null&&t.set(r,i.join(`
|
|
203
|
+
`).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),r=o[1].trim(),i=[]):r!==null&&i.push(a)}return n(),t}async function y0(e,t){let r=qk.resolve(e,...t.split(/[\\/]/u));if(!D(e,r))throw new Error(`Artifact escapes Native change: ${t}`);let i=await um.realpath(e),n=await um.realpath(r);if(!D(i,n))throw new Error(`Artifact symlink escapes Native change: ${t}`);if(!(await um.stat(n)).isFile())throw new Error(`Artifact is not a file: ${t}`);return n}function tc(e){return{valid:e.length===0,findings:e}}function dm(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r=null;for(let i of e.split(/\r?\n/u)){let n=i.match(/^\s*(`{3,}|~{3,})/u);if(n){let s=n[1]?.[0];r===null?r=s:r===s&&(r=null);continue}if(r!==null)continue;let a=i.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(a)||a.includes("|")&&a.split("|").some(s=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(s)))return!0;let o=a.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let s=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(s)||/[./_-]/u.test(s))return!0}}return!1}async function fm(e,t){let r=[],i;try{i=(await te({root:e,ref:t,maxBytes:zk.maxFileBytes})).text}catch(a){return tc([{code:"brief-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of Jk(i))n.set(Wc(a)??a,o);for(let a of g0)n.has(a)||r.push({code:"brief-section-missing",message:`Missing brief section: ${a}`,path:t});for(let a of Wk)(n.get(a)??"").length===0&&r.push({code:"brief-section-empty",message:`Brief section is empty: ${a}`,path:t});return dm(i)&&r.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),tc(r)}async function hm(e,t){let r=[],i;try{i=(await te({root:e,ref:t,maxBytes:zk.maxFileBytes})).text}catch(a){return tc([{code:"verification-missing",message:a.message,path:t}])}let n=new Map;for(let[a,o]of Jk(i))n.set(gg(a)??a,o);for(let a of w0)n.has(a)?(n.get(a)??"").length===0&&r.push({code:"verification-section-empty",message:`Verification section is empty: ${a}`,path:t}):r.push({code:"verification-section-missing",message:`Missing verification section: ${a}`,path:t});return tc(r)}function Zu(e,t){return qk.join(e.specsDir,t,"spec.md")}async function Gk(e,t){let r=[],i=se(e,t.name);for(let n of t.spec_changes){let a=Zu(e,n.capability),o=null;try{await T(e.nativeRoot,a),o=await hr(a)}catch(s){if(s.code!=="ENOENT"){r.push({code:"spec-canonical-unsafe",message:s.message,path:a});continue}}if(n.operation==="create"&&o!==null&&r.push({code:"spec-create-exists",message:`Canonical spec already exists: ${n.capability}`,path:a}),n.operation!=="create"&&o===null&&r.push({code:"spec-base-missing",message:`Canonical spec is missing: ${n.capability}`,path:a}),n.operation!=="create"&&o!==null&&o!==n.base_hash&&r.push({code:"spec-base-conflict",message:`Canonical spec changed for ${n.capability}: expected ${n.base_hash}, actual ${o}`,path:a}),n.source)try{await y0(i,n.source)}catch(s){r.push({code:"spec-source-invalid",message:s.message,path:n.source})}}return tc(r)}Ui();import{promises as RL}from"node:fs";import _E from"node:path";Xe();import Uk from"node:path";var N0="comet.native.archive-preflight.v1",b0="comet.native.archive-preflight.v1",k0="comet.native.archive-operation.v1",S0=/^[a-f0-9]{64}$/u,Kk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,E0=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function ed(e,t){return e<t?-1:e>t?1:0}function P0(e,t){if(typeof e!="string"||!S0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function Qr(e,t){return e===null?null:P0(e,t)}function R0(e,t){let r=Uk.posix.normalize(e);if(typeof e!="string"||e.length===0||e!==e.trim()||e.includes("\\")||Uk.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized Native-relative ref`);return e}function C0(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native archive preflight revision must be a positive integer");return e}function x0(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,r]of[["change",e.changeBranch],["target",e.targetBranch]])if(r!==null&&(r.length===0||r.trim()!==r||Array.from(r).some(i=>{let n=i.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 A0(e,t){if(!Kk.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 r=Qr(e.expectedBaseHash,`Native archive spec ${e.capability} expected base`),i=Qr(e.actualBaseHash,`Native archive spec ${e.capability} actual base`),n=Qr(e.proposedHash,`Native archive spec ${e.capability} proposed content`);if(e.operation==="create"&&r!==null)throw new Error(`Native archive create ${e.capability} must expect no canonical base`);if(e.operation!=="create"&&r===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:r,actualBaseHash:i,proposedHash:n}}function _0(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:Qr(e.contractHash,"Native archive contract hash"),acceptanceHash:Qr(e.acceptanceHash,"Native archive acceptance hash"),implementationScopeHash:Qr(e.implementationScopeHash,"Native archive implementation scope hash"),reportHash:Qr(e.reportHash,"Native archive report hash"),envelopeHash:Qr(e.envelopeHash,"Native archive envelope hash"),partialAllowanceHash:Qr(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(r=>r===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 I0(e){if(e.length>64)throw new Error("Native archive preflight has too many findings");let t=e.map(i=>{if(typeof i!="string"||!E0.test(i))throw new Error(`Native archive preflight finding code is invalid: ${String(i)}`);return i}),r=[...new Set(t)].sort(ed);if(r.length!==t.length)throw new Error("Native archive preflight has duplicate finding codes");return r}function T0(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 r of e.specs)r.actualBaseHash!==r.expectedBaseHash&&t.push("spec-base-conflict");return[...new Set(t)].sort(ed)}function Yk(e){if(!Kk.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(A0).sort((l,u)=>ed(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 r=t.map(l=>({...l,operationHash:O(k0,l)})),i=_0(e.evidence),n=x0(e.workspace),a=[...new Set([...I0(e.findingCodes??[]),...T0({phase:e.phase,archived:e.archived,pendingJournal:e.pendingJournal,targetExists:e.targetExists,specs:t,evidence:i})])].sort(ed),o=C0(e.revision),s=R0(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:r,evidence:i,workspace:n,findingCodes:a};return{schema:N0,change:e.change,archiveConfirmation:e.archiveConfirmation,revision:o,targetRef:s,ready:a.length===0,evidenceFreshness:i.freshness,operationCount:r.length,operations:r,workspace:n,findingCodes:a,preflightHash:O(b0,c)}}Ft();ke();Xe();import{createHash as j0}from"node:crypto";import Xk from"node:path";var $0="comet.native.conflict-radar.v1",Nt=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}),O0="comet.native.conflict-radar.v1",H0="comet.native.conflict-radar-signals.v1",D0=/^[a-f0-9]{64}$/u,eS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,L0=new Set(["name","revision","specs","declaredArtifacts","workspaceIdentityHash"]),M0=new Set(["capability","operation","baseHash"]),F0=new Set(["path","kind"]);function ao(e,t){return e<t?-1:e>t?1:0}function pm(e){return Buffer.byteLength(e,"utf8")}function mm(e,t,r){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${r} must be an object`);let i=e,n=Object.keys(i).filter(a=>!t.has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return i}function vm(e,t,r){if(typeof e!="string"||e.length===0||e!==e.trim())throw new Error(`${t} must be a non-empty trimmed string`);if(pm(e)>r)throw new Error(`${t} exceeds its byte budget`);return e}function B0(e,t){let r=vm(e,t,Nt.maxArtifactPathBytes),i=Xk.posix.normalize(r);if(r.includes("\\")||Array.from(r).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||/^(?:[A-Za-z]:|~)/u.test(r)||Xk.posix.isAbsolute(i)||r.split("/").includes("..")||i!==r||i==="."||r.endsWith("/"))throw new Error(`${t} must be a normalized project-relative path`);return r}function tS(e,t){if(typeof e!="string"||!D0.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function V0(e,t){let r=mm(e,M0,t),i=vm(r.capability,`${t} capability`,Nt.maxCapabilityBytes);if(!eS.test(i))throw new Error(`${t} capability is invalid`);if(r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`${t} operation is invalid`);let n=r.baseHash===null?null:tS(r.baseHash,`${t} canonical base hash`);if(r.operation==="create"&&n!==null)throw new Error(`${t} create operation requires a null canonical base hash`);if(r.operation!=="create"&&n===null)throw new Error(`${t} ${r.operation} operation requires a canonical base hash`);return{capability:i,operation:r.operation,baseHash:n}}function q0(e,t){let r=mm(e,F0,t);if(r.kind!=="file"&&r.kind!=="directory")throw new Error(`${t} kind is invalid`);return{path:B0(r.path,`${t} path`),kind:r.kind}}function W0(e,t){let r=mm(e,L0,`Conflict radar change ${t}`),i=vm(r.name,`Conflict radar change ${t} name`,Nt.maxNameBytes);if(!eS.test(i))throw new Error(`Conflict radar change ${t} name is invalid`);if(!Number.isSafeInteger(r.revision)||r.revision<1)throw new Error(`Conflict radar change ${i} revision must be a positive safe integer`);if(!Array.isArray(r.specs))throw new Error(`Conflict radar change ${i} specs must be an array`);if(r.specs.length>Nt.maxSpecsPerChange)throw new Error(`Conflict radar change ${i} exceeds the spec budget`);if(!Array.isArray(r.declaredArtifacts))throw new Error(`Conflict radar change ${i} declared artifacts must be an array`);if(r.declaredArtifacts.length>Nt.maxArtifactsPerChange)throw new Error(`Conflict radar change ${i} exceeds the declared artifact budget`);let n=r.specs.map((c,l)=>V0(c,`Conflict radar change ${i} spec ${l}`)).sort((c,l)=>ao(c.capability,l.capability));if(new Set(n.map(c=>c.capability)).size!==n.length)throw new Error(`Conflict radar change ${i} has duplicate capabilities`);let a=r.declaredArtifacts.map((c,l)=>q0(c,`Conflict radar change ${i} artifact ${l}`)).sort((c,l)=>ao(c.path,l.path)||ao(c.kind,l.kind)),o=a.map(c=>c.path);if(new Set(o).size!==o.length)throw new Error(`Conflict radar change ${i} has duplicate or conflicting artifact paths`);let s=r.workspaceIdentityHash===void 0||r.workspaceIdentityHash===null?null:tS(r.workspaceIdentityHash,`Conflict radar change ${i} workspace identity hash`);return{name:i,revision:r.revision,specs:n,declaredArtifacts:a,workspaceIdentityHash:s}}function z0(e){if(!Array.isArray(e))throw new Error("Native conflict radar input must be an array");if(e.length>Nt.maxChanges)throw new Error("Native conflict radar exceeds the change budget");let t=e.map(W0).sort((n,a)=>ao(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)>Nt.maxTotalSpecs)throw new Error("Native conflict radar exceeds the total spec budget");if(t.reduce((n,a)=>n+a.declaredArtifacts.length,0)>Nt.maxTotalArtifacts)throw new Error("Native conflict radar exceeds the total declared artifact budget");return t}function J0(e,t){let r=e.baseHash!==null&&e.baseHash===t.baseHash;return{kind:"capability",certainty:e.operation==="create"||t.operation==="create"||r?"definite-conflict":"possible-overlap",capability:e.capability,leftOperation:e.operation,rightOperation:t.operation,leftBaseHash:e.baseHash,rightBaseHash:t.baseHash}}function G0(e,t){let r=e.kind==="directory"&&(t.path===e.path||t.path.startsWith(`${e.path}/`)),i=t.kind==="directory"&&(e.path===t.path||e.path.startsWith(`${t.path}/`)),n=e.kind==="file"&&t.kind==="file"&&e.path===t.path;return!r&&!i&&!n?null:{kind:"artifact",certainty:n?"definite-conflict":"possible-overlap",leftArtifact:e,rightArtifact:t}}function U0(e,t){return e.workspaceIdentityHash===null||t.workspaceIdentityHash===null?"unknown":e.workspaceIdentityHash===t.workspaceIdentityHash?"same":"different"}function K0(e,t){let r=[],i=j0("sha256").update(`${H0}
|
|
204
|
+
[`),n=0,a=!1,o=l=>{n>0&&i.update(","),i.update(Ps(l)),n+=1,l.certainty==="definite-conflict"&&(a=!0),r.length<Nt.maxSignalsPerRelationship&&r.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(J0(l,u))}for(let l of e.declaredArtifacts)for(let u of t.declaredArtifacts){let d=G0(l,u);d&&o(d)}let c=a?"definite-conflict":n>0?"possible-overlap":"disjoint";return i.update("]"),{left:e.name,right:t.name,classification:c,workspaceRelationship:U0(e,t),signalCount:n,signalHash:i.digest("hex"),signals:r,signalsTruncated:r.length!==n}}function Qk(e){return e==="definite-conflict"?0:e==="possible-overlap"?1:2}function Y0(e,t){return Qk(e.classification)-Qk(t.classification)||ao(e.left,t.left)||ao(e.right,t.right)}function Zk(e,t,r,i){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:$0,workspaceIdentityAdvisoryOnly:!0,changeCount:e.length,relationshipCount:t.length,counts:n,relationships:r,relationshipsTruncated:r.length!==t.length,omittedRelationshipCount:t.length-r.length,radarHash:i}}function rS(e){let t=z0(e),r=[];for(let s=0;s<t.length;s+=1)for(let c=s+1;c<t.length;c+=1)r.push(K0(t[s],t[c]));r.sort(Y0);let i=r.map(s=>({left:s.left,right:s.right,classification:s.classification,workspaceRelationship:s.workspaceRelationship,signalCount:s.signalCount,signalHash:s.signalHash})),n=O(O0,{changes:t,relationships:i}),a=r.slice(0,Nt.maxRelationships).map(s=>({...s,signals:[...s.signals]})),o=Zk(t,r,a,n);for(;a.length>0&&pm(JSON.stringify(o))>Nt.maxSerializedBytes;)a=a.slice(0,-1),o=Zk(t,r,a,n);if(pm(JSON.stringify(o))>Nt.maxSerializedBytes)throw new Error("Native conflict radar summary exceeds its serialized output budget");return o}ii();yt();_r();var gD=4096;async function wD(e,t=Nt.maxChanges){try{let r=await xt({root:e.nativeRoot,directory:e.changesDir,label:"Native conflict changes directory",maxEntries:t});return await r.verify(),r.entries}catch(r){if(r.code==="ENOENT")return[];throw r}}async function BS(e,t){let r=await We(e,t),[i,n]=await Promise.all([r.implementation_scope?cd(e,t,r.implementation_scope):null,Tt(e,t).catch(()=>null)]);return{name:r.name,revision:r.revision,specs:r.spec_changes.map(a=>({capability:a.capability,operation:a.operation,baseHash:a.base_hash})),declaredArtifacts:i?.declaredArtifacts??[],workspaceIdentityHash:n?.nativeRootId??null}}async function ld(e,t,r={}){let n=(await wD(e,gD)).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 BS(e,t),o=0,s=0;for(let c of n){if(c===t)continue;let l=await BS(e,c).catch(d=>{if(r.tolerateInvalidSiblings)return null;throw d});if(!l)continue;let u=rS([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"]:[]]}}ke();ot();Q();Ya();ue();ke();pr();Tn();et();Q();yt();Jn();import{promises as OD}from"fs";import HD from"path";import{isDeepStrictEqual as dd}from"util";Xe();Xe();var go={warningAtConsecutiveFailures:2,manualStopAtConsecutiveFailures:3,maxHistoryRecords:64,maxFailedAcceptanceIds:1024,maxFailedCheckIds:128,maxOverrideSummaryCharacters:2e3};var yD=/^[a-z0-9][a-z0-9._:/-]{0,255}$/u;function ND(e,t){return e<t?-1:e>t?1:0}function bD(e,t,r,i){if(!Array.isArray(e)||e.length>r||!i&&e.length===0)throw new Error(`${t} exceeds its count boundary`);let n=e.map(a=>{if(typeof a!="string"||!yD.test(a))throw new Error(`${t} contains an invalid token: ${String(a)}`);return a});return[...new Set(n)].sort(ND)}function jm(e=[]){return bD(e,"Native repair failed check IDs",go.maxFailedCheckIds,!0)}function VS(e,t){let r=new Set(t);return e.every(i=>r.has(i))}function kD(e,t){return e.failedAcceptanceIds===void 0||e.failedCheckIds===void 0||t.failedAcceptanceIds===void 0||t.failedCheckIds===void 0?e.signatureHash!==t.signatureHash:VS(e.failedAcceptanceIds,t.failedAcceptanceIds)&&VS(e.failedCheckIds,t.failedCheckIds)&&(e.failedAcceptanceIds.length<t.failedAcceptanceIds.length||e.failedCheckIds.length<t.failedCheckIds.length)}function $m(e,t){let r=1,i=e;for(let n=t.length-1;n>=0;n-=1){let a=t[n];if(kD(i,a))break;r+=1,i=a}return r}uc();Xi();function Om(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 qS="repairStagnation",$t={maxEvents:4096,maxDataDepth:8,maxDataNodes:4096,maxTotalDataNodes:65536,maxObjectFields:64,maxArrayEntries:256,maxKeyCharacters:128,maxTextCharacters:4096,maxEventDataCharacters:65536,maxTotalDataCharacters:1048576,maxRunIdCharacters:256},ED=/^[a-f0-9]{64}$/u;var PD=new Set(["run_started","action_proposed","action_completed","eval_completed","checkpoint","state_migrated","state_transitioned","command_check_recorded","recovery_reconciled"]),RD=["data","runId","sequence","timestamp","type"],WS=["disposition","overrideSummaryHash","signatureHash"],CD=["contractHash","disposition","failedAcceptanceIds","failedCheckIds","maxVerifyFailures","overrideSummaryHash","signatureHash"],zS=12;function Dm(e,t){return e<t?-1:e>t?1:0}function JS(e,t,r){let i=Object.keys(e).sort(Dm);if(i.length!==t.length||i.some((n,a)=>n!==t[a]))throw new Error(`${r} fields are invalid`)}function ud(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new Error(`${t} must be a plain object`);return e}function pc(e,t){if(typeof e!="string"||!ED.test(e))throw new Error(`${t} must be a SHA-256 hash`);return e}function xD(e){if(!Array.isArray(e)||e.length>go.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(Dm)}function GS(e){if(typeof e!="string"||e.length===0||e.length>$t.maxRunIdCharacters||Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127}))throw new Error("Native repair trajectory run ID is invalid");return e}function Hm(e,t,r,i,n=!1){if(r.nodes+=1,r.nodes>$t.maxDataNodes)throw new Error("Native repair trajectory event data exceeds its node boundary");if(t>$t.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(`${i} contains a non-finite number`);return}if(typeof e=="string"){if(e.length>$t.maxTextCharacters&&(!n||e.length>$t.maxEventDataCharacters))throw new Error(`${i} contains oversized text`);if(r.characters+=e.length,r.characters>$t.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");return}if(typeof e!="object")throw new Error(`${i} contains a non-JSON value`);if(r.ancestors.has(e))throw new Error(`${i} contains a cycle`);r.ancestors.add(e);try{if(Array.isArray(e)){if(e.length>$t.maxArrayEntries)throw new Error(`${i} contains an oversized array`);e.forEach((s,c)=>Hm(s,t+1,r,`${i}[${c}]`));return}let a=ud(e,i),o=Object.keys(a);if(o.length>$t.maxObjectFields)throw new Error(`${i} contains too many fields`);for(let s of o){if(s.length===0||s.length>$t.maxKeyCharacters)throw new Error(`${i} contains an invalid field name`);if(r.characters+=s.length,r.characters>$t.maxEventDataCharacters)throw new Error("Native repair trajectory event data exceeds its text boundary");Hm(a[s],t+1,r,`${i}.${s}`,t===0&&(s==="summary"||s==="noCodeReason"))}}finally{r.ancestors.delete(e)}}}function AD(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 _D(e,t,r){let i=ud(e,`Native repair trajectory event ${t+1}`);if(JS(i,RD,`Native repair trajectory event ${t+1}`),!Number.isSafeInteger(i.sequence)||i.sequence!==t+1)throw new Error("Native repair trajectory sequence is invalid");if(AD(i.timestamp),typeof i.type!="string"||!PD.has(i.type))throw new Error("Native repair trajectory event type is invalid");if(GS(i.runId)!==r)throw new Error("Native repair trajectory run ID changed inside the committed prefix");let n={nodes:0,characters:0,ancestors:new Set};return Hm(i.data,0,n,"Native trajectory event data"),ud(i.data,"Native repair trajectory event data"),{event:i,dataNodes:n.nodes,dataCharacters:n.characters}}function Lm(e){let t=ud(e,"Native repair trajectory projection"),r=Object.keys(t).sort(Dm),i=r.length===WS.length&&r.every((l,u)=>l===WS[u]);i||JS(t,CD,"Native repair trajectory projection");let n=pc(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:pc(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(i)return{signatureHash:n,disposition:t.disposition,overrideSummaryHash:a,contractHash:null,failedAcceptanceIds:[],failedCheckIds:[],maxVerifyFailures:null};let o=pc(t.contractHash,"Native repair trajectory contract hash"),s=xD(t.failedAcceptanceIds),c=jm(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 ID(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 TD(e,t){let r=t.filter(s=>s.kind==="failure"),i=r.length+1,n=e.maxVerifyFailures??zS;if(i>n)throw new Error("Native repair trajectory commits a failure beyond the hard-stop boundary");let a=$m({signatureHash:e.signatureHash,...e.contractHash===null?{}:{failedAcceptanceIds:e.failedAcceptanceIds,failedCheckIds:e.failedCheckIds}},r),o=i>=n?"hard-stop":a<go.warningAtConsecutiveFailures?"continue":a<go.manualStopAtConsecutiveFailures?"warn":"manual-stop";if(e.disposition!==o||e.overrideSummaryHash!==null)throw new Error(`Native repair trajectory failure disposition is invalid: expected ${o}`)}function jD(e,t,r){let i=t.filter(a=>a.kind==="failure"),n=r?.maxVerifyFailures??zS;if(i.length>=n)throw new Error("Native repair trajectory cannot override a hard stop");if(r?.disposition!=="manual-stop"||r.signatureHash!==e.signatureHash||i.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 US(e){if(!Array.isArray(e.trajectory)||e.trajectory.length>$t.maxEvents)throw new Error("Native repair trajectory exceeds its event boundary");let t=GS(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 r=[],i=null,n=null,a=null,o=0,s=0,c=0;for(let l=0;l<e.committedTrajectoryOffset;l+=1){let u=_D(e.trajectory[l],l,t),{event:d}=u;if(s+=u.dataNodes,c+=u.dataCharacters,s>$t.maxTotalDataNodes||c>$t.maxTotalDataCharacters)throw new Error("Native repair committed trajectory exceeds its aggregate data boundary");let f=d.data,h=Object.hasOwn(f,"repairScopeHash")?pc(f.repairScopeHash,"Native repair trajectory repair scope hash"):Object.hasOwn(f,"implementationScopeHash")?pc(f.implementationScopeHash,"Native repair trajectory implementation scope hash"):null;if(!Object.hasOwn(f,qS)){if(i?.contractHash===null&&d.type==="state_transitioned"&&f.previousPhase==="build"&&f.nextPhase==="verify"&&(h!==null&&n!==null&&h!==n||h===null&&(i?.disposition==="manual-stop"||i?.disposition==="hard-stop"))){r.length=0,i=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 m=Lm(f[qS]);if(ID(f,m),m.overrideSummaryHash===null)m.contractHash!==null&&a!==null&&m.contractHash!==a&&(r.length=0,o=0),m.contractHash!==null&&(a=m.contractHash),m.contractHash===null&&h!==null&&n!==null&&h!==n&&(r.length=0,o=0),h!==null&&(n=h),TD(m,r),o+=1,r.push({kind:"failure",revision:d.sequence,iteration:o,signatureHash:m.signatureHash,...m.contractHash===null?{}:{failedAcceptanceIds:[...m.failedAcceptanceIds],failedCheckIds:[...m.failedCheckIds]}});else{if(i?.contractHash===null&&h!==null&&n!==null&&h!==n)throw new Error("Native repair override cannot cross implementation scope progress");jD(m,r,i);let p=r.at(-1);if(!p||p.kind!=="failure")throw new Error("Native repair trajectory override has no failure history");r.push({kind:"override",revision:d.sequence,iteration:p.iteration,signatureHash:m.signatureHash,summaryHash:m.overrideSummaryHash})}if(i=m,r.length>go.maxHistoryRecords)throw new Error("Native repair trajectory history exceeds its record boundary")}return{history:r,latestProjection:i}}function KS(e){return US(e).history}function YS(e){let t=US(e).latestProjection;return t?{...t}:null}pr();var Hr={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:[]},mc=F("comet-native-runtime:v3:scope-reopen"),$D=[{skillVersion:"3",skillHash:F("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:F("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:F("comet-native-runtime:v1")}];function XS(e){return e.skillVersion===Hr.definition.metadata.version&&e.skillHash===mc||$D.some(t=>t.skillVersion===e.skillVersion&&t.skillHash===e.skillHash)}var Mm={resolveStep({pkg:e,state:t}){return e.definition.orchestration.steps?.find(r=>r.id===t.currentStep)},resolveNext({step:e,outcome:t}){return e.id==="verify"&&t.state?.verification_result==="fail"?"build":e.next??null}};Ui();pr();Ui();async function rn(e){let r={sequence:(await dt(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 gk(e.changeDir,e.run.trajectoryRef,r),r}async function Un(e){let t={runId:e.run.runId,stateVersion:e.run.iteration,trajectoryOffset:e.trajectoryOffset,contextHash:null,artifactsHash:F(e.evidenceHash),createdAt:(e.now??new Date).toISOString()};return await wk(e.changeDir,e.run.checkpointRef,t),t}pr();function QS(e){return F(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}))}Js();$s();var oE=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],DD=new Set(oE),sE=new Set([...oE,"minimum_runtime_version","revision"]),LD=new Set([...sE,"operation"]),MD=512*1024,Fm=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),FD=new Set([...Fm,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]),vc=class extends Error{constructor(r){super(`Native transition for ${r} requires doctor migration before recovery`);this.change=r;this.name="NativeTransitionMigrationRequiredError"}change;code="native-transition-migration-required"};function it(e,t){return HD.join(M(e,t),"transition.json")}function BD(e){return`transition-${e}`}async function VD(e,t,r){let i=BD(t);return ji(e,i,r)}async function Kn(e,t,r,i){let n=await VD(e,t,r);try{return await i()}finally{await $i(n)}}function hd(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal must be an object");return e}function Vm(e,t){let r=Object.keys(e).find(i=>!t.has(i));if(r)throw new Error(`Native transition journal contains unknown field: ${r}`)}function fd(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Dr(e,t){return dd(e,t)}function Bm(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native transition journal event data is invalid");let r=e,i=Object.keys(r),n=i.find(u=>!FD.has(u)),a=[...Fm].find(u=>!Object.hasOwn(r,u)),o=Fm.size+(Object.hasOwn(r,"implementationScopeHash")?1:0)+(Object.hasOwn(r,"repairScopeHash")?1:0)+(Object.hasOwn(r,"repairStagnation")?1:0)+(Object.hasOwn(r,"returnToBuild")?1:0);if(n||a||i.length!==o)throw new Error(`Native transition journal event data keys are invalid${n?`: ${n}`:a?`: missing ${a}`:""}`);if(!["shape","build","verify","archive"].includes(r.previousPhase)||!["shape","build","verify","archive"].includes(r.nextPhase))throw new Error("Native transition journal event phases are invalid");if(r.evidenceHash!==t)throw new Error("Native transition journal event evidence hash mismatch");if(r.returnToBuild!==void 0&&typeof r.returnToBuild!="boolean")throw new Error("Native transition journal returnToBuild flag is invalid");if(Om(r.summary,"Native transition journal event summary"),Gt(r.summary)!==r.summary)throw new Error("Native transition journal event summary contains unredacted credentials");if(!Array.isArray(r.artifacts)||r.artifacts.length>128||r.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(r.noCodeReason!==null&&(Om(r.noCodeReason,"Native transition journal event no-code reason"),Gt(r.noCodeReason)!==r.noCodeReason))throw new Error("Native transition journal event no-code reason contains unredacted credentials");if(r.verificationResult!==null&&r.verificationResult!=="pass"&&r.verificationResult!=="fail")throw new Error("Native transition journal event verification result is invalid");let s=Object.hasOwn(r,"implementationScopeHash")?r.implementationScopeHash:null;if(s!==null&&(typeof s!="string"||!/^[a-f0-9]{64}$/.test(s)||r.previousPhase!=="build"&&r.previousPhase!=="verify"))throw new Error("Native transition journal implementation scope hash is invalid");let c=Object.hasOwn(r,"repairStagnation")?Lm(r.repairStagnation):null;if(c){let u=c.overrideSummaryHash===null;if(u&&(r.previousPhase!=="verify"||r.nextPhase!=="build"||r.verificationResult!=="fail")||!u&&(r.previousPhase!=="build"||r.nextPhase!=="verify"||r.verificationResult!==null))throw new Error("Native transition journal repair projection does not match its phase")}let l=Object.hasOwn(r,"repairScopeHash")?r.repairScopeHash:null;if(l!==null&&(typeof l!="string"||!/^[a-f0-9]{64}$/.test(l)||r.previousPhase!=="build"&&r.previousPhase!=="verify"||s===null))throw new Error("Native transition journal repair scope hash is invalid");return{previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:t,summary:r.summary,artifacts:[...r.artifacts],noCodeReason:r.noCodeReason,verificationResult:r.verificationResult,...r.returnToBuild===!0?{returnToBuild:!0}:{},...s?{implementationScopeHash:s}:{},...l?{repairScopeHash:l}:{},...c?{repairStagnation:c}:{}}}function qD(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e,i=Object.keys(r),n=new Set(["previousPhase","nextPhase","evidenceHash","summary","reason"]);if(i.length===n.size&&i.every(a=>n.has(a))&&r.reason==="spec-rebase")return Bm({previousPhase:r.previousPhase,nextPhase:r.nextPhase,evidenceHash:r.evidenceHash,summary:r.summary,artifacts:[],noCodeReason:null,verificationResult:null},t)}return Bm(e,t)}function qm(e,t,r=!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 i=r?qD(e.eventData,e.evidenceHash):Bm(e.eventData,e.evidenceHash),n=Gi(e.nextRun),a=e.previousRun===null?null:Gi(e.previousRun);return{id:e.id,evidenceHash:e.evidenceHash,createdAt:e.createdAt,previousRun:a,nextRun:n,eventData:i}}function ZS(e,t,r=!1){if(e.skill!==Hr.definition.metadata.name||(r?!XS(e):e.skillVersion!==Hr.definition.metadata.version||e.skillHash!==mc)||e.orchestration!==Hr.definition.orchestration.mode||e.pendingRef!==_t.pendingRef||e.trajectoryRef!==_t.trajectoryRef||e.contextRef!==_t.contextRef||e.artifactsRef!==_t.artifactsRef||e.checkpointRef!==_t.checkpointRef)throw new Error(`Native transition journal ${t} metadata or storage refs are invalid`)}function eE(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 tE(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 Wm(e,t,r,i=!1,n="advance"){let{previousRun:a,nextRun:o}=r;if(ZS(o,"next Run",i||a!==null),tE(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(ZS(a,"previous Run",!0),tE(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(!dd(eE(a),eE(o)))throw new Error("Native transition journal Run identity or storage invariants changed")}function WD(e,t,r){return F(JSON.stringify({operation:"spec-rebase",change:e,summary:t,specChanges:r}))}function cE(e,t,r){return e.phase!=="shape"&&t.phase==="build"&&r.verificationResult===null?"spec-rebase":"advance"}function rE(e){return"implementation_scope"in e?{implementation_scope:e.implementation_scope,verification_evidence:e.verification_evidence,partial_allowance:e.partial_allowance}:null}function zm(e,t,r,i,n=!1){let a=r.eventData,o=rE(e),s=rE(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(i==="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&&dd(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(i==="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&&dd(e.spec_changes,t.spec_changes),l=QS({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||r.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(i==="spec-rebase"){let c=WD(e.name,a.summary,t.spec_changes),l=F(`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&&r.evidenceHash!==c||n&&r.evidenceHash!==c&&r.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 Jm(e,t){let r=hd(e);if(Vm(r,LD),r.schema!==Di)throw new Error(`Expected Native transition schema ${Di}`);let i=fd(r.minimum_runtime_version,"Native transition minimum_runtime_version");if(i>3)throw new Error(`Native transition requires runtime protocol ${i}; current protocol is ${3}`);if(i!==3)throw new Error(`Native transition ${Di} minimum_runtime_version must be ${3}`);let n=fd(r.revision,"Native transition revision");if(n!==1)throw new Error("Native transition journal revision must be 1");if(r.operation!=="advance"&&r.operation!=="spec-rebase"&&r.operation!=="evidence-retreat"&&r.operation!=="runtime-rebuild")throw new Error("Native transition journal operation is invalid");let a=qm(r,t),o=wt(r.previousState),s=wt(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native transition journal state mismatch");if(zm(o,s,a,r.operation),Wm(o,s,a,!1,r.operation),s.revision!==o.revision+1)throw new Error("Native transition journal state revision must advance exactly once");return{schema:Di,minimum_runtime_version:3,revision:n,operation:r.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 zD(e,t){let r=hd(e);if(Vm(r,DD),r.schema!==On)throw new Error(`Expected Native transition schema ${On}`);let i=qm(r,t,!0),n=Hn(r.previousState),a=Hn(r.nextState);if(n.name!==t||a.name!==t)throw new Error("Native transition journal state mismatch");return zm(n,a,i,cE(n,a,i.eventData),!0),Wm(n,a,i,!0),{schema:On,id:i.id,change:t,evidenceHash:i.evidenceHash,createdAt:i.createdAt,previousState:n,nextState:a,previousRun:i.previousRun,nextRun:i.nextRun,eventData:i.eventData}}function Gm(e,t){let r=hd(e);if(Vm(r,sE),r.schema!==Ur)throw new Error(`Expected Native transition schema ${Ur}`);if(fd(r.minimum_runtime_version,"Native v2 transition minimum_runtime_version")!==2)throw new Error(`Native transition ${Ur} minimum_runtime_version must be 2`);let n=fd(r.revision,"Native v2 transition revision");if(n!==1)throw new Error("Native v2 transition journal revision must be 1");let a=qm(r,t,!0),o=Rr(r.previousState),s=Rr(r.nextState);if(o.name!==t||s.name!==t)throw new Error("Native v2 transition journal state mismatch");if(zm(o,s,a,cE(o,s,a.eventData),!0),Wm(o,s,a,!0),s.revision!==o.revision+1)throw new Error("Native v2 transition journal state revision must advance exactly once");return{schema:Ur,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 JD(e,t){let r=hd(e);if(r.schema===Di)return{status:"current",journal:Jm(r,t)};if(r.schema===On)return{status:"migration-required",journal:zD(r,t)};if(r.schema===Ur)return{status:"migration-required",journal:Gm(r,t)};throw new Error(`Unsupported Native transition journal schema: ${String(r.schema)}`)}async function Um(e,t){let r=it(e,t),i=$(e,r);await T(i,r);try{let n=await oe({root:i,file:r,maxBytes:MD,label:`Native transition journal ${t}`});return JD(JSON.parse(n.bytes.toString("utf8")),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function ni(e,t){let r=await Um(e,t);if(!r)return null;if(r.status==="migration-required")throw new vc(t);return r.journal}function iE(e,t){if(Dr(e,t.nextRun))return"next";if(t.previousRun===null){if(e===null)return"previous"}else if(Dr(e,t.previousRun))return"previous";throw new Error(`Native transition Run content changed for ${t.change}; recovery journal was preserved`)}function nE(e,t){if(Dr(e,t.nextState))return"next";if(Dr(e,t.previousState))return"previous";throw new Error(`Native transition change content changed for ${t.change}; recovery journal was preserved`)}function GD(e){let{journal:t}=e;return lE({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 lE(e){return{sequence:e.sequence,timestamp:e.timestamp,type:e.type,runId:e.runId,data:e.data}}function aE(e,t){let r=e.map((a,o)=>({event:a,index:o})).filter(({event:a})=>a.data.transitionId===t.id),i=r.filter(({event:a})=>a.type==="run_started"),n=r.filter(({event:a})=>a.type==="state_transitioned");if(r.length!==i.length+n.length||i.length>(t.previousRun===null?1:0)||n.length>1||t.previousRun===null&&n.length===1&&(i.length!==1||i[0].index>=n[0].index))throw new Error(`Native trajectory transition id collision for ${t.change}; recovery journal was preserved`);for(let a of[...i,...n]){let o=GD({sequence:a.index+1,journal:t,type:a.event.type});if(!Dr(lE(a.event),o))throw new Error(`Native trajectory event changed for transition ${t.id}; recovery journal was preserved`)}return{started:i[0]?.event??null,transitioned:n[0]?.event??null}}async function pd(e,t,r){if(await io(e,t))throw new Error(`Native schema migration is incomplete for ${t}; run doctor --repair`);await Wu(e,t);let i=await ni(e,t);if(!i)return null;let n=M(e,t),a=aE(await dt(n,i.nextRun.trajectoryRef),i),[o,s]=await Promise.all([Ve(n),We(e,t)]),c=iE(o,i),l=nE(s,i);if((a.started||a.transitioned)&&(c!=="next"||l!=="next"))throw new Error(`Native trajectory is ahead of transition state for ${i.change}; recovery journal was preserved`);if(c==="previous"&&(await Vn(n,i.nextRun),await r?.afterRunStateWritten?.(i)),!Dr(await Ve(n),i.nextRun))throw new Error(`Native transition Run content changed while continuing ${i.change}; recovery journal was preserved`);if(l==="previous"){let v=await Qu(e,i.nextState,i.previousState.revision);if(!Dr(v,i.nextState))throw new Error(`Native transition change write diverged for ${i.change}; recovery journal was preserved`);await r?.afterChangeStateWritten?.(i)}if(!Dr(await We(e,t),i.nextState))throw new Error(`Native transition change content changed while continuing ${i.change}; recovery journal was preserved`);let u=await ni(e,t);if(!u||!Dr(u,i))throw new Error(`Native transition journal changed while continuing ${i.change}; it was preserved`);let d=aE(await dt(n,i.nextRun.trajectoryRef),i);i.previousRun===null&&(d.started||await rn({changeDir:n,run:i.nextRun,type:"run_started",data:{runtime:"comet-native",phase:i.previousState.phase,transitionId:i.id},now:new Date(i.createdAt)}));let f=d.transitioned;f||(f=await rn({changeDir:n,run:i.nextRun,type:"state_transitioned",data:{...i.eventData,transitionId:i.id},now:new Date(i.createdAt)})),await Un({changeDir:n,run:i.nextRun,trajectoryOffset:f.sequence,evidenceHash:i.evidenceHash,now:new Date(i.createdAt)});let[h,m]=await Promise.all([Ve(n),We(e,t)]);iE(h,{...i,previousRun:i.nextRun}),nE(m,{...i,previousState:i.nextState});let p=await ni(e,t);if(!p||!Dr(p,i))throw new Error(`Native transition journal changed while continuing ${i.change}; it was not removed`);return await OD.rm(it(e,t),{force:!0}),i.nextState}async function uE(e,t,r){return de(e,`continue transition ${t}`,()=>Kn(e,t,`continue transition ${t}`,()=>pd(e,t,r)))}xs();Ft();ke();Ft();xs();Xe();import dE from"node:path";var UD="comet.native.contract.v1",KD="comet.native.acceptance-set.v1",fE=/^[a-f0-9]{64}$/u,gc={maxAcceptanceCriteria:Cs.maxCriteria};function hE(e,t){let r=dE.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let n=i.codePointAt(0)??0;return n<=31||n===127})||dE.posix.isAbsolute(r)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||r!==e||r==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized project-relative ref`);return e}function pE(e){return O("comet.native.contract-content.v1",e.replace(/\r\n?/gu,`
|
|
205
|
+
`))}function YD(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(fE))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(fE))throw new Error(`Replace contract ${e.capability} requires a base hash`);let t=hE(e.source,`Contract source for ${e.capability}`);return{snapshot:{capability:e.capability,operation:e.operation,source:t,baseHash:e.baseHash,contentHash:pE(e.markdown)},markdown:e.markdown}}function XD(e,t){return mE(e.id,t.id)}function mE(e,t){return e<t?-1:e>t?1:0}function vE(e){let t=hE(e.briefSource??"brief.md","Native brief source"),r=e.specs.map(YD).sort((d,f)=>mE(d.snapshot.capability,f.snapshot.capability)),i=r.map(({snapshot:d})=>d.capability);if(new Set(i).size!==i.length)throw new Error("Native contract contains duplicate capabilities");let n=[t,...r.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=du(e.briefMarkdown,t,gc.maxAcceptanceCriteria);for(let{snapshot:d,markdown:f}of r)f===null||d.source===null||(a.push(...fu(f,d.source,gc.maxAcceptanceCriteria-a.length)),a.push(...GN(f,d.source,gc.maxAcceptanceCriteria-a.length)));if(a.sort(XD),a.length===0)throw new Error("Native contract has no structured acceptance criteria");if(a.length>gc.maxAcceptanceCriteria)throw new Error(`Native contract exceeds its ${gc.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:pE(e.briefMarkdown)},c=r.map(({snapshot:d})=>d),l=O(KD,a),u={schema:"comet.native.contract.v1",brief:s,specs:c,acceptance:a,acceptanceHash:l};return{...u,contractHash:O(UD,u)}}var md={maxSpecs:64,maxFileBytes:hs,maxTotalBytes:4*1024*1024};async function wo(e){if(e.specChanges.length>md.maxSpecs)throw new Error("Native contract exceeds its spec-count budget");let t=await te({root:e.changeDir,ref:e.briefRef,maxBytes:md.maxFileBytes}),r=t.size,i=[];for(let n of e.specChanges){if(n.operation==="remove"){i.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 te({root:e.changeDir,ref:n.source,maxBytes:md.maxFileBytes});if(r+=a.size,r>md.maxTotalBytes)throw new Error("Native contract exceeds its total byte budget");i.push({capability:n.capability,operation:n.operation,source:a.ref,baseHash:n.base_hash,markdown:a.text})}return{contract:vE({briefSource:t.ref,briefMarkdown:t.text,specs:i}),sourceCount:i.filter(n=>n.source!==null).length+1,totalBytes:r}}ii();Fn();Xi();uc();import{execFile as vL}from"node:child_process";vd();Km();ke();import{promisify as gL}from"node:util";ke();import{promises as nL}from"fs";ue();ke();pr();Q();yt();ds();Jn();import yo from"path";var an={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024},No=/^[a-f0-9]{64}$/u;function gd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function wd(e,t,r){let i=new Set(t),n=Object.keys(e).filter(o=>!i.has(o)),a=t.filter(o=>!(o in e));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(a.length>0)throw new Error(`${r} is missing field(s): ${a.join(", ")}`)}function nn(e,t,r=2e3){if(typeof e!="string"||e.length===0||e.length>r)throw new Error(`${t} must be a non-empty string of at most ${r} characters`);return e}function gE(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Ym(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function QD(e){let t=e.trim().replaceAll("\\","/");if(t.length===0||yo.isAbsolute(t)||/^(?:[A-Za-z]:|~|\/)/u.test(t)||t.split("/").includes(".."))throw new Error(`Checkpoint artifact must be project-relative: ${e}`);let r=yo.posix.normalize(t);if(r==="."||r===".."||r.startsWith("../"))throw new Error(`Checkpoint artifact must name a project file: ${e}`);return r}function Xm(e,t){return yo.join(M(e,t),"checkpoints","progress.json")}function on(e,t){return yo.join(M(e,t),"checkpoint-journal.json")}function Qm(e,t,r){if(!No.test(r))throw new Error("Native checkpoint manifest hash is invalid");return yo.join(M(e,t),"checkpoints","manifests",`${r}.json`)}function ZD(e){if(!No.test(e))throw new Error("Native checkpoint manifest hash is invalid");return`runtime/checkpoints/manifests/${e}.json`}async function Zm(e,t,r){let i=await oe({root:e,file:t,maxBytes:an.maxDocumentBytes,label:r});return JSON.parse(i.bytes.toString("utf8"))}function eL(e,t){let r=gd(e,`checkpoint manifest artifact ${t}`);wd(r,["path","hash","size"],`checkpoint manifest artifact ${t}`);let i=QD(nn(r.path,`checkpoint artifact ${t} path`,4096)),n=Sr(i);if(n)throw new Error(`checkpoint artifact ${t} is excluded as sensitive (${n}): ${i}`);if(typeof r.hash!="string"||!No.test(r.hash))throw new Error(`checkpoint artifact ${t} hash is invalid`);return{path:i,hash:r.hash,size:Ym(r.size,`checkpoint artifact ${t} size`)}}function yd(e,t){let r=gd(e,"Native checkpoint manifest");if(wd(r,["schema","change","artifacts","totalBytes"],"Native checkpoint manifest"),r.schema!=="comet.native.checkpoint-manifest.v1")throw new Error("Native checkpoint manifest schema is invalid");if(r.change!==t)throw new Error("Native checkpoint manifest change mismatch");if(!Array.isArray(r.artifacts))throw new Error("Native checkpoint manifest artifacts must be an array");if(r.artifacts.length>an.maxArtifacts)throw new Error("Native checkpoint manifest has too many artifacts");let i=r.artifacts.map(eL),n=[...i].sort((o,s)=>o.path.localeCompare(s.path));if(JSON.stringify(i)!==JSON.stringify(n))throw new Error("Native checkpoint manifest artifacts must be sorted");if(new Set(i.map(o=>o.path)).size!==i.length)throw new Error("Native checkpoint manifest has duplicate artifacts");let a=Ym(r.totalBytes,"checkpoint manifest totalBytes");if(i.reduce((o,s)=>o+s.size,0)!==a)throw new Error("Native checkpoint manifest totalBytes mismatch");if(a>an.maxTotalBytes)throw new Error("Native checkpoint manifest totalBytes exceeds its budget");return{schema:"comet.native.checkpoint-manifest.v1",change:t,artifacts:i,totalBytes:a}}function ev(e){return F(JSON.stringify(yd(e,e.change)))}function tv(e,t){let r=gd(e,"Native progress checkpoint");if(wd(r,["schema","id","change","phase","previousRevision","stateRevision","summary","nextAction","inputHash","manifestHash","manifestRef","artifactCount","createdAt"],"Native progress checkpoint"),r.schema!=="comet.native.progress-checkpoint.v1")throw new Error("Native progress checkpoint schema is invalid");if(r.change!==t)throw new Error("Native checkpoint change mismatch");let i=r.phase;if(i!=="shape"&&i!=="build"&&i!=="verify"&&i!=="archive")throw new Error("Native checkpoint phase is invalid");let n=gE(r.previousRevision,"Native checkpoint previousRevision"),a=gE(r.stateRevision,"Native checkpoint stateRevision");if(a!==n+1)throw new Error("Native checkpoint stateRevision must increment previousRevision once");let o=nn(r.manifestHash,"Native checkpoint manifestHash",64);if(!No.test(o))throw new Error("Native checkpoint manifestHash is invalid");let s=ZD(o);if(r.manifestRef!==s)throw new Error("Native checkpoint manifestRef does not match manifestHash");let c=nn(r.inputHash,"Native checkpoint inputHash",64);if(!No.test(c))throw new Error("Native checkpoint inputHash is invalid");let l=nn(r.createdAt,"Native checkpoint createdAt",64);if(Number.isNaN(Date.parse(l)))throw new Error("Native checkpoint createdAt is invalid");let u=Ym(r.artifactCount,"Native checkpoint artifactCount");if(u>an.maxArtifacts)throw new Error("Native checkpoint artifactCount exceeds its budget");let d=nn(r.summary,"Native checkpoint summary"),f=nn(r.nextAction,"Native checkpoint nextAction");if(Gt(d)!==d||Gt(f)!==f)throw new Error("Native checkpoint text contains unredacted credential material");return{schema:"comet.native.progress-checkpoint.v1",id:nn(r.id,"Native checkpoint id",128),change:t,phase:i,previousRevision:n,stateRevision:a,summary:d,nextAction:f,inputHash:c,manifestHash:o,manifestRef:s,artifactCount:u,createdAt:l}}function tL(e,t){let r=gd(e,"Native checkpoint journal");if(wd(r,["schema","id","change","inputHash","createdAt","previousState","nextState","checkpoint","manifest"],"Native checkpoint journal"),r.schema!=="comet.native.checkpoint-journal.v1")throw new Error("Native checkpoint journal schema is invalid");if(r.change!==t)throw new Error("Native checkpoint journal change mismatch");let i=wt(r.previousState),n=wt(r.nextState),a=tv(r.checkpoint,t),o=yd(r.manifest,t),s=nn(r.inputHash,"Native checkpoint journal inputHash",64),c=F(JSON.stringify({summary:a.summary,nextAction:a.nextAction,artifacts:o.artifacts}));if(!No.test(s)||s!==a.inputHash||s!==c||r.id!==a.id||r.createdAt!==a.createdAt)throw new Error("Native checkpoint journal envelope mismatch");if(i.name!==t||n.name!==t||n.revision!==i.revision+1||a.previousRevision!==i.revision||a.stateRevision!==n.revision||a.phase!==n.phase||a.manifestHash!==ev(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:i,nextState:n,checkpoint:a,manifest:o}}async function rL(e,t,r){let i=yo.resolve(e.projectRoot,...t.split("/"));if(!D(e.projectRoot,i)||D(e.nativeRoot,i)||D(e.runtimeDir,i))throw new Error(`Checkpoint artifact is outside project content: ${t}`);let n=np(e,t);if(n)throw new Error(`Checkpoint artifact is excluded as sensitive (${n}): ${t}`);let a=await oe({root:e.projectRoot,file:i,maxBytes:an.maxFileBytes,label:`Checkpoint artifact ${t}`,forbiddenRoots:[e.nativeRoot,e.runtimeDir],hooks:{afterParentChainCaptured:()=>r?.afterParentChainCaptured?.(t),afterOpen:()=>r?.afterOpen?.(t),beforeRead:()=>r?.beforeRead?.(t)}});return{path:t,hash:a.hash,size:a.size}}async function iL(e,t){let r=Xm(e,t),i=$(e,r);await T(i,r);try{return tv(await Zm(i,r,"Native progress checkpoint"),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function rv(e,t,r){let i=Qm(e,t,r),n=$(e,i);await T(n,i);let a=await Zm(n,i,"Native checkpoint manifest"),o=yd(a,t);if(iv(e,o),ev(o)!==r)throw new Error("Native checkpoint manifest content hash mismatch");return o}async function sn(e,t){let r=on(e,t),i=$(e,r);await T(i,r);try{let n=tL(await Zm(i,r,"Native checkpoint journal"),t);return iv(e,n.manifest),n}catch(n){if(n.code==="ENOENT")return null;throw n}}async function wE(e,t,r,i){let n=yd(r,t);iv(e,n);let a=ev(n),o=Qm(e,t,a),s=$(e,o);await T(s,o);try{let c=await rv(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 re(o,n,{containedRoot:s,beforeCommit:i?.beforeCommit}),a}function iv(e,t){for(let r of t.artifacts){let i=np(e,r.path);if(i)throw new Error(`Native checkpoint manifest contains a sensitive artifact (${i}): ${r.path}`)}}async function yE(e,t){let r=tv(t,t.change),i=await rv(e,r.change,r.manifestHash),n=F(JSON.stringify({summary:r.summary,nextAction:r.nextAction,artifacts:i.artifacts}));if(r.inputHash!==n||r.artifactCount!==i.artifacts.length)throw new Error("Native progress checkpoint does not match its artifact manifest");let a=Xm(e,t.change),o=$(e,a);await T(o,a),await re(a,r,{containedRoot:o})}async function NE(e){let t;try{t=await iL(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:Xm(e.paths,e.name)}]}}if(!t)return{checkpoint:null,manifest:null,freshness:"fresh",reasons:["no-checkpoint"],findings:[]};let r=[],i=[];t.stateRevision!==e.stateRevision&&r.push("state-revision-changed");let n=null;try{n=await rv(e.paths,e.name,t.manifestHash);let a=F(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 rL(e.paths,o.path);(s.hash!==o.hash||s.size!==o.size)&&r.push(`artifact-changed:${o.path}`)}catch{r.push(`artifact-unavailable:${o.path}`)}}catch(a){r.push("checkpoint-manifest-invalid"),i.push({code:"checkpoint-manifest-invalid",message:`Native checkpoint manifest is invalid: ${a.message}`,path:Qm(e.paths,e.name,t.manifestHash)})}return{checkpoint:t,manifest:n,freshness:r.length===0?"fresh":"stale",reasons:r,findings:i}}et();async function bE(e,t,r){let i=await sn(e,t);if(!i)return null;if(await wE(e,i.change,i.manifest)!==i.checkpoint.manifestHash)throw new Error("Native checkpoint recovery manifest hash mismatch");return await Qu(e,i.nextState,i.previousState.revision,{allowPendingCheckpointRecovery:!0}),await r?.afterStateWritten?.(i),await yE(e,i.checkpoint),await r?.afterProgressWritten?.(i),await nL.rm(on(e,t),{force:!0}),i}async function kE(e,t,r){return de(e,`continue checkpoint ${t}`,()=>Kn(e,t,`continue checkpoint ${t}`,async()=>(await pd(e,t),bE(e,t,r))))}ue();ad();Q();ar();import{constants as nv,promises as Ut}from"node:fs";import bo from"node:path";var aL=/^[a-f0-9]{64}$/u,oL=/^runtime\/evidence\/check-receipts\/([a-f0-9]{64})\.json$/u,wc=512*1024;function sL(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Nd(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Rt(r,i)?J(r,i):J(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function cL(e,t){let r=bo.resolve(e),i=bo.resolve(t);if(!D(r,i))throw new Error("Native check receipt parent is outside the Native root");let n=[],a=r;for(let o of["",...bo.relative(r,i).split(bo.sep).filter(Boolean)]){o&&(a=bo.join(a,o));let s=await Ut.lstat(a);if(!s.isDirectory()||s.isSymbolicLink())throw new Error(`Native check receipt parent must be a real directory: ${a}`);let c=await Ut.realpath(a);if(n.length>0&&!D(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 SE(e){for(let t of e){let r=await Ut.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!sL(t,r)||await Ut.realpath(t.path)!==t.realPath)throw new Error(`Native check receipt parent changed while reading: ${t.path}`)}}function lL(e){if(!aL.test(e))throw new Error("Native check receipt hash is invalid");return`runtime/evidence/check-receipts/${e}.json`}function uL(e){let t=oL.exec(e);if(!t)throw new Error("Native check receipt ref is invalid");return t[1]}function dL(e,t,r){return Ii(M(e,t),lL(r))}async function fL(e,t,r){let i=await cL(r,bo.dirname(e)),n=await Ut.lstat(e);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native check receipt must be a regular file");if(n.size>wc)throw new Error(`Native check receipt exceeds ${wc} bytes`);let[a,o]=await Promise.all([Ut.realpath(t),Ut.realpath(e)]);if(!D(a,o))throw new Error("Native check receipt resolves outside its change");let s=process.platform==="win32"?"r":nv.O_RDONLY|nv.O_NOFOLLOW|nv.O_NONBLOCK,c=await Ut.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(),Ut.lstat(e),Ut.realpath(e)]);if(await SE(i),!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Nd(n,l)||!Nd(l,u))throw new Error("Native check receipt changed while opening");let f=[],h=0,m=Buffer.allocUnsafe(16*1024);for(;;){let N=wc+1-h,E=await c.read(m,0,Math.min(m.length,N),null);if(E.bytesRead===0)break;if(h+=E.bytesRead,h>wc)throw new Error(`Native check receipt exceeds ${wc} bytes`);f.push(Buffer.from(m.subarray(0,E.bytesRead)))}let[p,v,g]=await Promise.all([c.stat(),Ut.lstat(e),Ut.realpath(e)]);if(await SE(i),!v.isFile()||v.isSymbolicLink()||g!==o||!D(a,g)||!Nd(l,p)||!Nd(l,v))throw new Error("Native check receipt changed while reading");return JSON.parse(Buffer.concat(f,h).toString("utf8"))}finally{await c.close()}}async function EE(e,t,r){let i=uL(r),n=M(e,t),a=dL(e,t,i),o=$(e,a);await T(o,a);let s=nd(await fL(a,n,o));if(s.change!==t||s.receiptHash!==i)throw new Error("Native check receipt ref/hash/change mismatch");return s}ii();et();Jn();var yc=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Fn();ho();Xi();var HK=64*1024;var DK=3600*1e3;var LK=gL(vL);var wL=["change","sourceRevision","contractHash","scopeHash","snapshotHash","artifactHash"];function PE(e,t){let r=[];for(let i of wL){let n=e.bindings[i],a=t[i];n!==a&&r.push(`${i}: expected ${JSON.stringify(a)}, got ${JSON.stringify(n)}`)}return{ok:r.length===0,mismatches:r}}async function RE(e){if(e.receipt.kind!=="static-inspection")return null;let t=await EE(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}ho();var cn=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};function NL(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 bL(e){let t=NL(e.bundle.baseline),r=await Qp(e.paths,t,{origin:"explicit",now:e.now});return Em({baseline:t,current:r,contractHash:e.bundle.scope.contractHash,declaredArtifacts:e.bundle.scope.declaredArtifacts,noCodeReason:e.bundle.scope.noCodeReason,externalDrift:e.bundle.authority.externalDrift}).scope.currentProjectionHash}async function xE(e){if(!e.state.implementation_scope)throw new Error("Native change has no implementation scope");let t=await fc(e.paths,e.state.name,e.state.implementation_scope),r=await wo({changeDir:se(e.paths,e.state.name),briefRef:e.state.brief,specChanges:e.state.spec_changes}),i=await bL({paths:e.paths,bundle:t,now:e.now}),n=[];return r.contract.contractHash!==t.scope.contractHash&&n.push("verification-contract-stale"),i!==t.scope.currentProjectionHash&&n.push("verification-implementation-stale"),{bundle:t,contract:r.contract,contractHash:r.contract.contractHash,acceptanceHash:r.contract.acceptanceHash,findingCodes:n}}async function AE(e){if(!e.state.implementation_scope)return{freshness:"missing",findingCodes:["verification-evidence-missing"]};try{let t=await xE(e),r=[...new Set(t.findingCodes)].sort();return{freshness:r.length===0?"fresh":"stale",findingCodes:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"]}}}async function kL(e){let t=await te({root:se(e.paths,e.state.name),ref:e.reportRef});return{ref:t.ref,hash:t.hash,text:t.text,entries:KN(t.text)}}function SL(e){let{receipt:t,implementationScope:r}=e,i=[],n=Sm({baseline:r.baseline,current:r.current,declaredArtifacts:r.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!==r.scope.scopeHash||t.implementation.expectedSnapshotHash!==r.scope.currentProjectionHash||t.implementation.beforeSnapshotHash!==r.scope.currentProjectionHash||t.implementation.afterSnapshotHash!==r.scope.currentProjectionHash||t.counts.filesSelected!==n.length||t.status==="passed"&&(t.counts.filesScanned+t.counts.binaryFilesSkipped!==n.length||t.counts.bytesScanned!==a))&&i.push("verification-receipt-stale"),e.result==="pass"&&t.status!=="passed"&&i.push("verification-receipt-outcome-mismatch"),i}function EL(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:Im(e.implementationScope.scope.declaredArtifacts)}}async function CE(e){let t=await hc(e.paths,e.state.name,e.ref),r=[];t.role!==e.role&&r.push(`role: expected ${e.role}, got ${t.role}`);let i=PE(t,e.expectedBindings);if(r.push(...i.mismatches),e.acceptanceId!==void 0&&!t.acceptanceIds.includes(e.acceptanceId)&&r.push(`acceptanceId: expected ${e.acceptanceId} in [${t.acceptanceIds.join(", ")}]`),r.length>0)throw new cn([{ref:e.ref,role:e.role,...e.acceptanceId!==void 0?{acceptanceId:e.acceptanceId}:{},mismatches:r}]);if(e.result==="pass"&&t.status!=="passed")throw new Error(`Native verification receipt is ${t.status}`);let n=await RE({paths:e.paths,state:e.state,receipt:t});if(n){let a=SL({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 PL(e){let t=EL({state:e.state,contractHash:e.contractHash,implementationScope:e.implementationScope,sourceRevision:e.sourceRevision}),r=[];for(let i of e.requiredReceiptRefs){let n=await CE({...e,ref:i,expectedBindings:t,role:"required-check"}).catch(a=>{if(a instanceof cn)return r.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 i of e.trace.entries)if(i.status!=="missing")for(let n of i.evidenceRefs){let a=await CE({...e,result:i.status==="passed"?"pass":"fail",ref:n,expectedBindings:t,acceptanceId:i.acceptanceId,role:"acceptance-evidence"}).catch(o=>{if(o instanceof cn)return r.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(i.status==="failed"&&a.status==="passed")throw new Error("Native failed acceptance evidence must reference a non-passing receipt")}}if(r.length>0)throw new cn(r)}function av(e,t){return{result:e,freshness:t,contractHash:null,acceptanceHash:null,implementationScopeHash:null,reportHash:null,envelopeHash:null,partialAllowanceHash:null,skippedAcceptanceCount:0}}async function bd(e){if(!e.state.implementation_scope||!e.state.verification_evidence||!e.state.verification_report)return{freshness:"missing",findingCodes:["verification-evidence-missing"],evidence:av(e.state.verification_result,"missing"),envelope:null};try{let[t,r]=await Promise.all([xE(e),vo(e.paths,e.state.name,e.state.verification_evidence)]);if(r.schema!=="comet.native.verification-evidence.v2")return{freshness:"stale",findingCodes:["verification-protocol-legacy"],evidence:av(e.state.verification_result,"stale"),envelope:null};let i=await kL({paths:e.paths,state:e.state,reportRef:e.state.verification_report}),n=[...t.findingCodes];(i.hash!==r.reportHash||i.ref!==r.reportRef)&&n.push("verification-report-stale"),(r.result!==e.state.verification_result||r.implementationScopeRef!==e.state.implementation_scope||r.partialAllowanceRef!==e.state.partial_allowance||r.sourceRevision>=e.state.revision||r.contractHash!==t.bundle.scope.contractHash||r.acceptanceCriteriaHash!==t.acceptanceHash)&&n.push("verification-state-mismatch");try{await PL({paths:e.paths,state:e.state,result:r.result,trace:r.acceptanceTrace,requiredReceiptRefs:r.requiredReceiptRefs,contractHash:r.contractHash,implementationScope:t.bundle,sourceRevision:r.sourceRevision})}catch{n.push("verification-receipt-invalid")}let a=[...new Set(n)].sort(),o=a.length>0?"stale":r.freshness;return{freshness:o,findingCodes:a,evidence:{result:e.state.verification_result,freshness:o,contractHash:r.contractHash,acceptanceHash:r.acceptanceCriteriaHash,implementationScopeHash:r.implementationScopeHash,reportHash:r.reportHash,envelopeHash:r.envelopeHash,partialAllowanceHash:r.partialAllowanceHash,skippedAcceptanceCount:r.acceptanceTrace.skipped},envelope:r}}catch{return{freshness:"invalid",findingCodes:["verification-evidence-invalid"],evidence:av(e.state.verification_result,"invalid"),envelope:null}}}_r();function CL(e,t){return`archive/${t.toISOString().slice(0,10)}-${e}`}async function IE(e){try{return await RL.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function xL(e,t){try{return(await te({root:e,ref:t})).hash}catch(r){if(r.code==="ENOENT")return null;throw r}}async function AL(e,t,r){let i=Zu(e,r.capability);if(!D(e.nativeRoot,i))throw new Error(`Native canonical spec escapes its root: ${r.capability}`);let n=_E.relative(e.nativeRoot,i).replaceAll("\\","/"),a=await xL(e.nativeRoot,n),o=null;if(r.operation!=="remove"){if(!r.source)throw new Error(`Native proposed spec is missing: ${r.capability}`);o=(await te({root:se(e,t),ref:r.source})).hash}return{capability:r.capability,operation:r.operation,expectedBaseHash:r.operation==="create"?null:r.base_hash,actualBaseHash:a,proposedHash:o}}async function _L(e,t){return IE(it(e,t))}async function kd(e){let t=e.now??new Date,r=await We(e.paths,e.name),i=await Tt(e.paths,e.name),n=await Ee(e.paths.projectRoot),a=CL(r.name,t),o=_E.resolve(e.paths.nativeRoot,...a.split("/"));if(!D(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(r.spec_changes.map(m=>AL(e.paths,r.name,m))),bd({paths:e.paths,state:r,now:t}),ld(e.paths,r.name),io(e.paths,r.name),no(e.paths,r.name),_L(e.paths,r.name),IE(o)]);return Yk({change:r.name,archiveConfirmation:n?.native.archive_confirmation??"automatic",stateSchema:r.schema,revision:r.revision,phase:r.phase,archived:r.archived,pendingJournal:u||d||f,targetRef:a,targetExists:h,specs:s,evidence:c.evidence,workspace:i?.schema==="comet.native.workspace.v3"?{schema:i.schema,isolation:i.isolation,changeBranch:i.changeBranch,targetBranch:i.targetBranch,finish:i.finish}:null,findingCodes:[...c.findingCodes,...l.findingCodes]})}pr();yt();import{promises as ov}from"node:fs";import ai from"node:path";var IL="comet.native.archive-tree.v1",TL={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};function $E(e){let t={...TL,...e};for(let[r,i]of Object.entries(t))if(!Number.isSafeInteger(i)||i<=0)throw new Error(`Native Archive content limit ${r} must be a positive safe integer`);return t}function TE(e){return JSON.stringify(e.map(t=>({name:t.name,kind:t.isDirectory()?"directory":t.isFile()?"file":t.isSymbolicLink()?"symlink":"other"})).sort((t,r)=>t.name.localeCompare(r.name)))}function jE(e,t,r,i){if(r.entryCount+=1,r.entryCount>i.maxEntries)throw new Error(`Native Archive content exceeds ${i.maxEntries} entries`);if(Buffer.byteLength(t.ref,"utf8")>i.maxRefBytes)throw new Error(`Native Archive content ref exceeds ${i.maxRefBytes} bytes: ${t.ref}`);let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(r.manifestBytes+=n+(e.length===0?0:1),r.manifestBytes+2>i.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${i.maxManifestBytes} bytes`);e.push(t)}async function OE(e,t,r,i,n,a){if(a>n.maxDepth)throw new Error(`Native Archive content exceeds depth ${n.maxDepth}`);let o=await xt({root:e,directory:t,label:`Native Archive content directory ${ai.relative(e,t)||"."}`,maxEntries:n.maxEntries}),s=TE(o.entries),c=[...o.entries];c.sort((u,d)=>u.name.localeCompare(d.name));for(let u of c){await o.verify();let d=ai.join(t,u.name),f=ai.relative(e,d).replaceAll("\\","/"),h=await ov.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()){jE(r,{ref:f,kind:"directory"},i,n),await OE(e,d,r,i,n,a+1);continue}if(!u.isFile()||!h.isFile())throw new Error(`Native Archive content must contain only files and directories: ${f}`);let m=await oe({root:e,file:d,maxBytes:n.maxFileBytes,label:`Native Archive content file ${f}`});if(i.totalBytes+=m.size,i.totalBytes>n.maxTotalBytes)throw new Error(`Native Archive content exceeds ${n.maxTotalBytes} total file bytes`);jE(r,{ref:f,kind:"file",hash:m.hash,size:m.size},i,n),await o.verify()}await o.verify();let l=await xt({root:e,directory:t,label:`Native Archive content directory ${ai.relative(e,t)||"."}`,maxEntries:n.maxEntries});if(TE(l.entries)!==s)throw new Error(`Native Archive content directory changed while reading: ${ai.relative(e,t)||"."}`);await Promise.all([o.verify(),l.verify()])}async function HE(e,t={}){let r=$E(t);e=ai.resolve(e);let i=await ov.lstat(e);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`Native Archive move source must be a real directory: ${e}`);let n=[];await OE(e,e,n,{entryCount:0,totalBytes:0,manifestBytes:0},r,0);let o=JSON.stringify(n);if(Buffer.byteLength(o,"utf8")>r.maxManifestBytes)throw new Error(`Native Archive content manifest exceeds ${r.maxManifestBytes} bytes`);return F(`${IL}\0${o}`)}async function yr(e,t={}){let r=$E(t);e=ai.resolve(e);let i;try{i=await ov.lstat(e)}catch(n){if(n.code==="ENOENT")return null;throw n}if(i.isSymbolicLink())throw new Error(`Native Archive transaction path must not be a symlink or junction: ${e}`);if(i.isFile())return{kind:"file",hash:(await oe({root:ai.dirname(e),file:e,maxBytes:r.maxFileBytes,label:`Native Archive transaction file ${ai.basename(e)}`})).hash};if(i.isDirectory())return{kind:"directory",hash:await HE(e,r)};throw new Error(`Native Archive transaction path has an unsupported file type: ${e}`)}ue();ar();import{promises as ft}from"node:fs";import Oe from"node:path";Q();yt();Mn();var cv=16*1024*1024,jL=256*1024,$L=16*1024,Nc="comet.native.archive-cas.v1";function OL(e,t){let r="runtime/",i=t.startsWith(r),n=i?e.runtimeDir:e.nativeRoot,a=i?t.slice(r.length):t,o=Oe.resolve(n,...a.split("/"));if(!D(n,o))throw new Error(`Unsafe Native Archive transaction ref: ${t}`);return o}async function ze(e,t){let r=OL(e,t);return T($(e,r),r)}function ln(e,t,r="file"){return t===null?e===null:e?.kind===r&&e.hash===t}function ko(e){return e===null?"missing":`${e.kind}:${e.hash}`}async function kt(e){let t=await yr(e.target);if(!ln(t,e.expectedHash,e.expectedKind))throw new Error(`${e.label} content changed: expected ${e.expectedHash??"missing"}, got ${ko(t)}`);return t}async function lv(e,t){let r=await xr(e,t),i=await oe({root:e.runtimeDir,file:r.journal,maxBytes:jL,label:`Native Archive transaction journal ${t}`}),n=Cu(JSON.parse(i.bytes.toString("utf8")));if(n.id!==t)throw new Error(`Invalid Native Archive transaction journal: ${t}`);return n}async function Sd(e,t,r){let i=Cu({...t,status:r}),n=await xr(e,i.id);return await re(n.journal,i,{containedRoot:e.runtimeDir}),i}function Ed(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}function DE(e){return{...Ed(e),ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function un(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs}function HL(e,t){return un(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function ne(e){try{return await ft.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Lr(e){let t=await ft.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);let r=DE(t),i=await oe({root:$(e.paths,e.file),file:e.file,maxBytes:cv,label:e.label}),n=await ft.lstat(e.file);if(!n.isFile()||n.isSymbolicLink()||!HL(r,DE(n))||i.hash!==e.expectedHash)throw new Error(`${e.label} content changed or object identity changed while binding`);return{identity:Ed(n),size:i.size}}function DL(e,t,r,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Archive CAS ${t.id} ${r} 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} ${r} record has an invalid shape`);let o=n.identity;if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Archive CAS ${t.id} ${r} identity must be an object`);let s=o;if(Object.keys(s).sort().join(",")!=="birthtimeMs,dev,ino")throw new Error(`Archive CAS ${t.id} ${r} 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} ${r} identity ${c} is invalid`);if(n.schema!==Nc||n.operationId!==t.id||n.role!==r||n.hash!==i)throw new Error(`Archive CAS ${t.id} ${r} record is not transaction-bound`);return{schema:Nc,operationId:t.id,role:r,hash:i,identity:{dev:s.dev,ino:s.ino,birthtimeMs:s.birthtimeMs}}}async function Mr(e,t,r,i){let n=await xr(e,t.id),a=Oe.join(n.backups,".cas"),o=`.${Oe.basename(i)}.comet-archive-cas-${t.id}-${r.id}`,s={directory:a,originalRecord:Oe.join(a,`${r.id}.original.json`),postRecord:Oe.join(a,`${r.id}.post.json`),candidate:Oe.join(a,`${r.id}.candidate`),originalQuarantine:Oe.join(Oe.dirname(i),`${o}.original`),rollbackQuarantine:Oe.join(Oe.dirname(i),`${o}.rollback`)};return await Promise.all(Object.values(s).map(c=>T($(e,c),c))),s}async function Kt(e){if(!await ne(e.file))return null;let t=await oe({root:e.paths.runtimeDir,file:e.file,maxBytes:$L,label:`Archive CAS ${e.operation.id} ${e.role} record`});return DL(JSON.parse(t.bytes.toString("utf8")),e.operation,e.role,e.expectedHash)}async function Pd(e){let t=await Kt(e);if(t){if(!un(t.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} object identity changed`);return t}await Cr({root:e.paths.runtimeDir,directory:Oe.dirname(e.file),label:`Archive CAS ${e.operation.id} records`});let r={schema:Nc,operationId:e.operation.id,role:e.role,hash:e.expectedHash,identity:e.identity};try{await re(e.file,r,{containedRoot:e.paths.runtimeDir,exclusive:!0})}catch(n){if(n.code!=="EEXIST")throw n}let i=await Kt(e);if(!i||!un(i.identity,e.identity))throw new Error(`Archive CAS ${e.operation.id} ${e.role} record changed`);return i}async function Te(e){let t=await Lr({paths:e.paths,file:e.file,expectedHash:e.record.hash,label:e.label});if(!un(e.record.identity,t.identity))throw new Error(`${e.label} object identity changed`)}async function LL(e){let t=await Lr({paths:e.paths,file:e.file,expectedHash:e.expectedHash,label:e.label}),r=await Pd({paths:e.paths,file:e.recordFile,operation:e.operation,role:e.role,expectedHash:e.expectedHash,identity:t.identity});return await Te({paths:e.paths,file:e.file,operation:e.operation,record:r,label:e.label}),r}async function ML(e){if(!await ne(e.quarantine)||await ne(e.target))return;let t=await fr({root:$(e.paths,e.target),directory:Oe.dirname(e.target),label:`Archive CAS ${e.operation.id} quarantine restoration`});await t.verify();try{await ft.link(e.quarantine,e.target)}catch(n){if(n.code==="EEXIST")return;throw n}await t.verify();let[r,i]=await Promise.all([ft.lstat(e.quarantine),ft.lstat(e.target)]);if(!un(Ed(r),Ed(i)))throw new Error(`Archive CAS ${e.operation.id} could not restore quarantined content`);await ft.unlink(e.quarantine),await t.verify()}async function BE(e){if(await ne(e.quarantine)){await Te({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`});return}let t=await fr({root:$(e.paths,e.target),directory:Oe.dirname(e.target),label:`Archive ${e.phase} target ${e.operation.target}`});await Te({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 Te({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive ${e.phase} target ${e.operation.target}`});try{await ft.rename(e.target,e.quarantine),await t.verify(),await Te({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive ${e.phase} quarantine ${e.operation.target}`})}catch(r){throw await ML(e),new Error(`Archive ${e.phase} target ${e.operation.target} changed during quarantine`,{cause:r})}await e.hooks?.afterArchiveTargetQuarantined?.(e.phase,e.operation,e.quarantine)}async function Yn(e){if(!await ne(e.file))return;await Te(e);let t=await fr({root:$(e.paths,e.file),directory:Oe.dirname(e.file),label:e.label});await t.verify(),await Te(e),await ft.unlink(e.file),await t.verify()}async function LE(e,t,r){if(!t.backup||t.expectedTargetHash===null)return;let i=await ze(e,t.target),n=await ze(e,t.backup),a=await yr(n);if(a!==null){if(!ln(a,t.expectedTargetHash))throw new Error(`Archive transaction backup content changed: ${t.backup}`);return}await kt({target:i,expectedHash:t.expectedTargetHash,label:`Archive transaction target ${t.target}`}),await Bi({sourceRoot:$(e,i),source:i,targetRoot:$(e,n),target:n,maxBytes:cv,label:`Archive transaction backup ${t.backup}`,expectedHash:t.expectedTargetHash,expectedTargetHash:null,exclusive:!0,hooks:{afterParentChainCaptured:()=>r?.afterProtectedCopySourceParentCaptured?.("backup",t.target)}}),await kt({target:n,expectedHash:t.expectedTargetHash,label:`Archive transaction backup ${t.backup}`})}async function VE(e){let t=e.operation.expectedTargetHash;if(t===null)throw new Error(`Archive operation ${e.operation.id} has no original target to quarantine`);let r=await Mr(e.paths,e.journal,e.operation,e.target),i=await Kt({paths:e.paths,file:r.originalRecord,operation:e.operation,role:"original",expectedHash:t});if(await ne(r.originalQuarantine)){if(!i)throw new Error(`Archive apply quarantine ${e.operation.target} has no bound object identity`);return await Te({paths:e.paths,file:r.originalQuarantine,operation:e.operation,record:i,label:`Archive apply quarantine ${e.operation.target}`}),await LE(e.paths,e.operation,e.hooks),{record:i,quarantine:r.originalQuarantine}}if(!await ne(e.target))throw new Error(`Archive apply target ${e.operation.target} disappeared before quarantine`);return i??=await LL({paths:e.paths,file:e.target,recordFile:r.originalRecord,operation:e.operation,role:"original",expectedHash:t,label:`Archive apply target ${e.operation.target}`}),await Te({paths:e.paths,file:e.target,operation:e.operation,record:i,label:`Archive apply target ${e.operation.target}`}),await LE(e.paths,e.operation,e.hooks),await BE({paths:e.paths,operation:e.operation,phase:"apply",target:e.target,quarantine:r.originalQuarantine,record:i,hooks:e.hooks}),{record:i,quarantine:r.originalQuarantine}}async function ME(e){let t=await Mr(e.paths,e.journal,e.operation,e.target);return await ne(t.candidate)?(await Lr({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`}),t.candidate):(await Cr({root:e.paths.runtimeDir,directory:t.directory,label:`Archive CAS ${e.operation.id} records`}),await Bi({sourceRoot:$(e.paths,e.staged),source:e.staged,targetRoot:e.paths.runtimeDir,target:t.candidate,maxBytes:cv,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 FL(e){let t=e.operation.stagedHash,r=await Mr(e.paths,e.journal,e.operation,e.target),i=await Kt({paths:e.paths,file:r.postRecord,operation:e.operation,role:"post",expectedHash:t});if(i&&await ne(e.target))return await Te({paths:e.paths,file:e.target,operation:e.operation,record:i,label:`Archive write target ${e.operation.target}`}),await ne(r.candidate)&&await Yn({paths:e.paths,file:r.candidate,operation:e.operation,record:i,label:`Archive write candidate ${e.operation.target}`}),i;if(await ne(e.target)){let c=await ME(e),l=await Lr({paths:e.paths,file:c,expectedHash:t,label:`Archive write candidate ${e.operation.target}`}),u=await Lr({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!un(l.identity,u.identity))throw new Error(`Archive write target ${e.operation.target} is occupied by an external object`);return i=await Pd({paths:e.paths,file:r.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:u.identity}),await Yn({paths:e.paths,file:c,operation:e.operation,record:i,label:`Archive write candidate ${e.operation.target}`}),i}let n=await ME(e),a=await Lr({paths:e.paths,file:n,expectedHash:t,label:`Archive write candidate ${e.operation.target}`});await Cr({root:$(e.paths,e.target),directory:Oe.dirname(e.target),label:`Archive write target ${e.operation.target}`});let o=await fr({root:$(e.paths,e.target),directory:Oe.dirname(e.target),label:`Archive write target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("apply",e.operation,e.target),await o.verify(),await Te({paths:e.paths,file:n,operation:e.operation,record:{schema:Nc,operationId:e.operation.id,role:"post",hash:t,identity:a.identity},label:`Archive write candidate ${e.operation.target}`});try{await ft.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 Lr({paths:e.paths,file:e.target,expectedHash:t,label:`Archive write target ${e.operation.target}`});if(!un(a.identity,s.identity))throw new Error(`Archive write target ${e.operation.target} changed during install`);return i=await Pd({paths:e.paths,file:r.postRecord,operation:e.operation,role:"post",expectedHash:t,identity:s.identity}),await Yn({paths:e.paths,file:n,operation:e.operation,record:i,label:`Archive write candidate ${e.operation.target}`}),i}async function BL(e,t,r,i){let n=await ze(e,r.target),a=await ze(e,r.staged);if(await kt({target:a,expectedHash:r.stagedHash,label:`Archive transaction staged file ${r.staged}`}),r.expectedTargetHash!==null){let o=await Mr(e,t,r,n);(!await Kt({paths:e,file:o.postRecord,operation:r,role:"post",expectedHash:r.stagedHash})||!await ne(n))&&await VE({paths:e,journal:t,operation:r,target:n,hooks:i})}else{let o=await yr(n);if(o!==null&&!ln(o,r.stagedHash))throw new Error(`Archive transaction target ${r.target} changed before create: ${ko(o)}`)}await FL({paths:e,journal:t,operation:r,staged:a,target:n,hooks:i}),await kt({target:n,expectedHash:r.stagedHash,label:`Archive transaction target ${r.target}`})}async function VL(e,t,r,i){let n=await ze(e,r.target);await VE({paths:e,journal:t,operation:r,target:n,hooks:i}),await kt({target:n,expectedHash:null,label:`Archive transaction target ${r.target}`})}async function qL(e,t){let r=await ze(e,t.source),i=await ze(e,t.target),[n,a]=await Promise.all([yr(r),yr(i)]);if(!(n===null&&ln(a,t.expectedSourceHash,"directory"))){if(!ln(n,t.expectedSourceHash,"directory")||a!==null)throw new Error(`Archive transaction move ${t.id} content changed: source=${ko(n)}, target=${ko(a)}`);await ft.mkdir(Oe.dirname(i),{recursive:!0}),await ft.rename(r,i),await kt({target:i,expectedHash:t.expectedSourceHash,expectedKind:"directory",label:`Archive transaction move target ${t.target}`})}}async function WL(e,t,r,i){return r.type==="write"?BL(e,t,r,i):r.type==="remove"?VL(e,t,r,i):qL(e,r)}function zL(e){let t=0,r=!1,i=[];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"){r=!0;continue}if(!r)throw new Error(`Native Archive transaction ${e.journal.id} completed an operation before it started`);i.push(a.id),t+=1,r=!1}return i}async function JL(e,t,r,i){let n=await ze(e,r.target);if(r.type==="write"){let a=await ze(e,r.staged);await kt({target:a,expectedHash:r.stagedHash,label:`Completed Archive staged file ${r.staged}`});let o=await Mr(e,t,r,n),s=await Kt({paths:e,file:o.postRecord,operation:r,role:"post",expectedHash:r.stagedHash});if(!s)throw new Error(`Completed Archive target ${r.target} has no CAS identity`);if(await Te({paths:e,file:n,operation:r,record:s,label:`Completed Archive target ${r.target}`}),r.expectedTargetHash!==null){await kt({target:await ze(e,r.backup),expectedHash:r.expectedTargetHash,label:`Completed Archive backup ${r.backup}`});let c=await Kt({paths:e,file:o.originalRecord,operation:r,role:"original",expectedHash:r.expectedTargetHash});if(!c)throw new Error(`Completed Archive target ${r.target} has no original CAS identity`);if(await ne(o.originalQuarantine))await Te({paths:e,file:o.originalQuarantine,operation:r,record:c,label:`Completed Archive original quarantine ${r.target}`});else if(!i)throw new Error(`Completed Archive original quarantine ${r.target} disappeared`)}return}if(r.type==="remove"){await kt({target:n,expectedHash:null,label:`Completed Archive target ${r.target}`}),await kt({target:await ze(e,r.backup),expectedHash:r.expectedTargetHash,label:`Completed Archive backup ${r.backup}`});let a=await Mr(e,t,r,n),o=await Kt({paths:e,file:a.originalRecord,operation:r,role:"original",expectedHash:r.expectedTargetHash});if(!o)throw new Error(`Completed Archive remove ${r.target} has no original CAS identity`);if(await ne(a.originalQuarantine))await Te({paths:e,file:a.originalQuarantine,operation:r,record:o,label:`Completed Archive original quarantine ${r.target}`});else if(!i)throw new Error(`Completed Archive original quarantine ${r.target} disappeared`);return}i||(await kt({target:await ze(e,r.source),expectedHash:null,label:`Completed Archive move source ${r.source}`}),await kt({target:n,expectedHash:r.expectedSourceHash,expectedKind:"directory",label:`Completed Archive move target ${r.target}`}))}async function qE(e,t,r){let i=t.status==="prepared"?await Sd(e,t,"applying"):t;if(i.status!=="applying")throw new Error(`Native Archive transaction ${i.id} cannot apply from ${i.status}`);let n=await qi(e,i.id),a=zL({journal:i,events:n}),o=new Set(a),s=n.some(l=>l.type==="archive-finalization-started");for(let l of i.operations.slice(0,a.length))await JL(e,i,l,s);let c=o.size;for(let l of i.operations)o.has(l.id)||(l.id==="archive-change"&&await r?.beforeArchiveChangeMove?.(l),await Wt(e,i.id,"operation-started",l.id),await WL(e,i,l,r),await Wt(e,i.id,"operation-completed",l.id),c+=1,await r?.afterOperation?.(l,c));return i=await lv(e,i.id),i}async function GL(e){try{return await Te(e),!0}catch{return!1}}async function UL(e){await Te({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});let t=await fr({root:$(e.paths,e.target),directory:Oe.dirname(e.target),label:`Archive rollback target ${e.operation.target}`});await e.hooks?.beforeArchiveTargetInstall?.("rollback",e.operation,e.target),await t.verify(),await Te({paths:e.paths,file:e.quarantine,operation:e.operation,record:e.record,label:`Archive rollback original quarantine ${e.operation.target}`});try{await ft.link(e.quarantine,e.target)}catch(r){throw r.code==="EEXIST"?new Error(`Archive rollback target ${e.operation.target} was created before exclusive restore`,{cause:r}):r}await t.verify(),await e.hooks?.afterArchiveTargetInstalled?.("rollback",e.operation,e.target),await Te({paths:e.paths,file:e.target,operation:e.operation,record:e.record,label:`Archive rollback target ${e.operation.target}`})}async function sv(e){if(e.operation.type!=="write")return;let t=await Mr(e.paths,e.journal,e.operation,e.target);if(!await ne(t.candidate))return;let r=await Lr({paths:e.paths,file:t.candidate,expectedHash:e.operation.stagedHash,label:`Archive write candidate ${e.operation.target}`});await Yn({paths:e.paths,file:t.candidate,operation:e.operation,record:{schema:Nc,operationId:e.operation.id,role:"post",hash:e.operation.stagedHash,identity:r.identity},label:`Archive write candidate ${e.operation.target}`})}async function KL(e,t,r,i){let n=await ze(e,r.target),a=await Mr(e,t,r,n),o=r.expectedTargetHash,s=o===null?null:await Kt({paths:e,file:a.originalRecord,operation:r,role:"original",expectedHash:o}),c=r.type==="write"?await Kt({paths:e,file:a.postRecord,operation:r,role:"post",expectedHash:r.stagedHash}):null;if(r.type==="write"&&!c&&await ne(a.candidate)&&await ne(n)){let l=await Lr({paths:e,file:a.candidate,expectedHash:r.stagedHash,label:`Archive write candidate ${r.target}`}),u=await Lr({paths:e,file:n,expectedHash:r.stagedHash,label:`Archive rollback target ${r.target}`});un(l.identity,u.identity)&&(c=await Pd({paths:e,file:a.postRecord,operation:r,role:"post",expectedHash:r.stagedHash,identity:u.identity}))}if(await ne(a.rollbackQuarantine)){if(!c)throw new Error(`Archive rollback quarantine ${r.target} has no CAS identity`);await Te({paths:e,file:a.rollbackQuarantine,operation:r,record:c,label:`Archive rollback quarantine ${r.target}`})}if(await ne(n)&&!(s!==null&&await GL({paths:e,file:n,operation:r,record:s,label:`Archive rollback target ${r.target}`}))){if(!c){if(!s){let u=await yr(n);if(ln(u,o)){await sv({paths:e,journal:t,operation:r,target:n});return}}throw new Error(`Archive rollback target ${r.target} is occupied by an external object`)}await BE({paths:e,operation:r,phase:"rollback",target:n,quarantine:a.rollbackQuarantine,record:c,hooks:i})}if(o===null){if(await ne(n))throw new Error(`Archive rollback create target ${r.target} could not be removed`)}else if(!await ne(n)){if(!s||!await ne(a.originalQuarantine))throw new Error(`Archive rollback original target ${r.target} cannot be recovered safely`);await UL({paths:e,operation:r,target:n,quarantine:a.originalQuarantine,record:s,hooks:i})}s&&await ne(a.originalQuarantine)&&await Yn({paths:e,file:a.originalQuarantine,operation:r,record:s,label:`Archive rollback original quarantine ${r.target}`}),c&&await ne(a.rollbackQuarantine)&&await Yn({paths:e,file:a.rollbackQuarantine,operation:r,record:c,label:`Archive rollback quarantine ${r.target}`}),await sv({paths:e,journal:t,operation:r,target:n}),await kt({target:n,expectedHash:o,label:`Archive rollback target ${r.target}`})}async function YL(e,t){let r=await ze(e,t.source),i=await ze(e,t.target),[n,a]=await Promise.all([yr(r),yr(i)]);if(!(ln(n,t.expectedSourceHash,"directory")&&a===null)){if(n!==null||!ln(a,t.expectedSourceHash,"directory"))throw new Error(`Archive rollback move ${t.id} content changed: source=${ko(n)}, target=${ko(a)}`);await ft.mkdir(Oe.dirname(r),{recursive:!0}),await ft.rename(i,r)}}async function WE(e,t,r){let i=await qi(e,t.id);if(i.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 Sd(e,t,"rolling-back");await Wt(e,n.id,"rollback-started");let a=new Set(i.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 YL(e,o):await KL(e,n,o,r));return await Wt(e,n.id,"rollback-completed"),n=await Sd(e,n,"rolled-back"),n}async function FE(e,t,r){let i=await ze(e,r.target);if(r.type==="write"){let n=await Mr(e,t,r,i),a=await Kt({paths:e,file:n.postRecord,operation:r,role:"post",expectedHash:r.stagedHash});if(!a)throw new Error(`Archive commit target ${r.target} has no CAS identity`);await Te({paths:e,file:i,operation:r,record:a,label:`Archive commit target ${r.target}`});return}await kt({target:i,expectedHash:null,label:`Archive commit target ${r.target}`})}async function XL(e,t){for(let r of t.operations){if(r.type==="move")continue;let i=await ze(e,r.target),n=await Mr(e,t,r,i);if(await ne(n.rollbackQuarantine))throw new Error(`Archive commit found an unfinished rollback for ${r.target}`);if(await FE(e,t,r),r.expectedTargetHash!==null){let a=await Kt({paths:e,file:n.originalRecord,operation:r,role:"original",expectedHash:r.expectedTargetHash});if(!a)throw new Error(`Archive commit target ${r.target} has no original CAS identity`);await ne(n.originalQuarantine)&&await Yn({paths:e,file:n.originalQuarantine,operation:r,record:a,label:`Archive commit original quarantine ${r.target}`})}await sv({paths:e,journal:t,operation:r,target:i})}for(let r of t.operations)r.type!=="move"&&await FE(e,t,r)}async function Rd(e,t,r){return r==="commit"&&await XL(e,t),await Wt(e,t.id,r),r==="commit"?Sd(e,t,"committed"):t}ke();ue();Nn();ke();ii();var IY=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});pr();Tn();et();Q();yt();ys();import{promises as QL}from"fs";import ZL from"path";var uv="comet.selection.v2",eM=16*1024;function Cd(e){return ZL.join(e,".comet","current-change.json")}function tM(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function zE(e){return e===null||typeof e=="string"}function rM(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!tM(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&&!zE(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:uv,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==uv)throw new Error(`current change selection schema must be ${uv}`);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(!zE(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 dv(e){let t;try{let i=Cd(e),{bytes:n}=await An(i,eM,{label:"current change selection"});t=n.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...rM(t)}}async function JE(e){await QL.rm(Cd(e),{force:!0})}async function GE(e,t,r){let i=await dv(e);return i.status!=="selected"||i.selection.workflow!==t||i.selection.change!==r?!1:(await JE(e),!0)}ke();ot();et();Lt();ue();import{promises as ra}from"node:fs";import pn from"node:path";Ft();Xe();Eo();So();ke();mv();Pr();js();Sc();_d();function jM(e){return e.state_version+1}function $M(e){return e.map(t=>({...t,result:"pending",reason:null}))}function OM(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:Gr(e.summary),completed_at:e.completedAt}}function xv(e){let t=Qe(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=(e.now??new Date).toISOString(),i=Oi(t,OM({state:t,outcome:"recovery",summary:e.reason,completedAt:r})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?$M(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return Qe({...i,phase:"build",status:"active",state_version:jM(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"}})}ue();_s();import{promises as RP}from"node:fs";import Rc from"node:path";function Fd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Bd(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Fr(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function PP(e,t){return e===null?null:Fr(e,t)}function qd(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function HM(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 DM(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Vd(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Av(e,t){if(e===null)return null;let r=Fr(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function _v(e,t){let r=Fr(e,t);if(!Rc.isAbsolute(r))throw new Error(`${t} must be absolute`);return Rc.resolve(r)}function LM(e,t){let r=`Native local checks[${t}]`,i=Fd(e,r);if(Bd(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((l,u)=>Fr(l,`${r}.argv[${u}]`,!0)),a=Vd(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Av(i.startedAt,`${r}.startedAt`),s=Av(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=qd(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:Fr(i.id,`${r}.id`),name:Fr(i.name,`${r}.name`),operationId:Fr(i.operationId,`${r}.operationId`),status:a,repeatable:DM(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:qd(i.executionCount,`${r}.executionCount`),argv:n,cwd:_v(i.cwd,`${r}.cwd`),exitCode:HM(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Fr(i.log,`${r}.log`)}}function Iv(e){let t="Native local execution state",r=Fd(e,t);if(Bd(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==As)throw new Error(`Native local execution schema must be ${As}`);let i=Fd(r.workspace,"Native local workspace");Bd(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Fd(r.execution,"Native local execution");Bd(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Av(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Fr(o.operationId,"Native local execution.operationId"),stage:Vd(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Vd(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:PP(o.executionId,"Native local execution.executionId"),status:Vd(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:qd(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(LM);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:As,change:Fr(r.change,"Native local change"),basedOnStateVersion:qd(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:_v(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:_v(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:PP(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function fn(e){return Iv({schema:As,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:Rc.resolve(e.projectRoot),worktreeRoot:Rc.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function Wd(e){let t;try{t=await RP.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return Iv(r)}async function oi(e,t,r={}){let i=Iv(t);await RP.mkdir(Rc.dirname(e),{recursive:!0}),await re(e,i,r)}et();pu();Pr();La();js();Sc();_d();ue();Nn();Sc();import{promises as MM}from"node:fs";function hn(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
|
|
206
|
+
`).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function si(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function FM(e){return e.archived?mt(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?mt(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?mt(e.language,"Verification passed; ready to archive","验收通过,可归档"):mt(e.language,"Verification passed","验收通过")}function BM(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?mt(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?FM(e):e.verification_result==="blocked"?mt(t,"Blocked","已阻塞"):e.verification_result==="fail"?mt(t,"Failed","未通过"):mt(t,"Pending","待处理")}function VM(e){if(e.verification?.assurance==="semantic-verification-unavailable")return mt(e.language,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查");if(e.verification_result==="fail")return mt(e.language,"Fix unresolved acceptance criteria and verify again","修复未通过的验收项后重新验证");if(e.verification_result==="blocked")return mt(e.language,"Resolve the reported blockers and resume verification","解决报告中的阻塞项后恢复验证");let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===kc?kc:"host-attested"),r=t===kc&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":r?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","skill-coordinated":r?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function qM(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,i=d=>kf(r,d),n=(d,f)=>mt(r,d,f),a=e.acceptance.map(d=>`| ${si(d.id)} | ${si(d.result)} | ${si(d.source)} | ${si(d.text)} | ${si(hn(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(hn).join(" ");return`| ${si(hn(d.name))} | ${si(f||"—")} | ${si(d.cwd_ref)} | ${d.status} | ${d.exit_code??"—"} | ${d.duration_ms} ms |`})].join(`
|
|
208
208
|
`),s=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(d=>`- **${d.owner}**: ${hn(d.reason)}${d.acceptance_ids.length>0?` (acceptance: ${d.acceptance_ids.join(", ")})`:""} — next: \`${d.resolution_action}\``).join(`
|
|
209
209
|
`),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(d=>`- ${hn(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(", ")||"—"} | ${
|
|
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(", ")||"—"} | ${si(hn(d.summary))} | ${d.completed_at} |`)].join(`
|
|
211
211
|
`),u=t?.finalVerification.layers?`
|
|
212
212
|
## ${n("Supervisor evidence layers","Supervisor 分层证据")}
|
|
213
213
|
|
|
@@ -261,16 +261,16 @@ ${e.history_overflow.dropped_entries>0?`${n("Earlier history entries folded into
|
|
|
261
261
|
`:""}## ${i("conclusion")}
|
|
262
262
|
|
|
263
263
|
${hn(e.verification.summary)}
|
|
264
|
-
`}function WM(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function zd(e){let t;try{t=await MM.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=WM(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function Jd(e){await ge(e.file,qM(e.state,e.supervisor))}Q();Nn();ri();ot();var CP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,zM="comet-state.yaml",JM="state.json",n9=zc("en");function Yt(e,t){if(!CP.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=pn.join(e.changesDir,t);if(!D(e.changesDir,r))throw new Error("Native change path escaped");return r}function Ht(e,t){return pn.join(Yt(e,t),zM)}function mn(e,t){return pn.join(Ye(e,t),JM)}async function vn(e,t){try{let r=await ra.readFile(Ht(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function xP(e){return ae(e).currentBranch}async function si(e,t){return Be(Ht(e,t))}async function AP(e){let t=await Hi({file:Ht(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=pn.join(Yt(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,r),await ra.rm(r,{force:!0})}return t}async function GM(e){let t=Yt(e.paths,e.state.name),r=pn.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await ra.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!CP.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=pn.join(t,...s.split("/")),l=await ra.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=pn.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let f=await ra.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(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function UM(e){let t=Yt(e.paths,e.state.name),r=await te({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(dm(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let a of e.specChanges){if(a.source===null){n.push({...a,contentHash:null});continue}let o=await te({root:t,ref:a.source,maxBytes:null,includeHash:!1});i.push({capability:a.capability,source:o.ref,markdown:o.text}),n.push({...a,contentHash:O("comet.native.shape-artifact-content.v1",o.text)})}return{acceptance:hu({briefMarkdown:r.text,specs:i}),formalHash:O("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:O("comet.native.shape-artifact-content.v1",r.text)},specs:n})}}function KM(e){return O("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function _P(e){let t=await GM(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:l})=>l)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((l,u)=>{let d=e.state.spec_changes[u];return d!==void 0&&l.capability===d.capability&&l.source===d.source&&(l.operation===d.operation||r?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await UM({...e,specChanges:t})}catch{return{drifted:!0,reason:"Native Shape artifacts changed or became invalid"}}let{acceptance:a}=n,o=e.state.acceptance.map(({source:l,text:u})=>({source:l,text:u}));if(!ZN(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await ea({changeDir:Yt(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:Ld({...e.state,acceptance:a})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return e.state.phase==="shape"&&e.state.status==="await-user"&&e.state.loop.next_action==="confirm-shape"&&e.state.shape_confirmation_hash===void 0?{drifted:!0,reason:"Native Shape confirmation fingerprint is missing"}:e.state.shape_confirmation_hash!==void 0&&KM({formalHash:n.formalHash,childrenHash:s?.hash??null,coordinationMode:e.state.coordination_mode})!==e.state.shape_confirmation_hash?{drifted:!0,reason:"Native Shape artifacts changed"}:(s?Md({acceptance:a,children:s.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function IP(e){let t=await si(e.paths,e.name),r=await Da(e.paths,{kind:"archive",change:e.name}),i=r?.kind==="archive"?r:null;if(!i&&(t.archived||t.verification===null||t.verification_result!=="pass"))return{state:t,action:"none"};let n=await Ot(e.paths,e.name);if(i&&n?.finalVerification.status==="pending"){if(i.journal.status!=="prepared"||i.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await ra.rm(i.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||n?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=uP(n);if(i||a.stateVersion!==n.stateVersion){let o=await YM({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; the final full verification will resume automatically."});return i&&await ra.rm(i.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await Xn(e.paths,dP(n,t)),{state:t,action:"recorded-final-verification"}}async function TP(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...Oi(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Jr(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await AP({paths:e.paths,previous:t,next:i});return await ai(mn(e.paths,t.name),fn({portableState:n,projectRoot:e.paths.projectRoot,branch:xP(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function YM(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);if(t.verification===null||t.verification_result!=="pass")throw new Error("Native Supervisor recovery requires a persisted final verification pass");let i={...Oi(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Jr(e.reason),completed_at:new Date().toISOString()}),phase:"verify",status:"active",state_version:t.state_version+1,acceptance:t.acceptance.map(a=>({...a,result:"pending",reason:null})),blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}},n=await AP({paths:e.paths,previous:t,next:i});return await ai(mn(e.paths,t.name),fn({portableState:n,projectRoot:e.paths.projectRoot,branch:xP(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Gd(e){if(e.state.verification===null)return"not-applicable";let t=pn.join(Yt(e.paths,e.state.name),"verification.md");return await zd({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await Jd({file:t,state:e.state}),"rebuilt")}async function jP(e){let t=await si(e.paths,e.name),r=mn(e.paths,e.name);try{let i=await Wd(r);return i===null?{state:t,local:null,localStatus:"missing"}:i.change!==t.name||i.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:i,localStatus:"available"}}catch(i){return i.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}var f9=16*1024;async function Ud(e){let t=await dv(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Uu(t.selection.change),t.selection)}function $P(e){return Cd(e.projectRoot)}async function Cc(e,t){return await Ta(e.projectRoot),GE(e.projectRoot,"native",t)}Mn();var B9=16*1024*1024,Kd=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},xc=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function HP(e,t){let r=t.operations.find(i=>i.id==="archive-change");if(!r||r.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return Po.resolve(e.nativeRoot,...r.target.split("/"))}async function DP(e,t,r){let i=await qi(e,t.id);if(i.some(v=>v.type==="archive-finalized"))return;let n=i.some(v=>v.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let v=t.operations.find(N=>N.id==="archive-change");if(!v||v.type!=="move"||!v.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let g=await wr(HP(e,t));if(g?.kind!=="directory"||g.hash!==v.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=HP(e,t),o=Po.join(a,Le),s=await Vk(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=M(e,s.name),l=await Ve(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 v=fg(Or,l,new Set,Mm,void 0);if(!v.action)throw new Error(v.reason??"Native archive produced no action");u=hg(Or,v.state,{actionId:v.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},Mm,void 0)}let d=F(`archive:${t.id}:${s.name}`),f=await dt(c,u.trajectoryRef),h=f.filter(v=>v.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(h.length>1||h.some(v=>v.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let m=h.find(v=>v.type==="state_transitioned"),p={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(m&&t.schema==="comet.native.transaction.v2"&&(!XM(m.data,p)||m.runId!==u.runId||m.timestamp!==t.createdAt||m!==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 Rd(e,t,"archive-finalization-started"),await r?.afterFinalizationStarted?.(t)):await qa(e,t,"archive-finalization-started")),!s.archived){let v={...s,archived:!0};await Bk(o,v)}m||(m=await rn({changeDir:c,run:u,type:"state_transitioned",data:p,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await Un({changeDir:c,run:u,trajectoryOffset:m.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await Vn(c,u),await Cc(e,s.name),t.schema==="comet.native.transaction.v2"?await Rd(e,t,"archive-finalized"):await qa(e,t,"archive-finalized")}async function Tv(e,t){let r=Ye(e,t);try{let i=await OP.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`Native Runtime cleanup target is not a real directory: ${r}`);return await T(e.runtimeDir,r),await OP.rm(r,{recursive:!0,force:!0}),null}catch(i){return i.code==="ENOENT"?null:`Archived change ${t}, but local Runtime cleanup failed: ${i.message}`}}async function QM(e,t,r){if(t.schema==="comet.native.transaction.v2"){if(!(await qi(e,t.id)).some(c=>c.type==="operation-started")){let c=await kd({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new xc(c,"Native Archive facts changed before the first transaction operation")}let o=await qE(e,t,{...r,beforeArchiveChangeMove:async c=>{await r?.beforeArchiveChangeMove?.(c);let l=await We(e,t.change),u=await bd({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 DP(e,o,r);let s=await Rd(e,o,"commit");return{journal:s,runtimeCleanupWarning:await Tv(e,s.change)}}let i=await Rb(e,t);await DP(e,i,r);let n=await qa(e,i,"commit");return{journal:n,runtimeCleanupWarning:n.change?await Tv(e,n.change):null}}function ZM(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(Po.resolve(t.projectRoot)!==Po.resolve(e.projectRoot)||Po.resolve(t.nativeRoot)!==Po.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function LP(e){return de(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await ji(e.paths,"archive",`recover archive ${e.transactionId}`);try{let r=await At(e.paths,e.transactionId),i=r.schema==="comet.native.transaction.v2"?await lv(e.paths,e.transactionId):r;return ZM(e.paths,i),i.status==="committed"?(i.change&&await Tv(e.paths,i.change),i):i.status==="rolled-back"?i:e.strategy==="continue"?(await QM(e.paths,i)).journal:i.schema==="comet.native.transaction.v2"?WE(e.paths,i):Au(e.paths,i)}finally{await $i(t)}},{allowedTransactionId:e.transactionId})}ke();ot();import{promises as pF}from"fs";xs();Xe();ke();Ya();Q();Ui();Js();async function MP(e,t){let r=[],i=M(e,t.name),n=Ii(i,_t.stateRef),a;try{a=await Ve(i)}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")&&r.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),r;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&&r.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")&&r.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&r.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=Ii(i,a.trajectoryRef),s=await Qa(e,t.name);if(s.status==="repairable")return r.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}),r;if(s.status==="invalid")return r.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),r;let c;try{if(c=await dt(i,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 r.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),r}let l=Ii(i,a.checkpointRef);try{let u=await Xa(i,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&r.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):r.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){r.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return r}Fn();Ar();var eF=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function tF(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function rF(e){return e?e.map(tF).join(" "):null}function iF(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(r=>{if(r.startsWith('"')&&r.endsWith('"'))try{return JSON.parse(r)}catch{return r.slice(1,-1)}return r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r})}function Xt(e,t,r,i={}){return{input:e,flags:t,required:i.required??!0,placeholder:r,...i.choices?{choices:i.choices}:{},...i.repeatable?{repeatable:!0}:{},...i.alternativeGroup?{alternativeGroup:i.alternativeGroup}:{}}}function nF(e){return e.map(t=>Xt(t,[],null))}function aF(e){let t=["comet","native","next",e.name,"--summary","<summary>"],r=[Xt("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),r.push(Xt("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:r};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),r.push(Xt("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),Xt("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let i=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),i.push("shared-understanding-confirmation"),r.push(Xt("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:i,inputOptions:r}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),r.push(Xt("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),Xt("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:r}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function nt(e,t){let r=t.commandArgs===void 0?iF(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?rF(r??null):t.command,commandArgs:r??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??nF(t.requiredInputs??[])}}function Yd(e){let r=(e.findings??[]).filter(d=>!Za(d.code)),i=r.find(d=>d.requiresUserDecision),n=r.find(d=>d.repairCommand!==null||eF.test(d.code)),a=r.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=r.find(d=>d.code==="repair-stagnation-stop"),s=r.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=r.find(d=>d.code==="runtime-missing"),l=[...new Set(r.map(d=>d.requiredAction))].sort();if(e.done)return nt(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return nt(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[Xt("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(i)return nt(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return nt(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return nt(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return nt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[Xt("summary",["--summary"],"<summary>")]});if(n)return nt(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 nt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[Xt("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return nt(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(r.length>0)return e.state.phase==="archive"?nt(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?nt(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):nt(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"),nt(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[Xt("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):nt(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return nt(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=aF(e.state);return nt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}ke();Q();Ar();import Ac from"path";var FP=8,oF={"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 sF(e){let t=oF[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"}:Za(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 cF(e,t,r){if(!r.path)return null;let i;if(Ac.isAbsolute(r.path)?i=Ac.resolve(r.path):/^(?:brief-|verification-|spec-source)/u.test(r.code)?i=Ac.resolve(se(e,t.name),...r.path.split(/[\\/]/u)):i=Ac.resolve(e.projectRoot,...r.path.split(/[\\/]/u)),!D(e.projectRoot,i))return null;let n=Ac.relative(e.projectRoot,i).replaceAll("\\","/");return n===""?".":n}function lF(e,t,r){return e==="next"?`comet native next ${t.name} --summary "<summary>"${r==="contract-changed-after-approval"||r==="shape-confirmation-required"||r==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function jv(e){return e.findings.map(t=>{let r=sF(t.code);return{code:t.code,message:t.message,severity:r.severity,path:cF(e.paths,e.state,t),requiredAction:r.requiredAction,retryCommand:lF(r.retry,e.state,t.code),repairCommand:r.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,r)=>{let i={error:0,warning:1,info:2};return i[t.severity]-i[r.severity]||t.code.localeCompare(r.code)||(t.path??"").localeCompare(r.path??"")||t.message.localeCompare(r.message)})}function $v(e){let t=[...new Set(e.map(r=>r.code))];return{total:e.length,errors:e.filter(r=>r.severity==="error").length,warnings:e.filter(r=>r.severity==="warning").length,info:e.filter(r=>r.severity==="info").length,requiresUserDecision:e.some(r=>r.requiresUserDecision),codes:t.slice(0,FP),truncated:t.length>FP}}var BP=240,VP=8,Xd=50;function qP(e){let t=Array.from(e);return t.length<=BP?e:`${t.slice(0,BP-1).join("")}…`}function uF(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function dF(e){let t=[...new Set(e.map(uF))],r={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,VP),reasonCount:e.length,codesTruncated:t.length>VP};return{inspection:r,inspectionDetails:{...r,reasons:e.slice(0,Xd),reasonsTruncated:e.length>Xd}}}async function WP(e){let t=null;try{let s=await sn(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:on(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:on(e.paths,e.state.name)}}let r=await NE({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),i=t?[t.code,...r.reasons]:r.reasons,n=dF(i);if(!r.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:an.maxArtifacts};let a={id:r.checkpoint.id,createdAt:r.checkpoint.createdAt,phase:r.checkpoint.phase,stateRevision:r.checkpoint.stateRevision,summary:qP(r.checkpoint.summary),nextAction:qP(r.checkpoint.nextAction),artifactCount:r.checkpoint.artifactCount},o=r.manifest?{...a,summary:r.checkpoint.summary,nextAction:r.checkpoint.nextAction,manifestHash:r.checkpoint.manifestHash,manifestRef:r.checkpoint.manifestRef,artifacts:r.manifest.artifacts,totalBytes:r.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:an.maxArtifacts}}Q();ri();Ui();ho();Xi();async function fF(e,t){let r=M(e,t.name),i=await Ve(r);if(!i||!t.run_id||i.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await Xa(r,i.checkpointRef);if(!n||n.runId!==i.runId||n.stateVersion!==i.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await dt(r,i.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:i.runId}}async function hF(e,t){let r=await fF(e,t);return{committed:r,latest:YS(r),history:KS(r)}}async function zP(e,t,r){if(t.phase!=="build"||t.verification_result!=="fail")return null;let i=await hF(e,t),n=i.latest;if(!n)return null;let a=i.history.filter(c=>c.kind==="failure"),o=a.length>=r,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:i.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:r,remainingVerifyFailures:Math.max(0,r-a.length)}}ri();Ar();yt();Q();var mF=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Ro=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function Ov(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function vF(e){return(await Ud(e))?.change??null}function gF(e,t,r=!1,i){return Yd({state:e,archiveReady:t,evidenceRetreat:r}).command}async function wF(e,t){let r=se(e,t.name),i=[...(await fm(r,t.brief)).findings,...(await Gk(e,t)).findings,...await MP(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Ka(e,t.name);if(n===null)i.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await Hu(e,n);a.complete||i.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){i.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await wo({changeDir:r,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&i.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){i.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await ii(e,t.name)&&i.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){i.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?i.push(...(await hm(r,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&i.push({code:"verification-report-missing",message:"Native change has no verification report"}),i}async function Hv(e,t,r){let i=await vF(e)===t,n=await Ss(e,t),a=await Ak(e,t),o;try{let y=await Ir(e,t);if(y.status==="migration-required"&&y.state)return{name:t,phase:y.state.phase,revision:"revision"in y.state?y.state.revision:null,approval:y.state.approval,verificationResult:y.state.verification_result,specChanges:y.state.spec_changes.length,selected:i,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:y.schema,migrationRequired:!0,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message};if(y.status!=="current"||!y.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,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:y.schema,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message??`Native change ${t} is incompatible`};o=y.state}catch(y){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,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:y.message}}if(n.status!=="available"){let y={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=jv({paths:e,state:o,findings:[y]}),L=Yd({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:i,nextCommand:L.command,archiveReady:!1,inspection:{freshness:"stale",codes:[y.code],reasonCount:1,codesTruncated:!1},findingSummary:$v(P),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:L,workspace:a,runtime:n,...r?.details?{findings:P}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:y.message}:{}}}let s=await WP({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await zP(e,o,r?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let y=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:y,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(r?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let y=await wo({changeDir:se(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 je=await vo(e,o.name,o.verification_evidence);for(let me of je.acceptanceTrace.entries)P.set(me.acceptanceId,me.status==="failed"?"failed":me.status==="missing"?"missing":"satisfied")}let L=JN({criteria:y.contract.acceptance,acceptanceHash:y.contract.acceptanceHash,verificationStatuses:P,failedCheckIds:c?.failedCheckIds??[],...r.acceptanceCursor?{cursor:r.acceptanceCursor}:{}}),H=L.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",L.nextCursor,"--project-root",e.projectRoot]:null;u={...L,...H?{nextPageCommand:Ov(H),nextPageArgs:H}:{}}}catch(y){if(r.acceptanceCursor)throw y;u=void 0}let d=[];if(r?.includeConflictFindings!==!1)try{let y=await ld(e,o.name,{tolerateInvalidSiblings:!0});d.push(...y.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 y=await Tt(e,o.name);if(y)if(y.schema==="comet.native.workspace.v3"){let P=await to({paths:e,identity:y});P.state==="drifted"&&P.code&&f.push({code:P.code,message:P.message??"Native workspace binding is no longer valid"})}else{let P=await Ks({paths:e,identity:y});f.push(...P.findingCodes.map(L=>({code:L,message:`Native workspace advisory changed: ${L} (${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=[],m=!1;if(o.phase==="verify"){let y=await AE({paths:e,state:o});m=y.freshness!=="fresh",h.push(...y.findingCodes.map(P=>({code:P,message:`Native Verify implementation scope is not current: ${P}`})))}let p=null,v=[];if(o.phase==="archive")try{p=await kd({paths:e,name:o.name}),v.push(...p.findingCodes.map(y=>({code:y,message:`Native Archive is blocked: ${y}`})))}catch{v.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let g=[...await wF(e,o),...s.findings,...d,...f,...h,...l,...v].filter((y,P,L)=>L.findIndex(H=>H.code===y.code&&H.path===y.path)===P),N=jv({paths:e,state:o,findings:g}),E=N.filter(y=>!Za(y.code)),w=o.phase==="archive"&&p?.ready===!0&&E.length===0,S=m||o.phase==="archive"&&(p?.findingCodes??[]).some(y=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(y)),k=N.some(y=>y.code==="trajectory-tail-incomplete"||y.code==="trajectory-invalid"||y.requiredAction==="return-to-bound-working-directory"||y.requiredAction==="repair-workspace-binding"),R=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",b=N.find(y=>y.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:i,nextCommand:k||R?null:gF(o,w,S,r?.clarificationMode),archiveReady:w,inspection:s.inspection,findingSummary:$v(N),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Yd({state:o,findings:N,archiveReady:w,evidenceRetreat:S,clarificationMode:r?.clarificationMode}),workspace:a,runtime:n,repair:c,...r?.details?{...u?{acceptancePage:u}:{},findings:N.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:Xd,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:N.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...b?{error:b.message}:{}}}async function yF(e){let t;try{t=await dr({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[],i=await pF.opendir(e.changesDir);try{for await(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink())&&(r.push(n.name),r.length>Ro.maxChanges))throw new Error(`Native status exceeds ${Ro.maxChanges} visible changes`)}finally{await i.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),r.sort()}function Qd(e,t){let r=t.toString(36),i=O("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${r}.${i}`}function NF(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=mF.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 r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let i=O("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:r});if(t[3]!==i)throw new Error("Native status cursor integrity check failed");return r}async function bF(e,t){let r=await yF(e),i=O("comet.native.status-names.v1",r),n=NF({namesHash:i,total:r.length,cursor:t?.cursor}),a=await Promise.all(r.slice(n,n+Ro.maxItems).map(u=>Hv(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:r.length,offset:n,items:d,nextCursor:f<r.length?Qd(i,f):null,nextPageCommand:f<r.length?Ov(["comet","native","status","--cursor",Qd(i,f)]):null,nextPageArgs:f<r.length?["comet","native","status","--cursor",Qd(i,f)]:null,limits:{...Ro}};if(Buffer.byteLength(JSON.stringify(h),"utf8")>Ro.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<r.length?Qd(i,s):null,l=c?["comet","native","status","--cursor",c]:null;return{schema:"comet.native.status-page.v1",total:r.length,offset:n,items:o,nextCursor:c,nextPageCommand:l?Ov(l):null,nextPageArgs:l,limits:{...Ro}}}async function Dv(e,t){return(await bF(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}ad();ke();import{createHash as FF,randomUUID as BF}from"node:crypto";import{constants as Vv,promises as ee}from"node:fs";import pe from"node:path";ot();ri();et();Q();var tf=da(Cn(),1);ue();ke();hr();et();Q();yt();import{randomUUID as kF}from"crypto";import{promises as YP}from"fs";import Mv from"path";import{isDeepStrictEqual as Fv}from"util";Ui();Fn();$s();var ia=/^[a-f0-9]{64}$/u,SF=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),EF=new Set(["sourceHash","targetHash","nextJournal"]),PF=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),JP=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),RF=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function Zd(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function GP(e){return JSON.stringify(e,null,2)+`
|
|
265
|
-
`}function Bv(e){return e.schema===Re?Ku(e):qn(e)}function Lv(e,t){return{...e,schema:Re,minimum_runtime_version:2,revision:t}}function CF(e){return{...e,schema:
|
|
266
|
-
`)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(i&&a.schema===Re?Co(a,u.previousState)||Co(a,u.nextState):a.schema===Pe&&(KP(a,u.previousState)||KP(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(i&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(r.transitionSupersede!==void 0){if(!n||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==Pe)throw new Error("Schema migration transition supersede target schema is invalid");s=AF(r.transitionSupersede,t,a,r.id)}let c;if(r.runRetreat!==void 0){if(!n||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!r.runRetreat||typeof r.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");Zd(r.runRetreat,RF,"Schema migration Run retreat");let l=r.runRetreat,u,d;try{u=Gi(l.previousRun),d=Gi(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!ia.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!==Pe||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:r.id,change:t,fromSchema:r.fromSchema,toSchema:r.toSchema,sourceHash:r.sourceHash,targetHash:r.targetHash,createdAt:r.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function Ic(e,t){let r=_c(e,t),i=$(e,r);await T(i,r);try{let n=await ku({root:i,file:r,maxBytes:524288,label:"Native schema migration journal"});return _F(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function IF(e,t,r){let i=await Ka(e,t),n=i?await Hu(e,i):await Du(e,{now:new Date(r),origin:"legacy-migration"});if(!n.complete){let a=Yp(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 ro(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}i===null&&await Zp(e,t,n)}async function XP(e){try{return await fr(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function TF(e,t){let r=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:r.nextRun.runId,data:{...r.eventData,migrationId:e.id,evidenceHash:r.evidenceHash}}}async function QP(e,t){let r=t.transitionSupersede,i=M(e,t.change),n=await dt(i,r.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&&!Fv(o.event,TF(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 jF(e,t,r){if(!t.transitionSupersede)return;let i=it(e,t.change),n=await XP(i);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=M(e,t.change),o=await Ve(a),s=await QP(e,t),c=await Xa(a,t.transitionSupersede.nextRun.checkpointRef);if(!r||!o||!ci(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!==F(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function $F(e,t,r){let i=t.transitionSupersede;if(!i)return;let n=M(e,t.change),a=await Ve(n);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!ci(a,i.nextRun)){if(!ci(a,i.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Vn(n,i.nextRun),await r?.afterRunStateWritten?.(t)}if(!ci(await Ve(n),i.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await QP(e,t);if(o.sequence===null){let l=await rn({changeDir:n,run:i.nextRun,type:"state_migrated",data:{...i.eventData,migrationId:t.id,evidenceHash:i.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await r?.afterTrajectoryWritten?.(t),await Un({changeDir:n,run:i.nextRun,trajectoryOffset:o.sequence,evidenceHash:i.evidenceHash,now:new Date(t.createdAt)}),await r?.afterCheckpointWritten?.(t);let s=it(e,t.change),c=await XP(s);if(c!==null){if(c!==i.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await YP.rm(s),await r?.afterTransitionSuperseded?.(t)}}async function OF(e,t,r){if(!t.runRetreat)return;let i=M(e,t.change),n=await Ve(i);if(!n)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!ci(n,t.runRetreat.nextRun)){if(!ci(n,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Vn(i,t.runRetreat.nextRun),await r?.afterRunStateWritten?.(t)}let a=await dt(i,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await rn({changeDir:i,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 r?.afterTrajectoryWritten?.(t),await Un({changeDir:i,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await r?.afterCheckpointWritten?.(t)}async function HF(e,t,r){let i=await Ic(e,t);if(!i)return null;if(await no(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=Mv.join(se(e,t),Le),a=await fr(n);if(await jF(e,i,a===i.targetHash),await IF(e,t,i.createdAt),a!==i.targetHash){if(a!==i.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${i.sourceHash}, actual ${a}`);await ge(n,(0,tf.stringify)(Bv(i.nextState))),await r?.afterStateWritten?.(i)}if(i.transition){let o=it(e,t),s=await fr(o);if(s!==i.transition.targetHash){if(s!==i.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${i.transition.sourceHash}, actual ${s}`);await re(o,i.transition.nextJournal),await r?.afterTransitionWritten?.(i)}}return await $F(e,i,r),await OF(e,i,r),await YP.rm(_c(e,t),{force:!0}),i.nextState}async function DF(e){let t=M(e.paths,e.state.name),r=await Ve(t);if(!r||r.runId!==e.state.run_id||r.currentStep!==e.state.phase||r.currentStep!=="verify"&&r.currentStep!=="archive"||r.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let i={...r,currentStep:"build",iteration:r.iteration+1,pending:null,status:"running"},n=F(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:r,nextRun:i,evidenceHash:n,eventData:{fromSchema:Re,toSchema:Pe,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function LF(e){let{journal:t,state:r}=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=Co(r,t.previousState),a=Co(r,t.nextState);if(!n&&!a)throw new Error(`Native change ${r.name} does not match its v2 evidence transition`);let o=M(e.paths,r.name),s=await Ve(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${r.name}`);let c=t.previousRun!==null&&ci(s,t.previousRun),l=ci(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${r.name}`);let d=(await dt(o,t.nextRun.trajectoryRef)).map((g,N)=>({event:g,index:N})).filter(({event:g})=>g.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 g={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!Fv(f.event,g)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let h={...ef(r),revision:r.revision+(r.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},m=s,p=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,v=F(JSON.stringify({operation:"supersede-v2-evidence-transition",change:r.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:r.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:h.revision}));return{nextState:h,plan:{sourceHash:await fr(it(e.paths,r.name)),transitionId:t.id,previousRun:m,nextRun:p,evidenceHash:v,eventData:{fromSchema:Re,toSchema:Pe,previousPhase:r.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function MF(e){let t,r,i,n;if(e.state.schema===lt){if(t=Lv(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==On)throw new Error("Native v1 change has a transition from another schema generation");let s=CF(e.pendingTransition.journal);if(UP(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(UP(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=it(e.paths,e.name);r={sourceHash:await fr(c),targetHash:F(GP(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==Gr)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 LF({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,i=l.plan}else{let l=xF(s);if(Co(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(Co(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=it(e.paths,e.name);r={sourceHash:await fr(u),targetHash:F(GP(l)),nextJournal:l}}}else t=ef(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await DF({paths:e.paths,state:e.state,migrationId:e.id}));let a=Mv.join(se(e.paths,e.name),Le),o=(0,tf.stringify)(Bv(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===lt?Re:Pe,sourceHash:await fr(a),targetHash:F(o),createdAt:e.now.toISOString(),nextState:t,...r?{transition:r}:{},...i?{transitionSupersede:i}:{},...n?{runRetreat:n}:{}}}async function ZP(e){return de(e.paths,`migrate schema for ${e.name}`,()=>Kn(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let r=await HF(e.paths,e.name,e.hooks);if(r?.schema===Pe)return r;let i=await Ir(e.paths,e.name);if(i.status==="current"&&i.state)return i.state;if(i.status!=="migration-required"||!i.state)throw new Error(i.message??`Native change ${e.name} cannot be migrated`);if(await no(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=i.state;if(n.schema!==lt&&n.schema!==Re)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await Um(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 MF({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??kF()}),s=_c(e.paths,e.name),c=$(e.paths,s);await T(c,s),await re(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}Mn();nr();Xi();uc();ho();var li=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),VF=512*1024,na=/^([a-f0-9]{64})\.json$/u,qF=/^\.([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,WF=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,rf=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function Wv(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Fr(e,t){return Wv(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function nR(e,t){return Wv(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function xo(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ht(e,t){return e<t?-1:e>t?1:0}function zF(e,t){let r=pe.relative(e.projectRoot,t);if(r.length===0||pe.isAbsolute(r)||r===".."||r.startsWith(`..${pe.sep}`))throw new Error("Native evidence retention finding path is outside the project");return r.split(pe.sep).join("/")}function aR(e,t){return pe.join(M(e,t),"evidence")}function nf(e,t){return zF(e,aR(e,t))}async function af(e,t){let r=pe.resolve(e),i=pe.resolve(t);if(!D(r,i))throw new Error("Native evidence retention path escapes its managed change");let n=pe.relative(r,i).split(pe.sep).filter(Boolean),a=[],o=r;for(let s of["",...n]){s&&(o=pe.join(o,s));let c=await ee.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await ee.realpath(o);if(a.length>0&&!D(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...xo(c)})}return a}async function Qt(e){for(let t of e){let r=await ee.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Wv(t,r)||await ee.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function oR(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:mo(e,t)}function eR(e){return e!==null&&WF.test(e)?[e]:[]}function JF(e,t,r,i){if(e==="snapshots")return{canonical:so(r,t),dependencies:[]};if(e==="scopes"){let a=co(r);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=id(r);if(a.change!==i||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[mo("scopes",a.scopeHash)]}}if(e==="verifications"){let a=lc(r);if(a.change!==i||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(eR));return{canonical:a,dependencies:[a.implementationScopeRef,MS(a.reportHash),...eR(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Native report evidence must be an object");let a=r;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||FF("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=od(r);if(a.bindings.change!==i||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=nd(r);if(n.change!==i||n.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:n,dependencies:[]}}async function gn(e){let t=await ee.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let r=e.kind==="check-receipts"?VF:tn;if(t.size>r)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let i=await ee.realpath(e.file);if(!D(e.directoryChain[0].realPath,i))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let n=process.platform==="win32"?"r":Vv.O_RDONLY|Vv.O_NOFOLLOW|Vv.O_NONBLOCK,a=await ee.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(),ee.lstat(e.file),ee.realpath(e.file)]);if(await Qt(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==i||!Fr(xo(t),o)||!Fr(xo(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let N=r+1-d,E=await a.read(u,0,Math.min(u.length,N),null);if(E.bytesRead===0)break;if(d+=E.bytesRead,d>r)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,E.bytesRead)))}let[f,h,m]=await Promise.all([a.stat(),ee.lstat(e.file),ee.realpath(e.file)]);if(await Qt(e.directoryChain),!h.isFile()||h.isSymbolicLink()||m!==i||!Fr(xo(o),f)||!Fr(xo(o),h))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let p=Buffer.concat(l,d).toString("utf8"),v;try{v=JSON.parse(p)}catch(N){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:N})}let g=JF(e.kind,e.hash,v,e.name);if(p!==JSON.stringify(g.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:xo(f),directoryChain:e.directoryChain,dependencies:[...new Set(g.dependencies)].sort(ht)}}finally{await a.close()}}async function tR(e){try{return await ee.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function GF(e){let t=M(e.paths,e.name),r=t,i=aR(e.paths,e.name);await T($(e.paths,i),i);let n;try{let s=await af(t,i);n=await ee.readdir(i,{withFileTypes:!0}),await Qt(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of rf){if(!n.some(f=>f.name===s))continue;let c=pe.join(i,s),l=await af(t,c),u=(await ee.readdir(c,{withFileTypes:!0})).sort((f,h)=>ht(f.name,h.name)),d=new Map;for(let f of u){let h=qF.exec(f.name);if(!h)continue;let m=d.get(h[1])??[];m.push(f),d.set(h[1],m)}for(let[f,h]of[...d.entries()].sort(([m],[p])=>ht(m,p))){if(h.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${s}/${f}`);let m=h[0];if(!m.isFile()||m.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${s}/${m.name}`);let p=pe.join(c,f),v=na.exec(f)?.[1];if(!v)throw new Error(`Native evidence cleanup quarantine name is invalid: ${m.name}`);let g=oR(s,v),N=pe.join(c,m.name),E=await gn({changeRoot:r,file:N,ref:g,kind:s,hash:v,name:e.name,directoryChain:l}),w=await tR(p),S=w?null:await gn({changeRoot:r,file:p,ref:g,kind:s,hash:v,name:e.name,directoryChain:l});a.push({ref:g,original:p,quarantine:N,document:E,action:w?"restore-original":"finish-linked-recovery",originalDocument:S})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(ht);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:Ao(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${of(o)}`),path:nf(e.paths,e.name)}]};for(let s of a.sort((c,l)=>ht(c.ref,l.ref))){if(await Qt(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await gn({changeRoot:r,file:s.original,ref:s.ref,kind:s.document.kind,hash:na.exec(pe.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await gn({changeRoot:r,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:na.exec(pe.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!Fr(s.originalDocument.identity,d.identity)||!Fr(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await ee.rm(s.quarantine),await Qt(s.document.directoryChain);continue}if(!await tR(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await ee.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!Fr(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await ee.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await gn({changeRoot:r,file:s.original,ref:s.ref,kind:s.document.kind,hash:na.exec(pe.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await gn({changeRoot:r,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:na.exec(pe.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!nR(s.document.identity,l.identity)||!Fr(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await ee.rm(s.quarantine),await Qt(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:Ao(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${of(o)}`),path:nf(e.paths,e.name)}]}}async function UF(e,t){let r=M(e,t),i=r,n=pe.join(r,"evidence");await T($(e,n),n);let a;try{let l=await af(r,n);a=await ee.readdir(n,{withFileTypes:!0}),await Qt(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!rf.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(ht);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${of(o)}`);let s=[],c=0;for(let l of rf){if(!a.some(h=>h.name===l))continue;let u=pe.join(n,l),d=await af(i,u),f=(await ee.readdir(u,{withFileTypes:!0})).sort((h,m)=>ht(h.name,m.name));await Qt(d);for(let h of f){if(s.length>=li.maxDocuments)throw new Error(`Native evidence store exceeds ${li.maxDocuments} documents`);let m=na.exec(h.name);if(!m||!h.isFile()||h.isSymbolicLink())throw new Error(`Native evidence kind ${l} has an unknown or special entry: ${h.name}`);let p=oR(l,m[1]),v=pe.join(u,h.name);await T($(e,v),v);let g=await gn({changeRoot:i,file:v,ref:p,kind:l,hash:m[1],name:t,directoryChain:d});if(c+=g.size,c>li.maxScannedBytes)throw new Error(`Native evidence store exceeds ${li.maxScannedBytes} scanned bytes`);s.push(g)}await Qt(d)}return s}function rR(e,t){let r=new Set,i=[...e].sort(ht).reverse();for(;i.length>0;){let n=i.pop();if(r.has(n))continue;let a=t.get(n);if(!a)throw new Error(`Native evidence dependency is missing: ${n}`);r.add(n);for(let o of[...a.dependencies].sort(ht).reverse())r.has(o)||i.push(o)}return r}function KF(e){let t=new Map(e.map(a=>[a.ref,a])),r=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&r.set(o,(r.get(o)??0)+1);let i=[...r].filter(([,a])=>a===0).map(([a])=>a).sort(ht),n=[];for(;i.length>0;){let a=i.shift(),o=t.get(a);n.push(o);for(let s of o.dependencies){let c=r.get(s);if(c===void 0)continue;let l=c-1;r.set(s,l),l===0&&(i.push(s),i.sort(ht))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function YF(e,t,r){let i=new Map(e.map(c=>[c.ref,c]));if(i.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!i.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let n=rR(t,i),a=new Set(n);for(let c of e)r-c.mtimeMs<li.minimumAgeMs&&a.add(c.ref);for(let c of rf){let l=e.filter(u=>u.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||ht(u.ref,d.ref)).slice(0,li.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=rR(a,i),s=e.filter(c=>!o.has(c.ref)&&r-c.mtimeMs>=li.minimumAgeMs).sort((c,l)=>ht(c.ref,l.ref));return{candidates:KF(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function of(e){let t=e.slice(0,li.maxReportedRefs),r=e.length-t.length;return`${t.join(", ")}${r>0?`, ... (${r} more)`:""}`}function Ao(e){let t=li.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let r=e;for(;r.length>0&&Buffer.byteLength(`${r}...`,"utf8")>t;)r=r.slice(0,-1);return`${r}...`}function qv(e,t,r,i){let n=t.candidates.map(a=>a.ref).sort(ht);return{severity:"info",code:r?"evidence-retention-cleaned":"evidence-retention-candidates",message:Ao(`${r?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${of(n)}`),path:i}}async function iR(e,t){try{await ee.lstat(t);return}catch(r){if(r.code!=="ENOENT")return}try{await ee.rename(e,t)}catch{}}async function XF(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await Qt(e.directoryChain);let r=await gn({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:na.exec(pe.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),i=await ee.lstat(e.file),n=await ee.realpath(e.file);if(!i.isFile()||i.isSymbolicLink()||!Fr(e.identity,i)||!Fr(e.identity,r.identity)||!D(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=pe.join(pe.dirname(e.file),`.${pe.basename(e.file)}.${BF()}.gc`);await ee.rename(e.file,a);try{let[o,s]=await Promise.all([ee.lstat(a),ee.realpath(a)]);if(await Qt(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!nR(e.identity,o)||!D(e.directoryChain[0].realPath,s))throw await iR(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await ee.rm(a),await Qt(e.directoryChain)}catch(o){throw await iR(a,e.file),o}}async function QF(e){if((await Ee(e.projectRoot))?.native.pending_root_move)return!0;let r;try{r=await ee.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return!1;throw i}for(let i of r){if(!i.isDirectory()||i.isSymbolicLink())return!0;try{let n=await At(e,i.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function ZF(e,t){if(t)return[t];let r;try{r=await ee.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return r.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort(ht)}async function eB(e,t){let r=await Ir(e,t);if(r.status!=="current"||!r.state||r.state.archived)return!0;let[i,n,a]=await Promise.all([ii(e,t),Ic(e,t),sn(e,t)]);return i!==null||n!==null||a!==null}async function tB(e){if(await eB(e.paths,e.name))return[];let t=await Ir(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let r=await GF({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(r.pending)return r.findings;let i=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&i.push(c);let n=await UF(e.paths,e.name),a=YF(n,i,e.nowMs);if(a.candidates.length===0)return r.findings;let o=nf(e.paths,e.name);if(!e.repair)return[...r.findings,qv(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await XF(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...r.findings,...s.length>0?[qv(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:Ao(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...r.findings,qv(e.name,a,!0,o)]}async function sR(e){if(e.deferAll||await QF(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let r=async n=>{let a=[];for(let o of await ZF(e.paths,e.name))try{a.push(...await tB({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:Ao(`Native evidence retention refused to clean ${o}: ${s.message}`),path:nf(e.paths,o)})}return a};if(!(e.repair??!1))return r(!1);let i=await r(!1);if(i.some(n=>n.severity==="error")||!i.some(n=>n.code==="evidence-retention-candidates"||n.code==="evidence-retention-recovery-required"))return i;try{return await de(e.paths,"prune Native evidence",()=>r(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:Ao(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}Tn();Q();yt();ue();ot();Tn();Q();yt();Mn();Ar();import{createHash as rB,randomUUID as N5}from"crypto";import{promises as $c}from"fs";import ce from"path";var Jv=64*1024*1024,iB=256*1024,dR=16*1024*1024;async function pt(e){try{return await $c.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function nB(e){let t;try{t=await $c.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return;throw r}for(let r of t.sort((i,n)=>i.name.localeCompare(n.name))){if(!r.isDirectory()||r.isSymbolicLink())continue;let i=await Tt(e,r.name);if(i){await Ju({paths:e,name:r.name,revision:i.capturedRevision,...i.schema==="comet.native.workspace.v3"?{binding:{isolation:i.isolation,changeBranch:i.changeBranch,targetBranch:i.targetBranch},...i.finish?{finish:i.finish}:{}}:{}});continue}}}async function jc(e,t){let r=[];async function i(n){let a=await xt({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=ce.join(n,s.name);if(t.excludedFiles?.has(ce.resolve(c))){await a.verify();continue}let l=await $c.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())r.push({ref:ce.relative(e,c).split(ce.sep).join("/"),type:"directory"}),await i(c);else if(s.isFile()&&l.isFile()){let u=await oe({root:e,file:c,maxBytes:Jv,label:`Native root file ${ce.relative(e,c)}`});r.push({ref:ce.relative(e,c).split(ce.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 i(e),r.sort((n,a)=>n.ref.localeCompare(a.ref))}async function aB(e,t,r,i){await Rr({root:i,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await xt({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=ce.join(a,l.name);if(ce.resolve(u)===ce.resolve(r)){await s.verify();continue}let d=await $c.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=ce.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await Rr({root:i,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await Bi({sourceRoot:e,source:u,targetRoot:i,target:f,maxBytes:Jv,label:`Native root move file ${ce.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 _o(e,t,r,i){let n=await jc(e,{rejectSymlinks:!0,excludedFiles:r?new Set([ce.resolve(r)]):void 0}),a=await jc(t,{rejectSymlinks:!0,excludedFiles:i?new Set([ce.resolve(i)]):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 oB(e,t){return ce.join(e.artifactRoot,`.comet-native-move-${t}`)}function sB(e,t){return ce.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function cB(e){return`${e}.removing`}function cR(e,t){return ce.join(ce.dirname(e),`.${ce.basename(e)}.${t}.rollback-removing`)}function fR(e,t,r){return ce.join(xu(e,t).directory,`root-move-cleanup-${r}.json`)}function lB(e){return JSON.stringify(e,null,2)+`
|
|
268
|
-
`}function uB(e){return rB("sha256").update(e).digest("hex")}function dB(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 r=e,i=Object.keys(r).sort(),n=r.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof r.ref!="string"||r.ref.length===0||r.ref.includes("\\")||ce.posix.normalize(r.ref)!==r.ref||r.ref.startsWith("/")||r.ref.split("/").includes("..")||Buffer.byteLength(r.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(r.type==="directory")return{ref:r.ref,type:"directory"};if(r.type!=="file"||typeof r.size!="number"||!Number.isSafeInteger(r.size)||r.size<0||typeof r.hash!="string"||!/^[a-f0-9]{64}$/u.test(r.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:r.ref,type:"file",size:r.size,hash:r.hash}}function fB(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let i=e;if(JSON.stringify(Object.keys(i).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||i.schema!=="comet.native.root-move-cleanup.v1"||i.transactionId!==t||i.kind!==r||!Array.isArray(i.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=i.entries.map(dB);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=ce.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:r,entries:n}}async function hB(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},r=lB(t);if(Buffer.byteLength(r,"utf8")>dR)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await ge(fR(e.paths,e.id,e.kind),r,{containedRoot:e.paths.runtimeDir}),uB(r)}async function pB(e){let t=await oe({root:e.paths.runtimeDir,file:fR(e.paths,e.id,e.cleanup.kind),maxBytes:dR,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 fB(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function zv(e){let t=await jc(e.quarantine,{rejectSymlinks:!0}),r=new Map(e.manifest.entries.map(i=>[i.ref,i]));for(let i of t){let n=r.get(i.ref);if(!n||JSON.stringify(n)!==JSON.stringify(i))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${i.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 lR(e){return e.ref.split("/").length}async function mB(e){let r=[...await zv({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>lR(a)-lR(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),i=0;for(let n of r){let a=ce.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await Su({root:e.projectRoot,file:a,maxBytes:Jv,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await $p({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),i+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,i)}await zv({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await $p({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function hR(e,t,r=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:r,pending_root_move:t}}}function vB(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 gB(e,t,r,i){for(let a of[e,t])try{let o=await At(a,i);if(o.kind!=="root-move")throw new Error(`Transaction ${i} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let n=ce.join(r,"runtime","transactions",i,"transaction.json");try{let a=await oe({root:r,file:n,maxBytes:iB,label:`Staged Native root-move journal ${i}`}),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: ${i}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${i}`,{cause:a})}}async function uR(e){let t=hR(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await Ti(e.projectRoot,t),t}async function Tc(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 r=hR(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 Ti(e.projectRoot,r),r}async function sf(e){let t=e.config,r=t.native.pending_root_move;if(!r||r.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=r.cleanup;if(i&&i.kind!==e.kind)throw new Error(`Native root move has unfinished ${i.kind} cleanup; cannot start ${e.kind}`);let n=await pt(e.target),a=await pt(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!i){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 hB({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await jc(e.target,{rejectSymlinks:!0})});i={kind:e.kind,state:"prepared",manifestHash:s},t=await Tc({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})}let o=await pB({paths:e.stablePaths,id:e.id,cleanup:i});if(n=await pt(e.target),a=await pt(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(i.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await pb({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(i.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return Tc({projectRoot:e.projectRoot,config:t,id:e.id})}return await zv({quarantine:e.quarantine,manifest:o,exact:i.state!=="deleting"}),i.state==="prepared"&&(i={...i,state:"quarantined"},t=await Tc({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})),i.state==="quarantined"&&(i={...i,state:"deleting"},t=await Tc({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})),await mB({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),Tc({projectRoot:e.projectRoot,config:t,id:e.id})}async function wB(e){let t=e.config,r=t.native.pending_root_move.stage;if(r==="copying"){if(!await pt(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=cB(e.staging);t=await sf({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 jc(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([ce.resolve(e.lockFile)])}),await aB(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await _o(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await uR({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),r="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(r==="ready"){if(await pt(e.destinationPaths.nativeRoot)){if(await pt(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await _o(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await pt(e.staging))throw new Error("Native move staging tree is missing");await _o(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await $c.rename(e.staging,e.destinationPaths.nativeRoot)}t=await uR({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),r="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(r!=="switched")throw new Error(`Unsupported Native root-move stage: ${r}`);if(!await pt(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let i=sB(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await pt(e.sourcePaths.nativeRoot)&&await _o(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await sf({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:i,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await nB(e.destinationPaths);let n=await At(e.destinationPaths,e.pending.id);await qa(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 Ti(e.projectRoot,o),o}async function pR(e){let t=await Ee(e.projectRoot),r=t?.native.pending_root_move;if(!t||!r)throw new Error("No pending Native root move was found");let i=await Ke(e.projectRoot,r.fromArtifactRoot),n=await Ke(e.projectRoot,r.toArtifactRoot),a=oB(n,r.id),o=await pt(i.nativeRoot)?i:n,s=await ji(o,"root-move",`recover root ${r.id}`);try{let c;try{c=await gB(i,n,a,r.id)}catch(m){if(r.stage!=="copying"||!await pt(i.nativeRoot))throw m;let p=vB({id:r.id,paths:i,now:new Date});await Eb(i,p),c={journal:p,paths:i}}if(e.strategy==="continue"){let m=await wB({projectRoot:e.projectRoot,config:t,pending:r,sourcePaths:i,destinationPaths:n,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:n.nativeRoot,config:m}}if(!await pt(i.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=cR(n.nativeRoot,r.id);!t.native.pending_root_move?.cleanup&&await pt(n.nativeRoot)&&await _o(i.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await sf({projectRoot:e.projectRoot,config:t,id:r.id,kind:"rollback-destination",stablePaths:i,target:n.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=cR(a,r.id);!t.native.pending_root_move?.cleanup&&await pt(a)&&await _o(i.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await sf({projectRoot:e.projectRoot,config:t,id:r.id,kind:"rollback-staging",stablePaths:i,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await At(i,r.id);await Au(i,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:r.fromArtifactRoot}};return await Ti(e.projectRoot,h),{activeNativeRoot:i.nativeRoot,config:h}}finally{await $i(s)}}Mn();Js();Ar();var Io=4096,yB=4096,NB=1024;async function wn(e,t,r){try{let i=await xt({root:$(e,t),directory:t,label:"Native doctor directory",maxEntries:r});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function lf(e,t){let r=new Map(e.map(i=>[Me.resolve(i.file),{...i,file:Me.resolve(i.file)}]));for(let{paths:i,file:n}of r.values()){let a;try{a=await Es(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 bp(i,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 bB(e,t){let r=$P(e),i;try{await T(e.projectRoot,r);let n=await Ud(e);if(!n)return[];i=n}catch(n){return n.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${n.message}`,path:r}]}if(i.schema!=="comet.selection.v2"||i.workflow!=="native"||typeof i.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:r}];try{return await vn(e,i.change)?[]:(await We(e,i.change),[])}catch(n){if(n.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${n.message}`,path:r}]}return t?(await cf.rm(r,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${i.change}`,path:r}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${i.change}`,path:r}]}async function kB(e){let t=[];for(let r of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await T($(e,r),r)}catch(i){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${i.message}`,path:r})}return t}async function SB(e,t){let r=[],i=[];for(let n of await wn(e,e.transactionsDir,yB)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await At(e,n.name)}catch(o){r.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:Me.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"){i.push(a),r.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 ja([e],`doctor archive recovery ${a.id}`,async()=>await lf([{paths:e,file:Me.join(e.locksDir,"root-move.lock")},{paths:e,file:Me.join(e.locksDir,"archive.lock")}],r)?(await LP({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){i.push(a);continue}r.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){i.push(a),r.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else i.push(a),r.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:r,unfinished:i}}async function EB(e,t,r){let i=[];for(let n of await wn(e,e.locksDir,NB)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=Me.join(e.locksDir,n.name);try{let o=await Es(a);if(o.status==="active")i.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")i.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&r.length===0){let s=await bp(e,a,o);s.status==="removed"?i.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&i.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 i.push({severity:r.length>0?"error":"warning",code:"lock-stale",message:r.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){i.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return i}async function PB(e,t,r=5){let i=[],n=t?await Dv(e,{maxVerifyFailures:r}).then(a=>a.filter(o=>o.name===t)):await Dv(e,{maxVerifyFailures:r});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"){i.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:Me.join(e.changesDir,a.name,Le)});continue}let o=await Hv(e,a.name,{details:!0,maxVerifyFailures:r});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||i.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:Me.join(e.projectRoot,s.path)}:{}})}return i}async function RB(e,t){let r=[],i=t.name?[t.name]:(await wn(e,e.changesDir,Io)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i)try{let a=await Qa(e,n);if(a.status!=="repairable")continue;if(!t.repair){r.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 Nk(e,n);o&&r.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){r.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${n}: ${a.message}`,path:Me.join(M(e,n),"trajectory.jsonl")})}return r}async function CB(e,t){let r=[],i=t.name?[t.name]:(await wn(e,e.changesDir,Io)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a=await Ss(e,n);if(a.status==="missing"){r.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"){r.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=In(e,n),s=Ye(e,n);if(!t.repair){r.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 ja([e],`migrate Runtime layout for ${n}`,async()=>{let c=await dr({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await T(e.runtimeDir,s),await cf.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await dr({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await cf.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 cf.rename(o,s)}),r.push({severity:"info",code:"runtime-layout-migrated",message:`Moved Native Runtime for ${n} to project-local .comet storage`,path:s})}catch(c){r.push({severity:"error",code:"runtime-layout-migration-failed",message:`Native Runtime layout migration failed for ${n}: ${c.message}`,path:o})}}return r}async function xB(e,t){let r=[],i=t.name?[t.name]:(await wn(e,e.changesDir,Io)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i)try{if(!await om(e,n))continue;if(!t.repair){r.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${n} uses legacy external-probe or hash-only metadata`,path:eo(e,n),repair:"migrate"});continue}let a=await We(e,n);await Ik({paths:e,name:n,revision:a.revision})&&r.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${n} with process-free root identities`,path:eo(e,n)})}catch(a){r.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:eo(e,n)})}return r}async function AB(e,t){let r=[],i=t.name?[t.name]:(await wn(e,e.changesDir,Io)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a=_c(e,n);try{let o=await Ic(e,n),s=await Ir(e,n);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){r.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${n} requires a newer runtime`,path:Me.join(e.changesDir,n,Le)});continue}if(!t.repair){r.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:Me.join(e.changesDir,n,Le),repair:"migrate"});continue}await ZP({paths:e,name:n}),r.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${n} to the current schema`,path:Me.join(e.changesDir,n,Le)})}catch(o){if(o.code==="ENOENT")continue;r.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${n}: ${o.message}`,path:a})}}return r}async function _B(e,t){let r=[],i=t.name?[t.name]:(await wn(e,e.changesDir,Io)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a;try{a=await ii(e,n)}catch(o){if(o instanceof vc)continue;r.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:it(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await ja([e],`doctor transition recovery ${n}`,async()=>await lf([{paths:e,file:Me.join(e.locksDir,"root-move.lock")},{paths:e,file:Me.join(e.locksDir,`transition-${n}.lock`)}],r)?(await uE(e,n),!0):!1))continue;r.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:it(e,n)})}catch(o){r.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:it(e,n)})}continue}r.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:it(e,n),repair:"continue"})}}return r}async function IB(e,t){let r=[],i=t.name?[t.name]:(await wn(e,e.changesDir,Io)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a=on(e,n),o;try{o=await sn(e,n)}catch(s){if(s.code==="ENOENT")continue;r.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){r.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${n}`,path:a});continue}try{if(!await ja([e],`doctor checkpoint recovery ${n}`,async()=>await lf([{paths:e,file:Me.join(e.locksDir,"root-move.lock")},{paths:e,file:Me.join(e.locksDir,`transition-${n}.lock`)}],r)?(await kE(e,n),!0):!1))continue;r.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${n}`,path:a})}catch(s){r.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return r}async function Oc(e){let t=e.repair??!1,r=[],i=e.paths,n;try{n=await Ee(i.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:i.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([Ke(i.projectRoot,c.fromArtifactRoot),Ke(i.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await lf([{paths:l,file:Me.join(l.locksDir,"root-move.lock")},{paths:u,file:Me.join(u.locksDir,"root-move.lock")}],r))return{healthy:!1,findings:r};let f=await pR({projectRoot:i.projectRoot,strategy:e.recoveryStrategy});i=await Ke(i.projectRoot,f.config.native.artifact_root),a=!1,r.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return r.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:r}}else r.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 kB(i);if(r.push(...o),o.length>0)return{healthy:!1,findings:r};let s=await SB(i,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return r.push(...s.findings),e.projectOnly||(r.push(...await CB(i,{name:e.name,repair:t})),r.push(...await AB(i,{name:e.name,repair:t})),r.push(...await xB(i,{name:e.name,repair:t})),r.push(...await RB(i,{name:e.name,repair:t})),r.push(...await _B(i,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),r.push(...await IB(i,{name:e.name,repair:t})),r.push(...await sR({paths:i,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),r.push(...await EB(i,t,s.unfinished)),r.push(...await bB(i,t)),e.projectOnly||r.push(...await PB(i,e.name,n?.native.max_verify_failures??5)),{healthy:r.every(c=>c.severity==="info"),findings:r}}Eo();Lt();ue();Ft();ke();ot();et();import{randomUUID as TB}from"node:crypto";import{promises as Je}from"node:fs";import Ge from"node:path";So();Er();La();Q();var Gv=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 mR(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function vR(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let r=Ge.join(e.archiveDir,t);if(!D(e.archiveDir,r))throw new Error("Native Archive path escaped");return r}async function Hc(e){try{return await Je.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function gR(e,t){let r=Ge.normalize(Ge.resolve(e)),i=Ge.normalize(Ge.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}async function jB(e,t){let r;try{r=await Je.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let i=[];for(let n of r){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=Ge.join(e.archiveDir,n.name);try{let o=await Be(Ge.join(a,"comet-state.yaml"));o.name===t&&i.push({dir:a,state:o})}catch{}}if(i.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return i[0]??null}async function $B(e,t){let r=await Da(e,{kind:"archive",change:t});return r?.kind==="archive"?r.journal:null}async function aa(e,t){await Je.mkdir(e.transactionsDir,{recursive:!0}),await re(Li(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function OB(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let r=ir(e.paths.projectRoot);r.some(a=>gR(a,e.paths.projectRoot))||r.push(e.paths.projectRoot);let i=[];for(let a of r){let o=await Ee(a);if(!o)continue;let s=await Ke(a,o.native.artifact_root);i.some(c=>gR(c.changesDir,s.changesDir))||i.push(s)}i.length===0&&i.push(e.paths);let n=new Set;for(let a of i){let o;try{o=await Je.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 Be(Ge.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 Xu(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 HB(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 DB(e){let t=Ge.join(e.paths.specsDir,e.change.capability),r=Ge.join(t,"spec.md");if(!D(e.paths.specsDir,r))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await Je.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 Je.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([Je.realpath(e.paths.specsDir),Je.realpath(t)]);if(!D(o,s))throw new Error("Native canonical capability path escaped");try{let c=await Je.lstat(r);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await Je.unlink(r)}catch(c){if(c.code!=="ENOENT")throw c}await Je.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let i=Ge.join(Yt(e.paths,e.state.name),e.change.source);await ge(i,e.change.content,{containedRoot:e.paths.nativeRoot}),await Je.mkdir(t,{recursive:!0}),await ge(r,e.change.content,{containedRoot:e.paths.nativeRoot})}function yR(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 LB(e,t){let r=Yt(e,t.name),i=[];for(let n of t.spec_changes){if(n.source===null){i.push({...n,content:null});continue}let a=await te({root:r,ref:n.source,maxBytes:null,includeHash:!1});i.push({...n,content:a.text})}return i}function MB(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(yR(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function wR(e,t){for(let r of t.spec_changes.slice(0,t.next_spec_index)){let i=`${r.capability}/spec.md`,n=Ge.join(e.specsDir,i);if(r.operation==="remove"){if(!await Hc(n))continue}else try{if((await te({root:e.specsDir,ref:i,maxBytes:null,includeHash:!1})).text===r.content)continue}catch(a){if(a.code!=="ENOENT")throw a}throw new Error(`Canonical Spec ${i} changed after Archive applied it; preserve the concurrent edit and resolve it before resuming Archive`)}}async function Uv(e){return de(e.paths,`archive portable change ${e.name}`,async()=>{let t=HB(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let r=await $B(e.paths,e.name),i=Yt(e.paths,e.name),n=await Hc(i),a=n?null:await jB(e.paths,e.name),o;if(n)o=await si(e.paths,e.name);else if(r)o=await Be(Ge.join(vR(e.paths,r.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);let s=await Ot(e.paths,e.name);if(n&&!o.archived&&r===null){let f=await _P({paths:e.paths,state:o});if(f.drifted){let h=f.reason??"Native confirmed requirements changed";throw await TP({paths:e.paths,state:o,reason:h}),new Error(`${h}; Native change returned to Shape and requires confirmation`)}}if(n&&!o.archived&&s?.finalVerification.status==="pending"&&o.verification_result==="pass"){let f=await IP({paths:e.paths,name:e.name});if(o=f.state,f.action==="rerun-final-verification")throw new Error("Native Supervisor final verification must be rerun for the current integration commit");f.action==="recorded-final-verification"&&(s=await Ot(e.paths,e.name))}let c=vR(e.paths,r?.archive_ref??mR(o)),l=await Hc(c);if(r&&MB(r,o),n&&l)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!r&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await Cc(e.paths,o.name),await Je.rm(Ye(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!r){if(!o.archived)yR(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let f=await OB({paths:e.paths,state:o});if(!o.archived&&f.length>0&&t!==o.name)throw new Gv(f);r={schema:Nu,id:TB(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:mR(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await LB(e.paths,o),created_at:new Date().toISOString()},await aa(e.paths,r)}if(!n&&l&&r.status==="report-aligned")r={...r,status:"moved"},await aa(e.paths,r);else if(!n&&l&&r.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${r.status}; doctor intervention is required`);await wR(e.paths,r);let u=r.spec_changes.slice(0,r.next_spec_index).map(({capability:f})=>Ge.relative(e.paths.projectRoot,Ge.join(e.paths.specsDir,f,"spec.md")).replaceAll("\\","/")),d=!1;if(r.status==="prepared"&&s&&!o.archived&&(s=(await Pc({paths:e.paths,state:s,archiveOwnedPaths:u})).state,d=!0),r.status==="prepared"){for(let f=r.next_spec_index;f<r.spec_changes.length;f+=1)await DB({paths:e.paths,state:o,change:r.spec_changes[f]}),r={...r,next_spec_index:f+1},await aa(e.paths,r),await e.hooks?.afterSpecApplied?.(f);r={...r,status:"specs-applied"},await aa(e.paths,r)}if(await wR(e.paths,r),r.status==="specs-applied"){if(s&&!o.archived&&!d&&(s=(await Pc({paths:e.paths,state:s,archiveOwnedPaths:u})).state,d=!0),!o.archived){let f={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await Hi({file:Ht(e.paths,o.name),expectedStateVersion:o.state_version,next:f,containedRoot:e.paths.nativeRoot})}r={...r,status:"state-finalized"},await aa(e.paths,r),await e.hooks?.afterFinalState?.()}if(r.status==="state-finalized"){let f=await Hc(i)?i:c;if(await Jd({file:Ge.join(f,"verification.md"),state:o,...s?{supervisor:s}:{}}),await zd({file:Ge.join(f,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");r={...r,status:"report-aligned"},await aa(e.paths,r),s&&!d&&(await Pc({paths:e.paths,state:s,archiveOwnedPaths:u}),d=!0),await e.hooks?.afterReportAligned?.()}if(r.status==="report-aligned"){if(s&&!d&&await Pc({paths:e.paths,state:s,archiveOwnedPaths:u}),await Je.mkdir(e.paths.archiveDir,{recursive:!0}),await Hc(c))throw new Error(`Native Archive target already exists: ${c}`);await Je.rename(i,c),r={...r,status:"moved"},await aa(e.paths,r),await e.hooks?.afterMove?.()}return r.status==="moved"&&(await Cc(e.paths,o.name),await Je.rm(Ye(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await Je.rm(Li(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:c,transactionId:r.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}_s();function ui(e,t,r){return e.language==="zh-CN"?r:t}function FB(e,t){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:ui(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:ui(e,"Reply A or B","回复 A 或 B"),agentInstruction:ui(e,"Relay the two coordination choices and wait for the user decision. After the user chooses, execute the prepare-shape-confirmation commandArgs with the selected --coordination-mode. Do not combine mode selection with final confirmation; confirmation of the complete Shape is a separate await-user step.","转述这两个推进方式并等待用户选择。用户选择后,使用对应的 --coordination-mode 执行 prepare-shape-confirmation 的完整 commandArgs;不要把推进方式选择和最终确认合并执行,完整 Shape 的确认是后续单独的 await-user 步骤。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return r(ui(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return r(ui(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:i})=>i==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return r(ui(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 BB(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会先执行完整 dry-run,再给出唯一的 confirmed 命令;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"只向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 中包含 --dry-run --finish 的完整命令;选择 E 时停止,不运行任何 Archive 命令。不要直接运行 --confirmed,也不要自行猜测 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run a complete dry-run first, then return one confirmed command; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative containing --dry-run --finish; for E, stop without running an Archive command. Do not run --confirmed directly or guess a finish mode."}}function VB(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",e.name,"--dry-run","--finish",i],requiredInputs:[],inputOptions:[],description:ui(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:ui(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function bR(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function oa(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function qB(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function NR(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function WB(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function zB(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function yn(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:bR({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[oa("summary","--summary"),qB(e.name,e.flag)]}}function Kv(e){return[yn({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),yn({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function uf(e,t,r={}){let i=WB(t)&&e.coordination_mode===void 0,n=FB(e,i),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[oa("summary","--summary")],commandAlternatives:[yn({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[oa("summary","--summary")],commandAlternatives:[yn({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Kv({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[oa("summary","--summary")],commandAlternatives:[yn({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),yn({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[oa("summary","--summary")],commandAlternatives:[yn({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Kv({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[oa("summary","--summary")],commandAlternatives:Kv({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?bR({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:i?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:zB({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[NR("coordination-mode","--coordination-mode",eb)]:[]],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:u})=>u==="verified");if(s)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}}],runnerAction:o("none")};let c=t.children.some(({status:u})=>u==="blocked"||u==="needs-reverify"),l=t.children.some(({status:u})=>u==="ready"||u==="active");return{...a,disposition:c&&!l?"blocked":"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:c&&!l?["resolve-child-blocker"]:["ready-children"],inputOptions:[oa("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${ui(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:c?[l]:[]}}],runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;return s==="blocked"?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:s==="preview"?r.archiveBlockers&&r.archiveBlockers.length>0?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}:l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[NR("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...VB(e)],userCommunication:BB(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[yn({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}Lt();ue();Ft();ke();et();Tp();La();pu();import{randomUUID as JB}from"node:crypto";import{promises as To}from"node:fs";import xR from"node:path";Er();Q();Ar();var Yv=["evidence.md","repair.md","archive.md","checkpoint.md"],GB="verification.md";async function UB(e){try{return await To.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Xv(e,t){let r=se(e,t),i=[Li(e,{kind:"migration",change:t}),In(e,t),...Yv.map(n=>xR.join(r,n))];return(await Promise.all(i.map(UB))).some(Boolean)}async function KB(e,t){let r=await Da(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function kR(e,t){await To.mkdir(e.transactionsDir,{recursive:!0}),await re(Li(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function SR(e,t,r={}){let i=r.removeVerificationReport===!1?Yv:[...Yv,GB];await Promise.all([To.rm(Ye(e,t),{recursive:!0,force:!0}),To.rm(In(e,t),{recursive:!0,force:!0}),...i.map(n=>To.rm(xR.join(se(e,t),n),{force:!0}))])}async function ER(e,t){await ai(mn(e,t.name),fn({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function PR(e,t){try{let r=await Tt(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function RR(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=ae(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function YB(e){let t=se(e.paths,e.state.name),r=await te({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await te({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return hu({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function CR(e,t){let r=await Xu(e,t);if(r.status==="runtime-incompatible")throw new Yr(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function Dc(e){return de(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await KB(e.paths,e.name),r=await vn(e.paths,e.name)?await Be(Ht(e.paths,e.name)):null;if(!t&&r)return await SR(e.paths,e.name,{removeVerificationReport:!1}),await ER(e.paths,r),r;let i=null,n=null;for(t||(i=await CR(e.paths,e.name),n=await PR(e.paths,e.name),RR(e.paths,n),t={schema:yu,id:JB(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await kR(e.paths,t));;){let a=ab(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await CR(e.paths,e.name),n??=await PR(e.paths,e.name),RR(e.paths,n),r=nb({state:i,acceptance:await YB({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await Ts(Ht(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await SR(e.paths,e.name):a.action==="commit-transaction"&&(r??=await Be(Ht(e.paths,e.name)),await ER(e.paths,r)),t={...t,status:a.nextStatus},await kR(e.paths,t)}return await To.rm(Li(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??Be(Ht(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}Lt();import{promises as _R}from"node:fs";import IR from"node:path";et();Eo();Xe();So();import{promises as Qv}from"node:fs";import XB from"node:path";var QB=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),ZB=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),eV=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task"]),tV=new Set(["status","summary"]);function df(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function ff(e,t,r){let i=new Set(Object.keys(e)),n=[...t].filter(o=>!i.has(o)),a=[...i].filter(o=>!t.has(o));return n.length===0&&a.length===0?null:`${r} fields must be exact (missing: ${n.join(", ")||"none"}; unexpected: ${a.join(", ")||"none"})`}function rV(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function sa(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function iV(e,t,r,i){let n=df(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=ff(n,QB,"Native Supervisor overlay");if(a)return a;if(i.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(i.parent!==t.name)return`Native Supervisor overlay parent ${i.parent} does not match ${t.name}`;let o=df(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=ff(o,ZB,"Native Supervisor integration");if(s)return s;if(i.integration.headCommit!==i.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=df(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=ff(c,tV,"Native Supervisor finalVerification");if(l)return l;if(i.finalVerification.status!=="pending"||i.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==r.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[u,d]of n.children.entries()){let f=df(d,`Native Supervisor child ${u}`);if(!f)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:h,contractHash:m,...p}=f,v=ff(p,eV,`Native Supervisor child ${u}`);if(v)return v;let g=r.children[u],N=g.covers.length>0?g.covers.map(w=>({id:w,source:r.acceptance_index?.[w]?.source??"brief.md",text:r.acceptance_index?.[w]?.text??w})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(h!==void 0&&JSON.stringify(h)!==JSON.stringify(N)||m!==void 0&&m!==O("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${g.name} acceptance scope does not match the legacy contract`;if(f.name!==g.name||f.summary!==g.summary||!rV(f.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let E=g.depends_on.length===0?"ready":"pending";if(f.status!==E)return`Native Supervisor child ${g.name} has progressed beyond its initial ${E} status`;if(f.baseCommit!==null||f.candidateCommit!==null||f.verifiedCommit!==null||f.integrationCommit!==null||f.verification!==null||f.blocker!==null||f.projectRoot!==null||f.task!==null)return`Native Supervisor child ${g.name} contains execution progress`;if(!Array.isArray(f.checks)||f.checks.length!==0)return`Native Supervisor child ${g.name} contains integration checks`}return null}async function ca(e){let t=$d(e.paths,e.state.name),r;try{let c=await Qv.lstat(t);if(!c.isFile()||c.isSymbolicLink())return sa(t,"","Native Supervisor overlay is not a regular file");r=await Qv.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:sa(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return sa(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=XB.join(e.paths.changesDir,e.state.name),a;try{a=await ea({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return sa(t,r,`Native children contract cannot be validated; restore children.yaml and retry next: ${c.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:r};let o;try{o=await Ot(e.paths,e.state.name)}catch(c){return sa(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return sa(t,r,"Native Supervisor overlay disappeared during inspection");let s=iV(i,e.state,a.contract,o);return s?sa(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}async function AR(e){let t=await ca({paths:e.paths,state:e.state});if(t.status!=="repairable-legacy-overlay"||t.snapshot!==e.expected.snapshot)throw new Error("Native Supervisor overlay changed before the safe repair could be applied");await Qv.rm(t.file,{force:!1})}Er();js();function nV(e,t){let r=ae(e.projectRoot);if(t.workspace.change_branch!==null){if(!r.isGitWorktree)return"The portable change requires a Git branch/worktree";if(r.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:r.isGitWorktree?t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function aV(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function oV(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:Oi(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Jr(t),completed_at:i});return Qe({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?aV(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 sV(e){try{let t=await Wd(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 TR(e){return de(e.paths,`recover portable change ${e.name}`,async()=>{let t=await si(e.paths,e.name);if(t.status==="done")return await Gd({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let r=nV(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await ca({paths:e.paths,state:t});if(i.status==="incompatible")return{state:t,local:null,action:"await-user",reason:"overlay-incompatible",message:i.message};let n=!1;i.status==="repairable-legacy-overlay"&&(await AR({paths:e.paths,state:t,expected:i}),n=!0);let a=mn(e.paths,e.name),o=await sV(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason;if(s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed"&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(m=>m.status==="planned"||m.status==="running"?{...m,status:"interrupted"}:m)},await ai(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await Gd({paths:e.paths,state:t}),{state:t,local:o.local,action:"resume-stable-boundary",reason:s,message:n?"Removed a stale legacy Supervisor overlay and resumed the portable state.":"Native local execution overlay matches the portable state."};let l=s==="interrupted"?o.local?.checks.find(m=>m.status==="interrupted"&&!m.repeatable):void 0;if(l){let m=xv({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Hi({file:Ht(e.paths,t.name),expectedStateVersion:t.state_version,next:m,containedRoot:e.paths.nativeRoot}),await _R.rm(IR.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let p=fn({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await ai(a,p,{containedRoot:e.paths.runtimeDir}),{state:t,local:p,action:"resume-stable-boundary",reason:s,message:`Native check ${l.id} was not repeatable; the change returned to Build for a new candidate.`}}let u=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",d=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",f=u||d;if(f){let m=oV(t,d?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",d);t=await Hi({file:Ht(e.paths,t.name),expectedStateVersion:t.state_version,next:m,containedRoot:e.paths.nativeRoot})}let h=fn({portableState:t,projectRoot:e.paths.projectRoot,branch:ae(e.paths.projectRoot).currentBranch});return await _R.mkdir(IR.dirname(mn(e.paths,t.name)),{recursive:!0}),await ai(a,h,{containedRoot:e.paths.runtimeDir}),await Gd({paths:e.paths,state:t}),{state:t,local:h,action:f?"reverify":"resume-stable-boundary",reason:s,message:f?"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.`}})}Lt();Eo();So();import{promises as HR}from"node:fs";import cV from"node:path";import jR from"node:path";function $R(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function OR(e,t){let r=e.acceptance.reduce((i,n)=>({...i,[n.result]:i[n.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:r,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:$R(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},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(i=>i.outcome==="fail"&&i.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:$R(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(i=>i.source).filter(i=>i!==null)].slice(0,16).map(i=>jR.relative(t.projectRoot,jR.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}function lV(e,t,r){return`native-details-v2.${e}.${t}.${r.toString(36)}`}function uV(e,t,r){if(!e)return 0;let i=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!i||Number(i[1])!==t||Number(i[2])!==r)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(i[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function dV(e,t,r){return[...e.acceptance.map(i=>({kind:"acceptance",value:i})),...e.spec_changes.map(i=>({kind:"spec-change",value:i})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(i=>({kind:"history",value:i})),{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(i=>({kind:"supervisor-child",value:pV(i,r)})),...t.history.map(i=>({kind:"supervisor-history",value:mV(i,r)}))]:[]]}function fV(e){return e.acceptance.reduce((t,r)=>({...t,[r.result]:t[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function DR(e,t){let r=ae(e.projectRoot),i=null;return t.workspace.change_branch!==null&&(r.isGitWorktree?r.currentBranch!==t.workspace.change_branch&&(i=`Expected branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}.`):i="The Native change requires a registered Git worktree."),i===null&&t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree&&(i="The Native change requires its linked worktree."),{projectRoot:cV.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:i===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:i}}function hV(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(r=>[r.projectRoot,r.task?.projectRoot])].filter(r=>!!r).map(r=>r.replaceAll("/","\\")).sort((r,i)=>i.length-r.length)}function hf(e,t){return e===null?null:t.reduce((r,i)=>r.replaceAll(i,"<worktree>").replaceAll(i.replaceAll("\\","/"),"<worktree>"),e)}function pV(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:hf(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function mV(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:hf(e.summary,t)??""}}async function la(e){let t=await jP(e),r=OR(t.state),i=t.state.status==="active"&&t.state.loop.stage!=="done",n=await ta({paths:e.paths,state:t.state}),a=await ca({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await Ot(e.paths,e.name,{diagnostics:!0}),s=o?{...DR(e.paths,t.state),projectRoot:"."}:DR(e.paths,t.state),c=uf(t.state,n),l=s.bindingState==="mismatch"?{...c,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...c.runnerAction,kind:"none"}}:c,u=o?hV(e.paths,o):[],d=o?(()=>{let m=o.children.filter(({status:w})=>w==="pending"||w==="ready").length,p=o.children.filter(({status:w})=>w==="active"||w==="verified").length,v=o.children.filter(({status:w})=>w==="integrated"||w==="archived").length,g=o.children.filter(({status:w})=>w==="blocked"||w==="needs-reverify").length,N=o.children.filter(({status:w})=>w==="active"||w==="blocked"||w==="needs-reverify").slice(0,16).map(w=>({name:w.name,summary:w.summary,projectRoot:w.task?.projectRoot??w.projectRoot?"<worktree>":null,reason:hf(w.blocker,u)})),E=o.children.flatMap(({blocker:w})=>{let S=hf(w,u);return S?[S]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:o.children.length,waiting:m,working:p,integrated:v,blocked:g,active:N,agents:{working:o.children.filter(({task:w})=>w!==null).length,completed:v},risks:E,nextAction:o.finalVerification.status==="passed"?"final-delivery":o.finalVerification.status==="pending"&&v===o.children.length?"parent-verification":m>0?"dispatch-ready-child":g>0?"resolve-blocker":"continue-supervisor"}})():null,f=e.details?(()=>{let m=o?.stateVersion??0,p=dV(t.state,o,u),v=uV(e.cursor,t.state.state_version,m),g=p.slice(v,v+32),N=v+g.length<p.length?lV(t.state.state_version,m,v+g.length):null;return{items:g,nextCursor:N,supervisorStateVersion:m}})():null,h=o?{schema:o.schema,parent:o.parent,integration:{branch:o.integration.branch,targetBranch:o.integration.targetBranch},finalVerification:{status:o.finalVerification.status,summary:o.finalVerification.summary},summary:d}: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:fV(t.state),unresolvedAcceptanceIds:r.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:r.blockers,workspace:s,localExecution:{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{childSummary:n.children.reduce((m,p)=>({...m,[p.status]:(m[p.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...h?{supervisor:h}:{},...a.status==="repairable-legacy-overlay"||a.status==="incompatible"?{supervisorOverlay:{status:a.status,message:a.message,repairCommand:a.status==="repairable-legacy-overlay"?`comet native doctor ${e.name} --repair`:null}}:{},continuation:l,...e.details?{details:{stateVersion:t.state.state_version,...o?{supervisorStateVersion:f.supervisorStateVersion}:{},items:f.items,nextCursor:f.nextCursor,nextPageArgs:f.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",f.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}async function LR(e){let t;try{t=await HR.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}let r=[];for(let i of t)if(!(!i.isDirectory()||i.isSymbolicLink()))try{let n=await HR.readFile(`${Yt(e,i.name)}/comet-state.yaml`,"utf8");/^schema:\s*comet\.native\.v4\s*$/mu.test(n)&&r.push(i.name)}catch(n){if(n.code!=="ENOENT")throw n}return r.sort((i,n)=>i.localeCompare(n,"en"))}La();ys();import Lc from"path";import{realpathSync as _V}from"fs";Lt();var di={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function MR(e){return e?e.command?`${di.next} ${e.command}`:e.ask_user?`${di.next} ${e.ask_user}`:null:null}function FR(e,t){let r=[e.summary],i=MR(e.next);return i&&r.push(i),e.user_message&&r.push("",di.relay,e.user_message),t!==void 0&&r.push("",di.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
264
|
+
`}function WM(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function zd(e){let t;try{t=await MM.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=WM(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function Jd(e){await ge(e.file,qM(e.state,e.supervisor))}Q();Nn();ii();ot();var CP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,zM="comet-state.yaml",JM="state.json",n9=zc("en");function Yt(e,t){if(!CP.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=pn.join(e.changesDir,t);if(!D(e.changesDir,r))throw new Error("Native change path escaped");return r}function Ht(e,t){return pn.join(Yt(e,t),zM)}function mn(e,t){return pn.join(Ye(e,t),JM)}async function vn(e,t){try{let r=await ra.readFile(Ht(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function xP(e){return ae(e).currentBranch}async function ci(e,t){return Be(Ht(e,t))}async function AP(e){let t=await Hi({file:Ht(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=pn.join(Yt(e.paths,t.name),"verification.md");await T(e.paths.nativeRoot,r),await ra.rm(r,{force:!0})}return t}async function GM(e){let t=Yt(e.paths,e.state.name),r=pn.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await ra.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!CP.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=pn.join(t,...s.split("/")),l=await ra.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=pn.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let f=await ra.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(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function UM(e){let t=Yt(e.paths,e.state.name),r=await te({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(dm(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let a of e.specChanges){if(a.source===null){n.push({...a,contentHash:null});continue}let o=await te({root:t,ref:a.source,maxBytes:null,includeHash:!1});i.push({capability:a.capability,source:o.ref,markdown:o.text}),n.push({...a,contentHash:O("comet.native.shape-artifact-content.v1",o.text)})}return{acceptance:hu({briefMarkdown:r.text,specs:i}),formalHash:O("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:O("comet.native.shape-artifact-content.v1",r.text)},specs:n})}}function KM(e){return O("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function _P(e){let t=await GM(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:l})=>l)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((l,u)=>{let d=e.state.spec_changes[u];return d!==void 0&&l.capability===d.capability&&l.source===d.source&&(l.operation===d.operation||r?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await UM({...e,specChanges:t})}catch{return{drifted:!0,reason:"Native Shape artifacts changed or became invalid"}}let{acceptance:a}=n,o=e.state.acceptance.map(({source:l,text:u})=>({source:l,text:u}));if(!ZN(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await ea({changeDir:Yt(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:Ld({...e.state,acceptance:a})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return e.state.phase==="shape"&&e.state.status==="await-user"&&e.state.loop.next_action==="confirm-shape"&&e.state.shape_confirmation_hash===void 0?{drifted:!0,reason:"Native Shape confirmation fingerprint is missing"}:e.state.shape_confirmation_hash!==void 0&&KM({formalHash:n.formalHash,childrenHash:s?.hash??null,coordinationMode:e.state.coordination_mode})!==e.state.shape_confirmation_hash?{drifted:!0,reason:"Native Shape artifacts changed"}:(s?Md({acceptance:a,children:s.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function IP(e){let t=await ci(e.paths,e.name),r=await Da(e.paths,{kind:"archive",change:e.name}),i=r?.kind==="archive"?r:null;if(!i&&(t.archived||t.verification===null||t.verification_result!=="pass"))return{state:t,action:"none"};let n=await Ot(e.paths,e.name);if(i&&n?.finalVerification.status==="pending"){if(i.journal.status!=="prepared"||i.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await ra.rm(i.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||n?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=uP(n);if(i||a.stateVersion!==n.stateVersion){let o=await YM({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; the final full verification will resume automatically."});return i&&await ra.rm(i.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await Xn(e.paths,dP(n,t)),{state:t,action:"recorded-final-verification"}}async function TP(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...Oi(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Gr(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await AP({paths:e.paths,previous:t,next:i});return await oi(mn(e.paths,t.name),fn({portableState:n,projectRoot:e.paths.projectRoot,branch:xP(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function YM(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);if(t.verification===null||t.verification_result!=="pass")throw new Error("Native Supervisor recovery requires a persisted final verification pass");let i={...Oi(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Gr(e.reason),completed_at:new Date().toISOString()}),phase:"verify",status:"active",state_version:t.state_version+1,acceptance:t.acceptance.map(a=>({...a,result:"pending",reason:null})),blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}},n=await AP({paths:e.paths,previous:t,next:i});return await oi(mn(e.paths,t.name),fn({portableState:n,projectRoot:e.paths.projectRoot,branch:xP(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Gd(e){if(e.state.verification===null)return"not-applicable";let t=pn.join(Yt(e.paths,e.state.name),"verification.md");return await zd({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await Jd({file:t,state:e.state}),"rebuilt")}async function jP(e){let t=await ci(e.paths,e.name),r=mn(e.paths,e.name);try{let i=await Wd(r);return i===null?{state:t,local:null,localStatus:"missing"}:i.change!==t.name||i.basedOnStateVersion!==t.state_version?{state:t,local:null,localStatus:"stale"}:{state:t,local:i,localStatus:"available"}}catch(i){return i.code==="ENOENT"?{state:t,local:null,localStatus:"missing"}:{state:t,local:null,localStatus:"invalid"}}}var f9=16*1024;async function Ud(e){let t=await dv(e.projectRoot);return t.status==="missing"||t.selection.workflow!=="native"?null:(Uu(t.selection.change),t.selection)}function $P(e){return Cd(e.projectRoot)}async function Cc(e,t){return await Ta(e.projectRoot),GE(e.projectRoot,"native",t)}Mn();var B9=16*1024*1024,Kd=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},xc=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function HP(e,t){let r=t.operations.find(i=>i.id==="archive-change");if(!r||r.type!=="move")throw new Error(`Archive transaction ${t.id} has no archive move`);return Po.resolve(e.nativeRoot,...r.target.split("/"))}async function DP(e,t,r){let i=await qi(e,t.id);if(i.some(v=>v.type==="archive-finalized"))return;let n=i.some(v=>v.type==="archive-finalization-started");if(t.schema==="comet.native.transaction.v2"&&!n){let v=t.operations.find(N=>N.id==="archive-change");if(!v||v.type!=="move"||!v.expectedSourceHash)throw new Error(`Archive transaction ${t.id} has no content-bound archive move`);let g=await yr(HP(e,t));if(g?.kind!=="directory"||g.hash!==v.expectedSourceHash)throw new Error(`Native Archive content changed before finalization for transaction ${t.id}`)}let a=HP(e,t),o=Po.join(a,Le),s=await Vk(o);if(!t.change||s.name!==t.change)throw new Error(`Archive transaction ${t.id} change mismatch`);let c=M(e,s.name),l=await Ve(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 v=fg(Hr,l,new Set,Mm,void 0);if(!v.action)throw new Error(v.reason??"Native archive produced no action");u=hg(Hr,v.state,{actionId:v.action.id,status:"succeeded",summary:`Archived Native change ${s.name}`},Mm,void 0)}let d=F(`archive:${t.id}:${s.name}`),f=await dt(c,u.trajectoryRef),h=f.filter(v=>v.data.transactionId===t.id);if(t.schema==="comet.native.transaction.v2"&&(h.length>1||h.some(v=>v.type!=="state_transitioned")))throw new Error(`Native Archive trajectory has a transaction id collision: ${t.id}`);let m=h.find(v=>v.type==="state_transitioned"),p={previousPhase:"archive",nextPhase:null,evidenceHash:d,summary:`Archived Native change ${s.name}`,transactionId:t.id};if(m&&t.schema==="comet.native.transaction.v2"&&(!XM(m.data,p)||m.runId!==u.runId||m.timestamp!==t.createdAt||m!==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 Rd(e,t,"archive-finalization-started"),await r?.afterFinalizationStarted?.(t)):await qa(e,t,"archive-finalization-started")),!s.archived){let v={...s,archived:!0};await Bk(o,v)}m||(m=await rn({changeDir:c,run:u,type:"state_transitioned",data:p,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}})),await Un({changeDir:c,run:u,trajectoryOffset:m.sequence,evidenceHash:d,...t.schema==="comet.native.transaction.v2"?{now:new Date(t.createdAt)}:{}}),await Vn(c,u),await Cc(e,s.name),t.schema==="comet.native.transaction.v2"?await Rd(e,t,"archive-finalized"):await qa(e,t,"archive-finalized")}async function Tv(e,t){let r=Ye(e,t);try{let i=await OP.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`Native Runtime cleanup target is not a real directory: ${r}`);return await T(e.runtimeDir,r),await OP.rm(r,{recursive:!0,force:!0}),null}catch(i){return i.code==="ENOENT"?null:`Archived change ${t}, but local Runtime cleanup failed: ${i.message}`}}async function QM(e,t,r){if(t.schema==="comet.native.transaction.v2"){if(!(await qi(e,t.id)).some(c=>c.type==="operation-started")){let c=await kd({paths:e,name:t.change,now:new Date(t.createdAt)});if(!c.ready||c.preflightHash!==t.preflightHash)throw new xc(c,"Native Archive facts changed before the first transaction operation")}let o=await qE(e,t,{...r,beforeArchiveChangeMove:async c=>{await r?.beforeArchiveChangeMove?.(c);let l=await We(e,t.change),u=await bd({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 DP(e,o,r);let s=await Rd(e,o,"commit");return{journal:s,runtimeCleanupWarning:await Tv(e,s.change)}}let i=await Rb(e,t);await DP(e,i,r);let n=await qa(e,i,"commit");return{journal:n,runtimeCleanupWarning:n.change?await Tv(e,n.change):null}}function ZM(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(Po.resolve(t.projectRoot)!==Po.resolve(e.projectRoot)||Po.resolve(t.nativeRoot)!==Po.resolve(e.nativeRoot))throw new Error(`Transaction ${t.id} belongs to a different Native root`)}async function LP(e){return de(e.paths,`recover archive ${e.transactionId}`,async()=>{let t=await ji(e.paths,"archive",`recover archive ${e.transactionId}`);try{let r=await At(e.paths,e.transactionId),i=r.schema==="comet.native.transaction.v2"?await lv(e.paths,e.transactionId):r;return ZM(e.paths,i),i.status==="committed"?(i.change&&await Tv(e.paths,i.change),i):i.status==="rolled-back"?i:e.strategy==="continue"?(await QM(e.paths,i)).journal:i.schema==="comet.native.transaction.v2"?WE(e.paths,i):Au(e.paths,i)}finally{await $i(t)}},{allowedTransactionId:e.transactionId})}ke();ot();import{promises as pF}from"fs";xs();Xe();ke();Ya();Q();Ui();Js();async function MP(e,t){let r=[],i=M(e,t.name),n=Ii(i,_t.stateRef),a;try{a=await Ve(i)}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")&&r.push({code:"run-state-missing",message:"Native change references a missing Run state",path:n}),r;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&&r.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")&&r.push({code:"run-action-pending",message:"Native Run has an unresolved pending action",path:n}),a.currentStep!==t.phase&&r.push({code:"run-phase-mismatch",message:`Native Run step ${a.currentStep??"(none)"} does not match phase ${t.phase}`,path:n});let o=Ii(i,a.trajectoryRef),s=await Qa(e,t.name);if(s.status==="repairable")return r.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}),r;if(s.status==="invalid")return r.push({code:"trajectory-invalid",message:`Native trajectory is invalid at line ${s.line}: ${s.message}`,path:o}),r;let c;try{if(c=await dt(i,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 r.push({code:"trajectory-invalid",message:`Native trajectory is invalid: ${u.message}`,path:o}),r}let l=Ii(i,a.checkpointRef);try{let u=await Xa(i,a.checkpointRef);u?(u.runId!==a.runId||u.stateVersion!==a.iteration||u.trajectoryOffset!==c.length)&&r.push({code:"checkpoint-mismatch",message:"Native Run checkpoint does not match Run state and trajectory",path:l}):r.push({code:"checkpoint-missing",message:"Native Run checkpoint is missing",path:l})}catch(u){r.push({code:"checkpoint-invalid",message:`Native Run checkpoint is invalid: ${u.message}`,path:l})}return r}Fn();_r();var eF=/^(?:run-|trajectory-|checkpoint-(?:missing|mismatch|invalid|progress-invalid)|transition-(?:incomplete|invalid))/u;function tF(e){return/^[A-Za-z0-9_./:=+@-]+$/u.test(e)?e:JSON.stringify(e)}function rF(e){return e?e.map(tF).join(" "):null}function iF(e){if(e===null)return null;let t=e.match(/"(?:[^"\\]|\\.)*"|'[^']*'|\S+/gu);return!t||t[0]!=="comet"?null:t.map(r=>{if(r.startsWith('"')&&r.endsWith('"'))try{return JSON.parse(r)}catch{return r.slice(1,-1)}return r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1):r})}function Xt(e,t,r,i={}){return{input:e,flags:t,required:i.required??!0,placeholder:r,...i.choices?{choices:i.choices}:{},...i.repeatable?{repeatable:!0}:{},...i.alternativeGroup?{alternativeGroup:i.alternativeGroup}:{}}}function nF(e){return e.map(t=>Xt(t,[],null))}function aF(e){let t=["comet","native","next",e.name,"--summary","<summary>"],r=[Xt("summary",["--summary"],"<summary>")];if(e.phase==="shape")return t.push("--confirmed"),r.push(Xt("shared-understanding-confirmation",["--confirmed"],null)),{commandArgs:t,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:r};if(e.phase==="build"){t.push("--artifact","<project-relative-path>"),r.push(Xt("artifact-or-no-code-reason",["--artifact"],"<project-relative-path>",{repeatable:!0,alternativeGroup:"build-evidence"}),Xt("artifact-or-no-code-reason",["--no-code-reason"],"<reason>",{alternativeGroup:"build-evidence"}));let i=["summary","artifact-or-no-code-reason"];return e.approval!=="confirmed"&&(t.push("--confirmed"),i.push("shared-understanding-confirmation"),r.push(Xt("shared-understanding-confirmation",["--confirmed"],null))),{commandArgs:t,requiredInputs:i,inputOptions:r}}return e.phase==="verify"?(t.push("--result","<pass|fail>","--report","<change-relative-path>"),r.push(Xt("verification-result",["--result"],"<pass|fail>",{choices:["pass","fail"]}),Xt("verification-report",["--report"],"<change-relative-path>")),{commandArgs:t,requiredInputs:["summary","verification-result","verification-report"],inputOptions:r}):{commandArgs:t,requiredInputs:[],inputOptions:[]}}function nt(e,t){let r=t.commandArgs===void 0?iF(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?rF(r??null):t.command,commandArgs:r??null,requiresUserDecision:t.requiresUserDecision??!1,requiredInputs:t.requiredInputs??[],inputOptions:t.inputOptions??nF(t.requiredInputs??[])}}function Yd(e){let r=(e.findings??[]).filter(d=>!Za(d.code)),i=r.find(d=>d.requiresUserDecision),n=r.find(d=>d.repairCommand!==null||eF.test(d.code)),a=r.find(d=>d.code==="repair-iteration-limit"||d.code==="repair-override-exhausted"),o=r.find(d=>d.code==="repair-stagnation-stop"),s=r.find(d=>d.requiredAction==="return-to-bound-working-directory"||d.requiredAction==="repair-workspace-binding"),c=r.find(d=>d.code==="runtime-missing"),l=[...new Set(r.map(d=>d.requiredAction))].sort();if(e.done)return nt(e.state,{disposition:"done",action:"none",commandArgs:null});if(a)return nt(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:["repair-continuation-decision"],inputOptions:[Xt("repair-continuation-decision",[],null,{choices:["continue","change-contract","stop"]})]});if(i)return nt(e.state,{disposition:"await-user",action:"work-phase",commandArgs:null,requiresUserDecision:!0,requiredInputs:l});if(o)return nt(e.state,{disposition:"blocked",action:"repair",commandArgs:null,requiredInputs:["new-repair-hypothesis"]});if(s)return nt(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l});if(c)return nt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:["comet","native","next",e.state.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[Xt("summary",["--summary"],"<summary>")]});if(n)return nt(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 nt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:d,requiredInputs:["summary"],inputOptions:[Xt("summary",["--summary"],"<summary>")]})}if(e.state.phase==="build"&&e.state.verification_result==="fail")return nt(e.state,{disposition:"continue",action:"work-phase",commandArgs:null,requiredInputs:["repair-verification-gaps"]});if(r.length>0)return e.state.phase==="archive"?nt(e.state,{disposition:"blocked",action:"none",commandArgs:null,requiredInputs:l}):l.includes("refresh-verification-receipts")?nt(e.state,{disposition:"continue",action:"work-phase",commandArgs:["comet","native","receipt","refresh",e.state.name,"--apply"],requiredInputs:l}):nt(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"),nt(e.state,{disposition:"await-user",action:"archive",commandArgs:d,command:null,requiresUserDecision:!0,requiredInputs:["archive-confirmation"],inputOptions:[Xt("archive-confirmation",["--confirmed"],null,{choices:["confirm","keep-active"]})]})):nt(e.state,{disposition:"continue",action:"archive",commandArgs:d})}return nt(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=aF(e.state);return nt(e.state,{disposition:"continue",action:"advance-phase",commandArgs:u.commandArgs,requiredInputs:u.requiredInputs,inputOptions:u.inputOptions})}ke();Q();_r();import Ac from"path";var FP=8,oF={"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 sF(e){let t=oF[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"}:Za(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 cF(e,t,r){if(!r.path)return null;let i;if(Ac.isAbsolute(r.path)?i=Ac.resolve(r.path):/^(?:brief-|verification-|spec-source)/u.test(r.code)?i=Ac.resolve(se(e,t.name),...r.path.split(/[\\/]/u)):i=Ac.resolve(e.projectRoot,...r.path.split(/[\\/]/u)),!D(e.projectRoot,i))return null;let n=Ac.relative(e.projectRoot,i).replaceAll("\\","/");return n===""?".":n}function lF(e,t,r){return e==="next"?`comet native next ${t.name} --summary "<summary>"${r==="contract-changed-after-approval"||r==="shape-confirmation-required"||r==="approval-confirmation-required"?" --confirmed":""}`:e==="status"?`comet native status ${t.name} --details`:null}function jv(e){return e.findings.map(t=>{let r=sF(t.code);return{code:t.code,message:t.message,severity:r.severity,path:cF(e.paths,e.state,t),requiredAction:r.requiredAction,retryCommand:lF(r.retry,e.state,t.code),repairCommand:r.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,r)=>{let i={error:0,warning:1,info:2};return i[t.severity]-i[r.severity]||t.code.localeCompare(r.code)||(t.path??"").localeCompare(r.path??"")||t.message.localeCompare(r.message)})}function $v(e){let t=[...new Set(e.map(r=>r.code))];return{total:e.length,errors:e.filter(r=>r.severity==="error").length,warnings:e.filter(r=>r.severity==="warning").length,info:e.filter(r=>r.severity==="info").length,requiresUserDecision:e.some(r=>r.requiresUserDecision),codes:t.slice(0,FP),truncated:t.length>FP}}var BP=240,VP=8,Xd=50;function qP(e){let t=Array.from(e);return t.length<=BP?e:`${t.slice(0,BP-1).join("")}…`}function uF(e){let t=e.indexOf(":");return t<0?e:e.slice(0,t)}function dF(e){let t=[...new Set(e.map(uF))],r={freshness:e.length===0||e.length===1&&e[0]==="no-checkpoint"?"fresh":"stale",codes:t.slice(0,VP),reasonCount:e.length,codesTruncated:t.length>VP};return{inspection:r,inspectionDetails:{...r,reasons:e.slice(0,Xd),reasonsTruncated:e.length>Xd}}}async function WP(e){let t=null;try{let s=await sn(e.paths,e.state.name);s&&(t={code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${s.id} requires deterministic recovery`,path:on(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:on(e.paths,e.state.name)}}let r=await NE({paths:e.paths,name:e.state.name,stateRevision:e.state.revision}),i=t?[t.code,...r.reasons]:r.reasons,n=dF(i);if(!r.checkpoint)return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:null,checkpointDetails:null,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:an.maxArtifacts};let a={id:r.checkpoint.id,createdAt:r.checkpoint.createdAt,phase:r.checkpoint.phase,stateRevision:r.checkpoint.stateRevision,summary:qP(r.checkpoint.summary),nextAction:qP(r.checkpoint.nextAction),artifactCount:r.checkpoint.artifactCount},o=r.manifest?{...a,summary:r.checkpoint.summary,nextAction:r.checkpoint.nextAction,manifestHash:r.checkpoint.manifestHash,manifestRef:r.checkpoint.manifestRef,artifacts:r.manifest.artifacts,totalBytes:r.manifest.totalBytes}:null;return{inspection:n.inspection,inspectionDetails:n.inspectionDetails,checkpoint:a,checkpointDetails:o,findings:t?[t,...r.findings]:r.findings,maxCheckpointArtifacts:an.maxArtifacts}}Q();ii();Ui();ho();Xi();async function fF(e,t){let r=M(e,t.name),i=await Ve(r);if(!i||!t.run_id||i.runId!==t.run_id)throw new Error("Native repair history Run state is missing or mismatched");let n=await Xa(r,i.checkpointRef);if(!n||n.runId!==i.runId||n.stateVersion!==i.iteration)throw new Error("Native repair history checkpoint is missing or mismatched");return{trajectory:await dt(r,i.trajectoryRef),committedTrajectoryOffset:n.trajectoryOffset,runId:i.runId}}async function hF(e,t){let r=await fF(e,t);return{committed:r,latest:YS(r),history:KS(r)}}async function zP(e,t,r){if(t.phase!=="build"||t.verification_result!=="fail")return null;let i=await hF(e,t),n=i.latest;if(!n)return null;let a=i.history.filter(c=>c.kind==="failure"),o=a.length>=r,s=n.disposition==="hard-stop"&&!o?"continue":n.disposition;return{disposition:o?"hard-stop":s,signatureHash:n.signatureHash,overrideRecorded:i.history.some(c=>c.kind==="override"&&c.signatureHash===n.signatureHash),failedAcceptanceIds:[...n.failedAcceptanceIds],failedCheckIds:[...n.failedCheckIds],totalVerifyFailures:a.length,maxVerifyFailures:r,remainingVerifyFailures:Math.max(0,r-a.length)}}ii();_r();yt();Q();var mF=/^native-status-v1\.([a-f0-9]{64})\.([0-9a-z]+)\.([a-f0-9]{64})$/u,Ro=Object.freeze({maxItems:24,maxChanges:4096,maxSerializedBytes:512*1024});function Ov(e){return e.map(t=>/^[A-Za-z0-9_./:=+@-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}async function vF(e){return(await Ud(e))?.change??null}function gF(e,t,r=!1,i){return Yd({state:e,archiveReady:t,evidenceRetreat:r}).command}async function wF(e,t){let r=se(e,t.name),i=[...(await fm(r,t.brief)).findings,...(await Gk(e,t)).findings,...await MP(e,t)];if(t.phase==="shape"||t.phase==="build")try{let n=await Ka(e,t.name);if(n===null)i.push({code:"baseline-snapshot-missing",message:"Native baseline is missing; restore a trusted baseline before advancing"});else{let a=await Hu(e,n);a.complete||i.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){i.push({code:"baseline-snapshot-invalid",message:`Native baseline could not be inspected safely: ${n.message}`})}if(t.phase==="build")try{let n=await wo({changeDir:r,briefRef:t.brief,specChanges:t.spec_changes});(t.approved_contract_hash??null)!==n.contract.contractHash&&i.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){i.push({code:"contract-inspection-invalid",message:`Native approved contract could not be inspected safely: ${n.message}`})}try{await ni(e,t.name)&&i.unshift({code:"transition-incomplete",message:"Native phase transition recovery is pending"})}catch(n){i.unshift({code:"transition-invalid",message:`Native transition journal is invalid: ${n.message}`})}return t.verification_report?i.push(...(await hm(r,t.verification_report)).findings):(t.phase==="verify"||t.phase==="archive"||t.verification_result==="pass")&&i.push({code:"verification-report-missing",message:"Native change has no verification report"}),i}async function Hv(e,t,r){let i=await vF(e)===t,n=await Ss(e,t),a=await Ak(e,t),o;try{let y=await Tr(e,t);if(y.status==="migration-required"&&y.state)return{name:t,phase:y.state.phase,revision:"revision"in y.state?y.state.revision:null,approval:y.state.approval,verificationResult:y.state.verification_result,specChanges:y.state.spec_changes.length,selected:i,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:y.schema,migrationRequired:!0,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message};if(y.status!=="current"||!y.state)return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,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:y.schema,minimumRuntimeVersion:y.minimumRuntimeVersion,error:y.message??`Native change ${t} is incompatible`};o=y.state}catch(y){return{name:t,phase:"invalid",revision:null,approval:null,verificationResult:"pending",specChanges:0,selected:i,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:y.message}}if(n.status!=="available"){let y={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=jv({paths:e,state:o,findings:[y]}),L=Yd({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:i,nextCommand:L.command,archiveReady:!1,inspection:{freshness:"stale",codes:[y.code],reasonCount:1,codesTruncated:!1},findingSummary:$v(P),detailsCommand:`comet native status ${o.name} --details`,checkpoint:null,continuation:L,workspace:a,runtime:n,...r?.details?{findings:P}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...n.status==="invalid"?{error:y.message}:{}}}let s=await WP({paths:e,state:o}),c=null,l=[];if(o.phase==="build"&&o.verification_result==="fail")try{if(c=await zP(e,o,r?.maxVerifyFailures??5),c&&(c.disposition==="manual-stop"||c.disposition==="hard-stop")){let y=c.disposition==="hard-stop"?"repair-iteration-limit":c.overrideRecorded?"repair-override-exhausted":"repair-stagnation-stop";l.push({code:y,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(r?.details&&(o.phase==="build"||o.phase==="verify"||o.phase==="archive"))try{let y=await wo({changeDir:se(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 je=await vo(e,o.name,o.verification_evidence);for(let me of je.acceptanceTrace.entries)P.set(me.acceptanceId,me.status==="failed"?"failed":me.status==="missing"?"missing":"satisfied")}let L=JN({criteria:y.contract.acceptance,acceptanceHash:y.contract.acceptanceHash,verificationStatuses:P,failedCheckIds:c?.failedCheckIds??[],...r.acceptanceCursor?{cursor:r.acceptanceCursor}:{}}),H=L.nextCursor?["comet","native","status",o.name,"--details","--acceptance-cursor",L.nextCursor,"--project-root",e.projectRoot]:null;u={...L,...H?{nextPageCommand:Ov(H),nextPageArgs:H}:{}}}catch(y){if(r.acceptanceCursor)throw y;u=void 0}let d=[];if(r?.includeConflictFindings!==!1)try{let y=await ld(e,o.name,{tolerateInvalidSiblings:!0});d.push(...y.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 y=await Tt(e,o.name);if(y)if(y.schema==="comet.native.workspace.v3"){let P=await to({paths:e,identity:y});P.state==="drifted"&&P.code&&f.push({code:P.code,message:P.message??"Native workspace binding is no longer valid"})}else{let P=await Ks({paths:e,identity:y});f.push(...P.findingCodes.map(L=>({code:L,message:`Native workspace advisory changed: ${L} (${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=[],m=!1;if(o.phase==="verify"){let y=await AE({paths:e,state:o});m=y.freshness!=="fresh",h.push(...y.findingCodes.map(P=>({code:P,message:`Native Verify implementation scope is not current: ${P}`})))}let p=null,v=[];if(o.phase==="archive")try{p=await kd({paths:e,name:o.name}),v.push(...p.findingCodes.map(y=>({code:y,message:`Native Archive is blocked: ${y}`})))}catch{v.push({code:"archive-preflight-invalid",message:"Native Archive preflight could not be recomputed safely"})}let g=[...await wF(e,o),...s.findings,...d,...f,...h,...l,...v].filter((y,P,L)=>L.findIndex(H=>H.code===y.code&&H.path===y.path)===P),N=jv({paths:e,state:o,findings:g}),E=N.filter(y=>!Za(y.code)),w=o.phase==="archive"&&p?.ready===!0&&E.length===0,S=m||o.phase==="archive"&&(p?.findingCodes??[]).some(y=>new Set(["verification-evidence-stale","verification-evidence-invalid","verification-evidence-missing","verification-contract-stale","verification-implementation-stale","verification-report-stale","verification-state-mismatch"]).has(y)),k=N.some(y=>y.code==="trajectory-tail-incomplete"||y.code==="trajectory-invalid"||y.requiredAction==="return-to-bound-working-directory"||y.requiredAction==="repair-workspace-binding"),R=c?.disposition==="manual-stop"||c?.disposition==="hard-stop",b=N.find(y=>y.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:i,nextCommand:k||R?null:gF(o,w,S,r?.clarificationMode),archiveReady:w,inspection:s.inspection,findingSummary:$v(N),detailsCommand:`comet native status ${o.name} --details`,checkpoint:s.checkpoint,continuation:Yd({state:o,findings:N,archiveReady:w,evidenceRetreat:S,clarificationMode:r?.clarificationMode}),workspace:a,runtime:n,repair:c,...r?.details?{...u?{acceptancePage:u}:{},findings:N.slice(0,50),inspectionDetails:s.inspectionDetails,checkpointDetails:s.checkpointDetails,budgets:{maxFindings:50,maxInspectionReasons:Xd,maxCheckpointArtifacts:s.maxCheckpointArtifacts,findingsTruncated:N.length>50,inspectionReasonsTruncated:s.inspectionDetails.reasonsTruncated,checkpointArtifactsTruncated:!1}}:{},schema:o.schema,minimumRuntimeVersion:o.minimum_runtime_version,...b?{error:b.message}:{}}}async function yF(e){let t;try{t=await fr({root:e.nativeRoot,directory:e.changesDir,label:"Native status changes directory"})}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[],i=await pF.opendir(e.changesDir);try{for await(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink())&&(r.push(n.name),r.length>Ro.maxChanges))throw new Error(`Native status exceeds ${Ro.maxChanges} visible changes`)}finally{await i.close().catch(n=>{if(n.code!=="ERR_DIR_CLOSED")throw n})}return await t.verify(),r.sort()}function Qd(e,t){let r=t.toString(36),i=O("comet.native.status-cursor.v1",{namesHash:e,offset:t});return`native-status-v1.${e}.${r}.${i}`}function NF(e){if(e.cursor===void 0||e.cursor===null)return 0;let t=mF.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 r=Number.parseInt(t[2],36);if(!Number.isSafeInteger(r)||r<=0||r>=e.total||r.toString(36)!==t[2])throw new Error("Native status cursor offset is invalid");let i=O("comet.native.status-cursor.v1",{namesHash:e.namesHash,offset:r});if(t[3]!==i)throw new Error("Native status cursor integrity check failed");return r}async function bF(e,t){let r=await yF(e),i=O("comet.native.status-names.v1",r),n=NF({namesHash:i,total:r.length,cursor:t?.cursor}),a=await Promise.all(r.slice(n,n+Ro.maxItems).map(u=>Hv(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:r.length,offset:n,items:d,nextCursor:f<r.length?Qd(i,f):null,nextPageCommand:f<r.length?Ov(["comet","native","status","--cursor",Qd(i,f)]):null,nextPageArgs:f<r.length?["comet","native","status","--cursor",Qd(i,f)]:null,limits:{...Ro}};if(Buffer.byteLength(JSON.stringify(h),"utf8")>Ro.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<r.length?Qd(i,s):null,l=c?["comet","native","status","--cursor",c]:null;return{schema:"comet.native.status-page.v1",total:r.length,offset:n,items:o,nextCursor:c,nextPageCommand:l?Ov(l):null,nextPageArgs:l,limits:{...Ro}}}async function Dv(e,t){return(await bF(e,{clarificationMode:t?.clarificationMode,maxVerifyFailures:t?.maxVerifyFailures})).items}ad();ke();import{createHash as FF,randomUUID as BF}from"node:crypto";import{constants as Vv,promises as ee}from"node:fs";import pe from"node:path";ot();ii();et();Q();var tf=da(Cn(),1);ue();ke();pr();et();Q();yt();import{randomUUID as kF}from"crypto";import{promises as YP}from"fs";import Mv from"path";import{isDeepStrictEqual as Fv}from"util";Ui();Fn();$s();var ia=/^[a-f0-9]{64}$/u,SF=new Set(["schema","id","change","fromSchema","toSchema","sourceHash","targetHash","createdAt","nextState","transition","transitionSupersede","runRetreat"]),EF=new Set(["sourceHash","targetHash","nextJournal"]),PF=new Set(["sourceHash","transitionId","previousRun","nextRun","evidenceHash","eventData"]),JP=new Set(["fromSchema","toSchema","previousPhase","nextPhase","reason","supersededTransitionId"]),RF=new Set(["previousRun","nextRun","evidenceHash","eventData"]);function Zd(e,t,r){let i=Object.keys(e).find(n=>!t.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function GP(e){return JSON.stringify(e,null,2)+`
|
|
265
|
+
`}function Bv(e){return e.schema===Re?Ku(e):qn(e)}function Lv(e,t){return{...e,schema:Re,minimum_runtime_version:2,revision:t}}function CF(e){return{...e,schema:Ur,minimum_runtime_version:2,revision:1,previousState:Lv(e.previousState,1),nextState:Lv(e.nextState,2)}}function ef(e,t){let r=t?.retreatEvidencePhase===!0&&(e.phase==="verify"||e.phase==="archive");return{...e,schema:Pe,minimum_runtime_version:3,verification_protocol:"legacy-v1",revision:e.revision+(r&&t?.incrementRetreatRevision?1:0),phase:r?"build":e.phase,verification_result:r?"pending":e.verification_result,verification_report:r?null:e.verification_report,approved_contract_hash:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:r?!1:e.archived}}function xF(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,r=t?F(JSON.stringify({operation:"spec-rebase",change:e.change,summary:e.eventData.summary,specChanges:e.nextState.spec_changes})):e.evidenceHash;return{...e,schema:Di,minimum_runtime_version:3,revision:1,operation:t?"spec-rebase":"advance",evidenceHash:r,previousState:ef(e.previousState),nextState:{...ef(e.nextState),...t?{implementation_scope:null,verification_evidence:null,partial_allowance:null}:{}},eventData:{...e.eventData,evidenceHash:r},nextRun:e.previousRun===null?{...e.nextRun,skillVersion:Hr.definition.metadata.version,skillHash:mc}:e.nextRun}}function UP(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Co(e,t){return JSON.stringify(Ku(e))===JSON.stringify(Ku(t))}function KP(e,t){return JSON.stringify(qn(e))===JSON.stringify(qn(t))}function li(e,t){return Fv(e,t)}function AF(e,t,r,i){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Schema migration transition supersede plan is invalid");let n=e;if(Zd(n,PF,"Schema migration transition supersede plan"),typeof n.sourceHash!="string"||!ia.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"||!ia.test(n.evidenceHash))throw new Error("Schema migration transition supersede evidence hash is invalid");let a=Gi(n.previousRun),o=Gi(n.nextRun);if(a.runId!==o.runId||r.run_id!==o.runId||r.phase!=="build"&&r.phase!=="verify"||o.currentStep!==r.phase||o.pending!==null||o.status!=="running"||r.verification_result!=="pending"||r.verification_report!==null||r.implementation_scope!==null||r.verification_evidence!==null||r.partial_allowance!==null)throw new Error("Schema migration transition supersede Run does not match target state");let s=a.currentStep==="verify"&&r.phase==="build"||a.currentStep==="archive"&&r.phase==="build",c=a.currentStep===r.phase?a:s?{...a,currentStep:r.phase,iteration:a.iteration+1,pending:null,status:"running"}:null;if(!c||!li(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!==JP.size||u.some(f=>!JP.has(f))||l.fromSchema!==Re||l.toSchema!==Pe||!["build","verify","archive"].includes(l.previousPhase)||l.nextPhase!==r.phase||l.reason!==(r.phase==="build"?"implementation-scope-required":"verification-evidence-required")||l.supersededTransitionId!==n.transitionId)throw new Error("Schema migration transition supersede event semantics are invalid");if(r.name!==t)throw new Error("Schema migration transition supersede change mismatch");let d=F(JSON.stringify({operation:"supersede-v2-evidence-transition",change:t,transitionId:n.transitionId,migrationId:i,previousPhase:l.previousPhase,nextPhase:l.nextPhase,reason:l.reason,previousIteration:a.iteration,nextRevision:r.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 _c(e,t){return Mv.join(M(e,t),"schema-migration.json")}function _F(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native schema migration journal must be an object");Zd(e,SF,"Native schema migration journal");let r=e;if(r.schema!=="comet.native.schema-migration.v1")throw new Error("Unsupported Native schema migration journal");if(r.change!==t)throw new Error("Schema migration change mismatch");let i=r.fromSchema===lt&&r.toSchema===Re,n=r.fromSchema===Re&&r.toSchema===Pe;if(!i&&!n)throw new Error("Schema migration route is unsupported");if(typeof r.id!="string"||r.id.length===0)throw new Error("Schema migration id is invalid");if(typeof r.sourceHash!="string"||!ia.test(r.sourceHash)||typeof r.targetHash!="string"||!ia.test(r.targetHash))throw new Error("Schema migration hash is invalid");if(typeof r.createdAt!="string"||Number.isNaN(Date.parse(r.createdAt)))throw new Error("Schema migration timestamp is invalid");let a=i?Rr(r.nextState):wt(r.nextState);if(a.name!==t)throw new Error("Schema migration target state change mismatch");if(F((0,tf.stringify)(Bv(a)))!==r.targetHash)throw new Error("Schema migration state target hash does not match its document");let o;if(r.transition!==void 0){if(!r.transition||typeof r.transition!="object")throw new Error("Schema migration transition target is invalid");Zd(r.transition,EF,"Schema migration transition target");let l=r.transition;if(typeof l.sourceHash!="string"||!ia.test(l.sourceHash)||typeof l.targetHash!="string"||!ia.test(l.targetHash))throw new Error("Schema migration transition hash is invalid");let u=i?Gm(l.nextJournal,t):Jm(l.nextJournal,t);if(F(JSON.stringify(l.nextJournal,null,2)+`
|
|
266
|
+
`)!==l.targetHash)throw new Error("Schema migration transition target hash does not match its journal");if(!(i&&a.schema===Re?Co(a,u.previousState)||Co(a,u.nextState):a.schema===Pe&&(KP(a,u.previousState)||KP(a,u.nextState))))throw new Error("Schema migration state/transition target mismatch");o={sourceHash:l.sourceHash,targetHash:l.targetHash,nextJournal:l.nextJournal}}if(i&&(!o&&a.revision!==1||o&&a.revision!==1&&a.revision!==2))throw new Error("Schema migration v1 target revision is invalid");let s;if(r.transitionSupersede!==void 0){if(!n||o)throw new Error("Schema migration transition supersede plan is not valid for this route");if(a.schema!==Pe)throw new Error("Schema migration transition supersede target schema is invalid");s=AF(r.transitionSupersede,t,a,r.id)}let c;if(r.runRetreat!==void 0){if(!n||o||s)throw new Error("Schema migration Run retreat is not valid for this route");if(!r.runRetreat||typeof r.runRetreat!="object")throw new Error("Schema migration Run retreat is invalid");Zd(r.runRetreat,RF,"Schema migration Run retreat");let l=r.runRetreat,u,d;try{u=Gi(l.previousRun),d=Gi(l.nextRun)}catch(f){throw new Error("Schema migration Run retreat is invalid",{cause:f})}if(typeof l.evidenceHash!="string"||!ia.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!==Pe||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:r.id,change:t,fromSchema:r.fromSchema,toSchema:r.toSchema,sourceHash:r.sourceHash,targetHash:r.targetHash,createdAt:r.createdAt,nextState:a,...o?{transition:o}:{},...s?{transitionSupersede:s}:{},...c?{runRetreat:c}:{}}}async function Ic(e,t){let r=_c(e,t),i=$(e,r);await T(i,r);try{let n=await ku({root:i,file:r,maxBytes:524288,label:"Native schema migration journal"});return _F(JSON.parse(n.text),t)}catch(n){if(n.code==="ENOENT")return null;throw n}}async function IF(e,t,r){let i=await Ka(e,t),n=i?await Hu(e,i):await Du(e,{now:new Date(r),origin:"legacy-migration"});if(!n.complete){let a=Yp(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 ro(t,n.omittedCount,o,a.samplePaths,a.sampleTruncated)}i===null&&await Zp(e,t,n)}async function XP(e){try{return await hr(e)}catch(t){if(t.code==="ENOENT")return null;throw t}}function TF(e,t){let r=e.transitionSupersede;return{sequence:t,timestamp:e.createdAt,type:"state_migrated",runId:r.nextRun.runId,data:{...r.eventData,migrationId:e.id,evidenceHash:r.evidenceHash}}}async function QP(e,t){let r=t.transitionSupersede,i=M(e,t.change),n=await dt(i,r.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&&!Fv(o.event,TF(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 jF(e,t,r){if(!t.transitionSupersede)return;let i=it(e,t.change),n=await XP(i);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=M(e,t.change),o=await Ve(a),s=await QP(e,t),c=await Xa(a,t.transitionSupersede.nextRun.checkpointRef);if(!r||!o||!li(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!==F(t.transitionSupersede.evidenceHash)||c.createdAt!==t.createdAt)throw new Error(`Native superseded transition disappeared before migration ${t.id} was durable`)}async function $F(e,t,r){let i=t.transitionSupersede;if(!i)return;let n=M(e,t.change),a=await Ve(n);if(!a)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!li(a,i.nextRun)){if(!li(a,i.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Vn(n,i.nextRun),await r?.afterRunStateWritten?.(t)}if(!li(await Ve(n),i.nextRun))throw new Error(`Native schema migration Run write diverged for ${t.change}`);let o=await QP(e,t);if(o.sequence===null){let l=await rn({changeDir:n,run:i.nextRun,type:"state_migrated",data:{...i.eventData,migrationId:t.id,evidenceHash:i.evidenceHash},now:new Date(t.createdAt)});o={trajectoryLength:l.sequence,sequence:l.sequence}}await r?.afterTrajectoryWritten?.(t),await Un({changeDir:n,run:i.nextRun,trajectoryOffset:o.sequence,evidenceHash:i.evidenceHash,now:new Date(t.createdAt)}),await r?.afterCheckpointWritten?.(t);let s=it(e,t.change),c=await XP(s);if(c!==null){if(c!==i.sourceHash)throw new Error(`Native superseded transition changed before removal for ${t.change}`);await YP.rm(s),await r?.afterTransitionSuperseded?.(t)}}async function OF(e,t,r){if(!t.runRetreat)return;let i=M(e,t.change),n=await Ve(i);if(!n)throw new Error(`Native schema migration Run state disappeared for ${t.change}`);if(!li(n,t.runRetreat.nextRun)){if(!li(n,t.runRetreat.previousRun))throw new Error(`Native schema migration Run source changed for ${t.change}`);await Vn(i,t.runRetreat.nextRun),await r?.afterRunStateWritten?.(t)}let a=await dt(i,t.runRetreat.nextRun.trajectoryRef),o=a.find(s=>s.type==="state_migrated"&&s.data.migrationId===t.id);o||(o=await rn({changeDir:i,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 r?.afterTrajectoryWritten?.(t),await Un({changeDir:i,run:t.runRetreat.nextRun,trajectoryOffset:a.length,evidenceHash:t.runRetreat.evidenceHash,now:new Date(t.createdAt)}),await r?.afterCheckpointWritten?.(t)}async function HF(e,t,r){let i=await Ic(e,t);if(!i)return null;if(await no(e,t))throw new Error(`Native change ${t} has a pending progress checkpoint; recover it with its v2 runtime before schema migration`);let n=Mv.join(se(e,t),Le),a=await hr(n);if(await jF(e,i,a===i.targetHash),await IF(e,t,i.createdAt),a!==i.targetHash){if(a!==i.sourceHash)throw new Error(`Native schema migration source changed for ${t}: expected ${i.sourceHash}, actual ${a}`);await ge(n,(0,tf.stringify)(Bv(i.nextState))),await r?.afterStateWritten?.(i)}if(i.transition){let o=it(e,t),s=await hr(o);if(s!==i.transition.targetHash){if(s!==i.transition.sourceHash)throw new Error(`Native transition migration source changed for ${t}: expected ${i.transition.sourceHash}, actual ${s}`);await re(o,i.transition.nextJournal),await r?.afterTransitionWritten?.(i)}}return await $F(e,i,r),await OF(e,i,r),await YP.rm(_c(e,t),{force:!0}),i.nextState}async function DF(e){let t=M(e.paths,e.state.name),r=await Ve(t);if(!r||r.runId!==e.state.run_id||r.currentStep!==e.state.phase||r.currentStep!=="verify"&&r.currentStep!=="archive"||r.pending!==null)throw new Error(`Native v2 ${e.state.phase} change ${e.state.name} has no consistent Run state for safe Build retreat`);let i={...r,currentStep:"build",iteration:r.iteration+1,pending:null,status:"running"},n=F(`schema-v3-evidence-retreat:${e.state.name}:${e.state.revision}:${e.migrationId}`);return{previousRun:r,nextRun:i,evidenceHash:n,eventData:{fromSchema:Re,toSchema:Pe,previousPhase:e.state.phase,nextPhase:"build",reason:"implementation-scope-required"}}}async function LF(e){let{journal:t,state:r}=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=Co(r,t.previousState),a=Co(r,t.nextState);if(!n&&!a)throw new Error(`Native change ${r.name} does not match its v2 evidence transition`);let o=M(e.paths,r.name),s=await Ve(o);if(!s)throw new Error(`Native v2 transition Run is missing for ${r.name}`);let c=t.previousRun!==null&&li(s,t.previousRun),l=li(s,t.nextRun);if(!c&&!l||a&&!l)throw new Error(`Native v2 transition Run does not match its durable state for ${r.name}`);let d=(await dt(o,t.nextRun.trajectoryRef)).map((g,N)=>({event:g,index:N})).filter(({event:g})=>g.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 g={sequence:f.index+1,timestamp:t.createdAt,type:"state_transitioned",runId:t.nextRun.runId,data:{...t.eventData,transitionId:t.id}};if(!Fv(f.event,g)||!a||!l)throw new Error(`Native v2 evidence transition ${t.id} trajectory event does not match its journal`)}let h={...ef(r),revision:r.revision+(r.phase==="build"?0:1),phase:"build",verification_result:"pending",verification_report:null,implementation_scope:null,verification_evidence:null,partial_allowance:null,archived:!1},m=s,p=s.currentStep!=="build"?{...s,currentStep:"build",iteration:s.iteration+1,pending:null,status:"running"}:s,v=F(JSON.stringify({operation:"supersede-v2-evidence-transition",change:r.name,transitionId:t.id,migrationId:e.migrationId,previousPhase:r.phase,nextPhase:"build",reason:"implementation-scope-required",previousIteration:s.iteration,nextRevision:h.revision}));return{nextState:h,plan:{sourceHash:await hr(it(e.paths,r.name)),transitionId:t.id,previousRun:m,nextRun:p,evidenceHash:v,eventData:{fromSchema:Re,toSchema:Pe,previousPhase:r.phase,nextPhase:"build",reason:"implementation-scope-required",supersededTransitionId:t.id}}}}async function MF(e){let t,r,i,n;if(e.state.schema===lt){if(t=Lv(e.state,1),e.pendingTransition){if(e.pendingTransition.journal.schema!==On)throw new Error("Native v1 change has a transition from another schema generation");let s=CF(e.pendingTransition.journal);if(UP(e.state,e.pendingTransition.journal.previousState))t=s.previousState;else if(UP(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=it(e.paths,e.name);r={sourceHash:await hr(c),targetHash:F(GP(s)),nextJournal:s}}}else if(e.pendingTransition){if(e.pendingTransition.journal.schema!==Ur)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 LF({paths:e.paths,state:e.state,journal:s,migrationId:e.id});t=l.nextState,i=l.plan}else{let l=xF(s);if(Co(e.state,e.pendingTransition.journal.previousState))t=l.previousState;else if(Co(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=it(e.paths,e.name);r={sourceHash:await hr(u),targetHash:F(GP(l)),nextJournal:l}}}else t=ef(e.state,{retreatEvidencePhase:!0,incrementRetreatRevision:!0}),(e.state.phase==="verify"||e.state.phase==="archive")&&(n=await DF({paths:e.paths,state:e.state,migrationId:e.id}));let a=Mv.join(se(e.paths,e.name),Le),o=(0,tf.stringify)(Bv(t));return{schema:"comet.native.schema-migration.v1",id:e.id,change:e.name,fromSchema:e.state.schema,toSchema:e.state.schema===lt?Re:Pe,sourceHash:await hr(a),targetHash:F(o),createdAt:e.now.toISOString(),nextState:t,...r?{transition:r}:{},...i?{transitionSupersede:i}:{},...n?{runRetreat:n}:{}}}async function ZP(e){return de(e.paths,`migrate schema for ${e.name}`,()=>Kn(e.paths,e.name,`migrate schema for ${e.name}`,async()=>{for(let t=0;t<3;t+=1){let r=await HF(e.paths,e.name,e.hooks);if(r?.schema===Pe)return r;let i=await Tr(e.paths,e.name);if(i.status==="current"&&i.state)return i.state;if(i.status!=="migration-required"||!i.state)throw new Error(i.message??`Native change ${e.name} cannot be migrated`);if(await no(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=i.state;if(n.schema!==lt&&n.schema!==Re)throw new Error(`Native change ${e.name} has no supported migration route`);let a=await Um(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 MF({paths:e.paths,name:e.name,state:n,pendingTransition:a,now:e.now??new Date,id:e.id?.()??kF()}),s=_c(e.paths,e.name),c=$(e.paths,s);await T(c,s),await re(s,o,{containedRoot:c}),await e.hooks?.afterPrepared?.(o)}throw new Error(`Native change ${e.name} exceeded the supported schema migration path`)}))}Mn();ar();Xi();uc();ho();var ui=Object.freeze({minimumAgeMs:720*60*60*1e3,keepLatestUnreferencedPerKind:32,maxDocuments:4096,maxScannedBytes:256*1024*1024,maxReportedRefs:8,maxReportMessageBytes:4096}),VF=512*1024,na=/^([a-f0-9]{64})\.json$/u,qF=/^\.([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,WF=/^runtime\/evidence\/(snapshots|scopes|allowances|verifications|reports|receipts|check-receipts)\/[a-f0-9]{64}\.json$/u,rf=["snapshots","scopes","allowances","verifications","reports","receipts","check-receipts"];function Wv(e,t){return J({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Br(e,t){return Wv(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function nR(e,t){return Wv(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}function xo(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ht(e,t){return e<t?-1:e>t?1:0}function zF(e,t){let r=pe.relative(e.projectRoot,t);if(r.length===0||pe.isAbsolute(r)||r===".."||r.startsWith(`..${pe.sep}`))throw new Error("Native evidence retention finding path is outside the project");return r.split(pe.sep).join("/")}function aR(e,t){return pe.join(M(e,t),"evidence")}function nf(e,t){return zF(e,aR(e,t))}async function af(e,t){let r=pe.resolve(e),i=pe.resolve(t);if(!D(r,i))throw new Error("Native evidence retention path escapes its managed change");let n=pe.relative(r,i).split(pe.sep).filter(Boolean),a=[],o=r;for(let s of["",...n]){s&&(o=pe.join(o,s));let c=await ee.lstat(o);if(!c.isDirectory()||c.isSymbolicLink())throw new Error(`Native evidence retention parent must be a real directory: ${o}`);let l=await ee.realpath(o);if(a.length>0&&!D(a[0].realPath,l))throw new Error(`Native evidence retention parent resolves outside its change: ${o}`);a.push({path:o,realPath:l,...xo(c)})}return a}async function Qt(e){for(let t of e){let r=await ee.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Wv(t,r)||await ee.realpath(t.path)!==t.realPath)throw new Error(`Native evidence retention parent changed: ${t.path}`)}}function oR(e,t){return e==="check-receipts"?`runtime/evidence/check-receipts/${t}.json`:mo(e,t)}function eR(e){return e!==null&&WF.test(e)?[e]:[]}function JF(e,t,r,i){if(e==="snapshots")return{canonical:so(r,t),dependencies:[]};if(e==="scopes"){let a=co(r);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=id(r);if(a.change!==i||a.allowanceHash!==t)throw new Error("Native allowance filename/change does not match its content");return{canonical:a,dependencies:[mo("scopes",a.scopeHash)]}}if(e==="verifications"){let a=lc(r);if(a.change!==i||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(eR));return{canonical:a,dependencies:[a.implementationScopeRef,MS(a.reportHash),...eR(a.partialAllowanceRef),...a.requiredReceiptRefs,...a.receiptRefs,...o]}}if(e==="reports"){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Native report evidence must be an object");let a=r;if(Object.keys(a).sort().join(",")!=="content,reportHash,schema"||a.schema!=="comet.native.verification-report.v1"||a.reportHash!==t||typeof a.content!="string"||FF("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=od(r);if(a.bindings.change!==i||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=nd(r);if(n.change!==i||n.receiptHash!==t)throw new Error("Native check receipt filename/change does not match its content");return{canonical:n,dependencies:[]}}async function gn(e){let t=await ee.lstat(e.file);if(!t.isFile()||t.isSymbolicLink())throw new Error(`Native evidence entry is not a regular file: ${e.ref}`);let r=e.kind==="check-receipts"?VF:tn;if(t.size>r)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);let i=await ee.realpath(e.file);if(!D(e.directoryChain[0].realPath,i))throw new Error(`Native evidence entry resolves outside its change: ${e.ref}`);let n=process.platform==="win32"?"r":Vv.O_RDONLY|Vv.O_NOFOLLOW|Vv.O_NONBLOCK,a=await ee.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(),ee.lstat(e.file),ee.realpath(e.file)]);if(await Qt(e.directoryChain),!o.isFile()||!s.isFile()||s.isSymbolicLink()||c!==i||!Br(xo(t),o)||!Br(xo(o),s))throw new Error(`Native evidence entry changed while opening: ${e.ref}`);let l=[],u=Buffer.allocUnsafe(64*1024),d=0;for(;;){let N=r+1-d,E=await a.read(u,0,Math.min(u.length,N),null);if(E.bytesRead===0)break;if(d+=E.bytesRead,d>r)throw new Error(`Native evidence entry exceeds its byte budget: ${e.ref}`);l.push(Buffer.from(u.subarray(0,E.bytesRead)))}let[f,h,m]=await Promise.all([a.stat(),ee.lstat(e.file),ee.realpath(e.file)]);if(await Qt(e.directoryChain),!h.isFile()||h.isSymbolicLink()||m!==i||!Br(xo(o),f)||!Br(xo(o),h))throw new Error(`Native evidence entry changed while reading: ${e.ref}`);let p=Buffer.concat(l,d).toString("utf8"),v;try{v=JSON.parse(p)}catch(N){throw new Error(`Native evidence entry is not valid JSON: ${e.ref}`,{cause:N})}let g=JF(e.kind,e.hash,v,e.name);if(p!==JSON.stringify(g.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:xo(f),directoryChain:e.directoryChain,dependencies:[...new Set(g.dependencies)].sort(ht)}}finally{await a.close()}}async function tR(e){try{return await ee.lstat(e),!1}catch(t){if(t.code==="ENOENT")return!0;throw t}}async function GF(e){let t=M(e.paths,e.name),r=t,i=aR(e.paths,e.name);await T($(e.paths,i),i);let n;try{let s=await af(t,i);n=await ee.readdir(i,{withFileTypes:!0}),await Qt(s)}catch(s){if(s.code==="ENOENT")return{findings:[],pending:!1};throw s}let a=[];for(let s of rf){if(!n.some(f=>f.name===s))continue;let c=pe.join(i,s),l=await af(t,c),u=(await ee.readdir(c,{withFileTypes:!0})).sort((f,h)=>ht(f.name,h.name)),d=new Map;for(let f of u){let h=qF.exec(f.name);if(!h)continue;let m=d.get(h[1])??[];m.push(f),d.set(h[1],m)}for(let[f,h]of[...d.entries()].sort(([m],[p])=>ht(m,p))){if(h.length!==1)throw new Error(`Native evidence cleanup has multiple quarantines for ${s}/${f}`);let m=h[0];if(!m.isFile()||m.isSymbolicLink())throw new Error(`Native evidence cleanup quarantine is not a regular file: ${s}/${m.name}`);let p=pe.join(c,f),v=na.exec(f)?.[1];if(!v)throw new Error(`Native evidence cleanup quarantine name is invalid: ${m.name}`);let g=oR(s,v),N=pe.join(c,m.name),E=await gn({changeRoot:r,file:N,ref:g,kind:s,hash:v,name:e.name,directoryChain:l}),w=await tR(p),S=w?null:await gn({changeRoot:r,file:p,ref:g,kind:s,hash:v,name:e.name,directoryChain:l});a.push({ref:g,original:p,quarantine:N,document:E,action:w?"restore-original":"finish-linked-recovery",originalDocument:S})}}if(a.length===0)return{findings:[],pending:!1};let o=a.map(s=>s.ref).sort(ht);if(!e.repair)return{pending:!0,findings:[{severity:"warning",code:"evidence-retention-recovery-required",message:Ao(`Native evidence cleanup has ${o.length} safely recoverable quarantined document(s) for ${e.name}: ${of(o)}`),path:nf(e.paths,e.name)}]};for(let s of a.sort((c,l)=>ht(c.ref,l.ref))){if(await Qt(s.document.directoryChain),s.action==="finish-linked-recovery"){let d=await gn({changeRoot:r,file:s.original,ref:s.ref,kind:s.document.kind,hash:na.exec(pe.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),f=await gn({changeRoot:r,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:na.exec(pe.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!s.originalDocument||!Br(s.originalDocument.identity,d.identity)||!Br(s.document.identity,f.identity))throw new Error(`Native evidence cleanup original or quarantine changed during recovery: ${s.ref}`);await ee.rm(s.quarantine),await Qt(s.document.directoryChain);continue}if(!await tR(s.original))throw new Error(`Native evidence cleanup original appeared during recovery: ${s.ref}`);let c=await ee.lstat(s.quarantine);if(!c.isFile()||c.isSymbolicLink()||!Br(s.document.identity,c))throw new Error(`Native evidence cleanup quarantine changed during recovery: ${s.ref}`);await ee.link(s.quarantine,s.original),await e.hooks.afterRecoveryLink?.({ref:s.ref,original:s.original,quarantine:s.quarantine});let l=await gn({changeRoot:r,file:s.original,ref:s.ref,kind:s.document.kind,hash:na.exec(pe.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain}),u=await gn({changeRoot:r,file:s.quarantine,ref:s.ref,kind:s.document.kind,hash:na.exec(pe.basename(s.original))[1],name:e.name,directoryChain:s.document.directoryChain});if(!nR(s.document.identity,l.identity)||!Br(l.identity,u.identity))throw new Error(`Native evidence cleanup recovery identity changed: ${s.ref}`);await ee.rm(s.quarantine),await Qt(s.document.directoryChain)}return{pending:!1,findings:[{severity:"info",code:"evidence-retention-cleanup-recovered",message:Ao(`Recovered ${o.length} interrupted Native evidence cleanup document(s) for ${e.name}: ${of(o)}`),path:nf(e.paths,e.name)}]}}async function UF(e,t){let r=M(e,t),i=r,n=pe.join(r,"evidence");await T($(e,n),n);let a;try{let l=await af(r,n);a=await ee.readdir(n,{withFileTypes:!0}),await Qt(l)}catch(l){if(l.code==="ENOENT")return[];throw l}let o=a.filter(l=>!rf.includes(l.name)||!l.isDirectory()||l.isSymbolicLink()).map(l=>l.name).sort(ht);if(o.length>0)throw new Error(`Native evidence root has unknown or special entries: ${of(o)}`);let s=[],c=0;for(let l of rf){if(!a.some(h=>h.name===l))continue;let u=pe.join(n,l),d=await af(i,u),f=(await ee.readdir(u,{withFileTypes:!0})).sort((h,m)=>ht(h.name,m.name));await Qt(d);for(let h of f){if(s.length>=ui.maxDocuments)throw new Error(`Native evidence store exceeds ${ui.maxDocuments} documents`);let m=na.exec(h.name);if(!m||!h.isFile()||h.isSymbolicLink())throw new Error(`Native evidence kind ${l} has an unknown or special entry: ${h.name}`);let p=oR(l,m[1]),v=pe.join(u,h.name);await T($(e,v),v);let g=await gn({changeRoot:i,file:v,ref:p,kind:l,hash:m[1],name:t,directoryChain:d});if(c+=g.size,c>ui.maxScannedBytes)throw new Error(`Native evidence store exceeds ${ui.maxScannedBytes} scanned bytes`);s.push(g)}await Qt(d)}return s}function rR(e,t){let r=new Set,i=[...e].sort(ht).reverse();for(;i.length>0;){let n=i.pop();if(r.has(n))continue;let a=t.get(n);if(!a)throw new Error(`Native evidence dependency is missing: ${n}`);r.add(n);for(let o of[...a.dependencies].sort(ht).reverse())r.has(o)||i.push(o)}return r}function KF(e){let t=new Map(e.map(a=>[a.ref,a])),r=new Map(e.map(a=>[a.ref,0]));for(let a of e)for(let o of a.dependencies)t.has(o)&&r.set(o,(r.get(o)??0)+1);let i=[...r].filter(([,a])=>a===0).map(([a])=>a).sort(ht),n=[];for(;i.length>0;){let a=i.shift(),o=t.get(a);n.push(o);for(let s of o.dependencies){let c=r.get(s);if(c===void 0)continue;let l=c-1;r.set(s,l),l===0&&(i.push(s),i.sort(ht))}}if(n.length!==e.length)throw new Error("Native evidence candidate dependency graph contains a cycle");return n}function YF(e,t,r){let i=new Map(e.map(c=>[c.ref,c]));if(i.size!==e.length)throw new Error("Native evidence store has duplicate refs");for(let c of e)for(let l of c.dependencies)if(!i.has(l))throw new Error(`Native evidence dependency is missing: ${l}`);let n=rR(t,i),a=new Set(n);for(let c of e)r-c.mtimeMs<ui.minimumAgeMs&&a.add(c.ref);for(let c of rf){let l=e.filter(u=>u.kind===c&&!n.has(u.ref)).sort((u,d)=>d.mtimeMs-u.mtimeMs||ht(u.ref,d.ref)).slice(0,ui.keepLatestUnreferencedPerKind);for(let u of l)a.add(u.ref)}let o=rR(a,i),s=e.filter(c=>!o.has(c.ref)&&r-c.mtimeMs>=ui.minimumAgeMs).sort((c,l)=>ht(c.ref,l.ref));return{candidates:KF(s),candidateBytes:s.reduce((c,l)=>c+l.size,0)}}function of(e){let t=e.slice(0,ui.maxReportedRefs),r=e.length-t.length;return`${t.join(", ")}${r>0?`, ... (${r} more)`:""}`}function Ao(e){let t=ui.maxReportMessageBytes;if(Buffer.byteLength(e,"utf8")<=t)return e;let r=e;for(;r.length>0&&Buffer.byteLength(`${r}...`,"utf8")>t;)r=r.slice(0,-1);return`${r}...`}function qv(e,t,r,i){let n=t.candidates.map(a=>a.ref).sort(ht);return{severity:"info",code:r?"evidence-retention-cleaned":"evidence-retention-candidates",message:Ao(`${r?"Removed":"Found"} ${t.candidates.length} old unreferenced Native evidence document(s) (${t.candidateBytes} bytes) for ${e}: ${of(n)}`),path:i}}async function iR(e,t){try{await ee.lstat(t);return}catch(r){if(r.code!=="ENOENT")return}try{await ee.rename(e,t)}catch{}}async function XF(e,t){await t.beforeDelete?.({ref:e.ref,file:e.file}),await Qt(e.directoryChain);let r=await gn({changeRoot:e.changeRoot,file:e.file,ref:e.ref,kind:e.kind,hash:na.exec(pe.basename(e.file))[1],name:e.change,directoryChain:e.directoryChain}),i=await ee.lstat(e.file),n=await ee.realpath(e.file);if(!i.isFile()||i.isSymbolicLink()||!Br(e.identity,i)||!Br(e.identity,r.identity)||!D(e.directoryChain[0].realPath,n))throw new Error(`Native evidence candidate changed before cleanup: ${e.ref}`);let a=pe.join(pe.dirname(e.file),`.${pe.basename(e.file)}.${BF()}.gc`);await ee.rename(e.file,a);try{let[o,s]=await Promise.all([ee.lstat(a),ee.realpath(a)]);if(await Qt(e.directoryChain),!o.isFile()||o.isSymbolicLink()||!nR(e.identity,o)||!D(e.directoryChain[0].realPath,s))throw await iR(a,e.file),new Error(`Native evidence candidate changed during cleanup: ${e.ref}`);await ee.rm(a),await Qt(e.directoryChain)}catch(o){throw await iR(a,e.file),o}}async function QF(e){if((await Ee(e.projectRoot))?.native.pending_root_move)return!0;let r;try{r=await ee.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return!1;throw i}for(let i of r){if(!i.isDirectory()||i.isSymbolicLink())return!0;try{let n=await At(e,i.name);if(n.status!=="committed"&&n.status!=="rolled-back")return!0}catch{return!0}}return!1}async function ZF(e,t){if(t)return[t];let r;try{r=await ee.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}return r.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort(ht)}async function eB(e,t){let r=await Tr(e,t);if(r.status!=="current"||!r.state||r.state.archived)return!0;let[i,n,a]=await Promise.all([ni(e,t),Ic(e,t),sn(e,t)]);return i!==null||n!==null||a!==null}async function tB(e){if(await eB(e.paths,e.name))return[];let t=await Tr(e.paths,e.name);if(t.status!=="current"||!t.state)return[];if(!("implementation_scope"in t.state))return[];let r=await GF({paths:e.paths,name:e.name,repair:e.repair,hooks:e.hooks});if(r.pending)return r.findings;let i=[];for(let c of[t.state.implementation_scope,t.state.partial_allowance,t.state.verification_evidence])c!==null&&i.push(c);let n=await UF(e.paths,e.name),a=YF(n,i,e.nowMs);if(a.candidates.length===0)return r.findings;let o=nf(e.paths,e.name);if(!e.repair)return[...r.findings,qv(e.name,a,!1,o)];let s=[];for(let c of a.candidates)try{await XF(c,e.hooks),s.push(c)}catch(l){let u=s.reduce((d,f)=>d+f.size,0);return[...r.findings,...s.length>0?[qv(e.name,{candidates:s,candidateBytes:u},!0,o)]:[],{severity:"error",code:"evidence-retention-cleanup-failed",message:Ao(`Native evidence cleanup stopped safely for ${e.name}: ${l.message}`),path:o}]}return[...r.findings,qv(e.name,a,!0,o)]}async function sR(e){if(e.deferAll||await QF(e.paths))return[];let t=e.now??new Date;if(Number.isNaN(t.getTime()))throw new Error("Native evidence retention time is invalid");let r=async n=>{let a=[];for(let o of await ZF(e.paths,e.name))try{a.push(...await tB({paths:e.paths,name:o,repair:n,nowMs:t.getTime(),hooks:e.hooks??{}}))}catch(s){a.push({severity:"error",code:"evidence-retention-unsafe",message:Ao(`Native evidence retention refused to clean ${o}: ${s.message}`),path:nf(e.paths,o)})}return a};if(!(e.repair??!1))return r(!1);let i=await r(!1);if(i.some(n=>n.severity==="error")||!i.some(n=>n.code==="evidence-retention-candidates"||n.code==="evidence-retention-recovery-required"))return i;try{return await de(e.paths,"prune Native evidence",()=>r(!0))}catch(n){return[{severity:"info",code:"evidence-retention-cleanup-deferred",message:Ao(`Native evidence cleanup was deferred until the project mutation lock is available: ${n.message}`)}]}}Tn();Q();yt();ue();ot();Tn();Q();yt();Mn();_r();import{createHash as rB,randomUUID as N5}from"crypto";import{promises as $c}from"fs";import ce from"path";var Jv=64*1024*1024,iB=256*1024,dR=16*1024*1024;async function pt(e){try{return await $c.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function nB(e){let t;try{t=await $c.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return;throw r}for(let r of t.sort((i,n)=>i.name.localeCompare(n.name))){if(!r.isDirectory()||r.isSymbolicLink())continue;let i=await Tt(e,r.name);if(i){await Ju({paths:e,name:r.name,revision:i.capturedRevision,...i.schema==="comet.native.workspace.v3"?{binding:{isolation:i.isolation,changeBranch:i.changeBranch,targetBranch:i.targetBranch},...i.finish?{finish:i.finish}:{}}:{}});continue}}}async function jc(e,t){let r=[];async function i(n){let a=await xt({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=ce.join(n,s.name);if(t.excludedFiles?.has(ce.resolve(c))){await a.verify();continue}let l=await $c.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())r.push({ref:ce.relative(e,c).split(ce.sep).join("/"),type:"directory"}),await i(c);else if(s.isFile()&&l.isFile()){let u=await oe({root:e,file:c,maxBytes:Jv,label:`Native root file ${ce.relative(e,c)}`});r.push({ref:ce.relative(e,c).split(ce.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 i(e),r.sort((n,a)=>n.ref.localeCompare(a.ref))}async function aB(e,t,r,i){await Cr({root:i,directory:t,label:"Native root move staging directory"});async function n(a,o){let s=await xt({root:e,directory:a,label:"Native root move source directory"}),c=s.entries;for(let l of c){await s.verify();let u=ce.join(a,l.name);if(ce.resolve(u)===ce.resolve(r)){await s.verify();continue}let d=await $c.lstat(u);if(l.isSymbolicLink()||d.isSymbolicLink())throw new Error(`Native root contains a symlink: ${u}`);let f=ce.join(o,l.name);if(l.isDirectory()&&d.isDirectory())await Cr({root:i,directory:f,label:"Native root move staging directory"}),await n(u,f);else if(l.isFile()&&d.isFile())await Bi({sourceRoot:e,source:u,targetRoot:i,target:f,maxBytes:Jv,label:`Native root move file ${ce.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 _o(e,t,r,i){let n=await jc(e,{rejectSymlinks:!0,excludedFiles:r?new Set([ce.resolve(r)]):void 0}),a=await jc(t,{rejectSymlinks:!0,excludedFiles:i?new Set([ce.resolve(i)]):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 oB(e,t){return ce.join(e.artifactRoot,`.comet-native-move-${t}`)}function sB(e,t){return ce.join(e.artifactRoot,`.comet-native-source-${t}.removing`)}function cB(e){return`${e}.removing`}function cR(e,t){return ce.join(ce.dirname(e),`.${ce.basename(e)}.${t}.rollback-removing`)}function fR(e,t,r){return ce.join(xu(e,t).directory,`root-move-cleanup-${r}.json`)}function lB(e){return JSON.stringify(e,null,2)+`
|
|
268
|
+
`}function uB(e){return rB("sha256").update(e).digest("hex")}function dB(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 r=e,i=Object.keys(r).sort(),n=r.type==="file"?["hash","ref","size","type"]:["ref","type"];if(JSON.stringify(i)!==JSON.stringify(n))throw new Error(`Native root-move cleanup manifest entry ${t} has invalid fields`);if(typeof r.ref!="string"||r.ref.length===0||r.ref.includes("\\")||ce.posix.normalize(r.ref)!==r.ref||r.ref.startsWith("/")||r.ref.split("/").includes("..")||Buffer.byteLength(r.ref,"utf8")>4096)throw new Error(`Native root-move cleanup manifest entry ${t} has an invalid ref`);if(r.type==="directory")return{ref:r.ref,type:"directory"};if(r.type!=="file"||typeof r.size!="number"||!Number.isSafeInteger(r.size)||r.size<0||typeof r.hash!="string"||!/^[a-f0-9]{64}$/u.test(r.hash))throw new Error(`Native root-move cleanup manifest entry ${t} is invalid`);return{ref:r.ref,type:"file",size:r.size,hash:r.hash}}function fB(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native root-move cleanup manifest must be an object");let i=e;if(JSON.stringify(Object.keys(i).sort())!==JSON.stringify(["entries","kind","schema","transactionId"])||i.schema!=="comet.native.root-move-cleanup.v1"||i.transactionId!==t||i.kind!==r||!Array.isArray(i.entries))throw new Error("Native root-move cleanup manifest binding is invalid");let n=i.entries.map(dB);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=ce.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:r,entries:n}}async function hB(e){let t={schema:"comet.native.root-move-cleanup.v1",transactionId:e.id,kind:e.kind,entries:e.entries},r=lB(t);if(Buffer.byteLength(r,"utf8")>dR)throw new Error("Native root-move cleanup manifest exceeds its byte budget");return await ge(fR(e.paths,e.id,e.kind),r,{containedRoot:e.paths.runtimeDir}),uB(r)}async function pB(e){let t=await oe({root:e.paths.runtimeDir,file:fR(e.paths,e.id,e.cleanup.kind),maxBytes:dR,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 fB(JSON.parse(t.bytes.toString("utf8")),e.id,e.cleanup.kind)}async function zv(e){let t=await jc(e.quarantine,{rejectSymlinks:!0}),r=new Map(e.manifest.entries.map(i=>[i.ref,i]));for(let i of t){let n=r.get(i.ref);if(!n||JSON.stringify(n)!==JSON.stringify(i))throw new Error(`Native root-move cleanup quarantine differs from its bound manifest: ${i.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 lR(e){return e.ref.split("/").length}async function mB(e){let r=[...await zv({quarantine:e.quarantine,manifest:e.manifest,exact:!1})].sort((n,a)=>lR(a)-lR(n)||(n.type===a.type?a.ref.localeCompare(n.ref):n.type==="file"?-1:1)),i=0;for(let n of r){let a=ce.join(e.quarantine,...n.ref.split("/"));n.type==="file"?await Su({root:e.projectRoot,file:a,maxBytes:Jv,expectedHash:n.hash,expectedSize:n.size,label:`Native root-move cleanup file ${n.ref}`}):await $p({root:e.projectRoot,directory:a,label:`Native root-move cleanup directory ${n.ref}`}),i+=1,await e.hooks?.afterRootMoveCleanupEntryRemoved?.(e.manifest.kind,n.ref,i)}await zv({quarantine:e.quarantine,manifest:e.manifest,exact:!1}),await $p({root:e.projectRoot,directory:e.quarantine,label:`Native root-move cleanup quarantine ${e.manifest.kind}`})}function hR(e,t,r=e.native.artifact_root){return{...e,native:{...e.native,artifact_root:r,pending_root_move:t}}}function vB(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 gB(e,t,r,i){for(let a of[e,t])try{let o=await At(a,i);if(o.kind!=="root-move")throw new Error(`Transaction ${i} is not a root move`);return{journal:o,paths:a}}catch(o){if(o.code!=="ENOENT")throw o}let n=ce.join(r,"runtime","transactions",i,"transaction.json");try{let a=await oe({root:r,file:n,maxBytes:iB,label:`Staged Native root-move journal ${i}`}),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: ${i}`);return{journal:o,paths:t}}catch(a){throw a.code!=="ENOENT"?a:new Error(`Native root-move journal is missing: ${i}`,{cause:a})}}async function uR(e){let t=hR(e.config,{...e.pending,stage:e.stage},e.activeArtifactRoot);return await Ti(e.projectRoot,t),t}async function Tc(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 r=hR(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 Ti(e.projectRoot,r),r}async function sf(e){let t=e.config,r=t.native.pending_root_move;if(!r||r.id!==e.id)throw new Error(`Native root-move cleanup ${e.id} lost its pending configuration`);let i=r.cleanup;if(i&&i.kind!==e.kind)throw new Error(`Native root move has unfinished ${i.kind} cleanup; cannot start ${e.kind}`);let n=await pt(e.target),a=await pt(e.quarantine);if(n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(!i){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 hB({paths:e.stablePaths,id:e.id,kind:e.kind,entries:await jc(e.target,{rejectSymlinks:!0})});i={kind:e.kind,state:"prepared",manifestHash:s},t=await Tc({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})}let o=await pB({paths:e.stablePaths,id:e.id,cleanup:i});if(n=await pt(e.target),a=await pt(e.quarantine),n&&a)throw new Error(`Native root-move cleanup target and quarantine both exist: ${e.kind}`);if(n){if(i.state!=="prepared")throw new Error(`Native root-move cleanup target reappeared after quarantine: ${e.kind}`);await pb({root:e.projectRoot,directory:e.target,quarantine:e.quarantine,label:e.label,beforeQuarantine:e.beforeQuarantine,afterQuarantine:e.afterQuarantine}),a=!0}if(!a){if(i.state!=="deleting")throw new Error(`Native root-move cleanup quarantine disappeared: ${e.kind}`);return Tc({projectRoot:e.projectRoot,config:t,id:e.id})}return await zv({quarantine:e.quarantine,manifest:o,exact:i.state!=="deleting"}),i.state==="prepared"&&(i={...i,state:"quarantined"},t=await Tc({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})),i.state==="quarantined"&&(i={...i,state:"deleting"},t=await Tc({projectRoot:e.projectRoot,config:t,id:e.id,cleanup:i})),await mB({projectRoot:e.projectRoot,quarantine:e.quarantine,manifest:o,hooks:e.hooks}),Tc({projectRoot:e.projectRoot,config:t,id:e.id})}async function wB(e){let t=e.config,r=t.native.pending_root_move.stage;if(r==="copying"){if(!await pt(e.sourcePaths.nativeRoot))throw new Error(`Native source root is missing: ${e.sourcePaths.nativeRoot}`);let s=cB(e.staging);t=await sf({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 jc(e.sourcePaths.nativeRoot,{rejectSymlinks:!0,excludedFiles:new Set([ce.resolve(e.lockFile)])}),await aB(e.sourcePaths.nativeRoot,e.staging,e.lockFile,e.destinationPaths.projectRoot),await _o(e.sourcePaths.nativeRoot,e.staging,e.lockFile),t=await uR({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"ready"}),r="ready",await e.hooks?.afterRootMoveStage?.("ready",e.journal)}if(r==="ready"){if(await pt(e.destinationPaths.nativeRoot)){if(await pt(e.staging))throw new Error(`Native destination is occupied: ${e.destinationPaths.nativeRoot}`);await _o(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile)}else{if(!await pt(e.staging))throw new Error("Native move staging tree is missing");await _o(e.sourcePaths.nativeRoot,e.staging,e.lockFile),await $c.rename(e.staging,e.destinationPaths.nativeRoot)}t=await uR({projectRoot:e.projectRoot,config:t,pending:e.pending,stage:"switched",activeArtifactRoot:e.pending.toArtifactRoot}),r="switched",await e.hooks?.afterRootMoveStage?.("switched",e.journal)}if(r!=="switched")throw new Error(`Unsupported Native root-move stage: ${r}`);if(!await pt(e.destinationPaths.nativeRoot))throw new Error(`Native destination root is missing: ${e.destinationPaths.nativeRoot}`);let i=sB(e.sourcePaths,e.pending.id);!t.native.pending_root_move?.cleanup&&await pt(e.sourcePaths.nativeRoot)&&await _o(e.sourcePaths.nativeRoot,e.destinationPaths.nativeRoot,e.lockFile),t=await sf({projectRoot:e.projectRoot,config:t,id:e.pending.id,kind:"forward-source",stablePaths:e.destinationPaths,target:e.sourcePaths.nativeRoot,quarantine:i,label:"Native root move source removal",beforeQuarantine:()=>e.hooks?.beforeRootMoveSourceRemove?.(e.sourcePaths.nativeRoot),afterQuarantine:s=>e.hooks?.afterRootMoveSourceQuarantined?.(s),hooks:e.hooks}),await nB(e.destinationPaths);let n=await At(e.destinationPaths,e.pending.id);await qa(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 Ti(e.projectRoot,o),o}async function pR(e){let t=await Ee(e.projectRoot),r=t?.native.pending_root_move;if(!t||!r)throw new Error("No pending Native root move was found");let i=await Ke(e.projectRoot,r.fromArtifactRoot),n=await Ke(e.projectRoot,r.toArtifactRoot),a=oB(n,r.id),o=await pt(i.nativeRoot)?i:n,s=await ji(o,"root-move",`recover root ${r.id}`);try{let c;try{c=await gB(i,n,a,r.id)}catch(m){if(r.stage!=="copying"||!await pt(i.nativeRoot))throw m;let p=vB({id:r.id,paths:i,now:new Date});await Eb(i,p),c={journal:p,paths:i}}if(e.strategy==="continue"){let m=await wB({projectRoot:e.projectRoot,config:t,pending:r,sourcePaths:i,destinationPaths:n,staging:a,journal:c.journal,lockFile:s.file,hooks:e.hooks});return{activeNativeRoot:n.nativeRoot,config:m}}if(!await pt(i.nativeRoot))throw new Error("Cannot roll back after the old Native root was removed; continue recovery");let l=cR(n.nativeRoot,r.id);!t.native.pending_root_move?.cleanup&&await pt(n.nativeRoot)&&await _o(i.nativeRoot,n.nativeRoot,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-destination")&&(t=await sf({projectRoot:e.projectRoot,config:t,id:r.id,kind:"rollback-destination",stablePaths:i,target:n.nativeRoot,quarantine:l,label:"Native root move rollback destination removal",hooks:e.hooks}));let u=cR(a,r.id);!t.native.pending_root_move?.cleanup&&await pt(a)&&await _o(i.nativeRoot,a,s.file),(!t.native.pending_root_move?.cleanup||t.native.pending_root_move.cleanup.kind==="rollback-staging")&&(t=await sf({projectRoot:e.projectRoot,config:t,id:r.id,kind:"rollback-staging",stablePaths:i,target:a,quarantine:u,label:"Native root move rollback staging removal",hooks:e.hooks}));let d=await At(i,r.id);await Au(i,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:r.fromArtifactRoot}};return await Ti(e.projectRoot,h),{activeNativeRoot:i.nativeRoot,config:h}}finally{await $i(s)}}Mn();Js();_r();var Io=4096,yB=4096,NB=1024;async function wn(e,t,r){try{let i=await xt({root:$(e,t),directory:t,label:"Native doctor directory",maxEntries:r});return await i.verify(),i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}}async function lf(e,t){let r=new Map(e.map(i=>[Me.resolve(i.file),{...i,file:Me.resolve(i.file)}]));for(let{paths:i,file:n}of r.values()){let a;try{a=await Es(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 bp(i,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 bB(e,t){let r=$P(e),i;try{await T(e.projectRoot,r);let n=await Ud(e);if(!n)return[];i=n}catch(n){return n.code==="ENOENT"?[]:[{severity:"error",code:"selection-invalid",message:`Native selection is invalid: ${n.message}`,path:r}]}if(i.schema!=="comet.selection.v2"||i.workflow!=="native"||typeof i.change!="string")return[{severity:"error",code:"selection-invalid",message:"Native selection has an invalid schema or change name",path:r}];try{return await vn(e,i.change)?[]:(await We(e,i.change),[])}catch(n){if(n.code!=="ENOENT")return[{severity:"error",code:"selection-target-invalid",message:`Selected Native change is invalid: ${n.message}`,path:r}]}return t?(await cf.rm(r,{force:!0}),[{severity:"info",code:"selection-cleared",message:`Cleared stale Native selection ${i.change}`,path:r}]):[{severity:"warning",code:"selection-stale",message:`Selected Native change does not exist: ${i.change}`,path:r}]}async function kB(e){let t=[];for(let r of[e.specsDir,e.changesDir,e.archiveDir,e.runtimeDir,e.locksDir,e.transactionsDir])try{await T($(e,r),r)}catch(i){t.push({severity:"error",code:"native-path-unsafe",message:`Managed Native path is unsafe: ${i.message}`,path:r})}return t}async function SB(e,t){let r=[],i=[];for(let n of await wn(e,e.transactionsDir,yB)){if(!n.isDirectory()||n.isSymbolicLink())continue;let a;try{a=await At(e,n.name)}catch(o){r.push({severity:"error",code:"transaction-invalid",message:`Native transaction ${n.name} is invalid: ${o.message}`,path:Me.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"){i.push(a),r.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 ja([e],`doctor archive recovery ${a.id}`,async()=>await lf([{paths:e,file:Me.join(e.locksDir,"root-move.lock")},{paths:e,file:Me.join(e.locksDir,"archive.lock")}],r)?(await LP({paths:e,transactionId:a.id,strategy:t.recoveryStrategy}),!0):!1)){i.push(a);continue}r.push({severity:"info",code:"archive-transaction-recovered",message:`${t.recoveryStrategy==="continue"?"Continued":"Rolled back"} archive transaction ${a.id}`})}catch(o){i.push(a),r.push({severity:"error",code:"archive-recovery-failed",message:`Archive recovery failed: ${o.message}`})}else i.push(a),r.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:r,unfinished:i}}async function EB(e,t,r){let i=[];for(let n of await wn(e,e.locksDir,NB)){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".lock"))continue;let a=Me.join(e.locksDir,n.name);try{let o=await Es(a);if(o.status==="active")i.push({severity:"warning",code:"lock-active",message:`Native lock is active for ${o.owner?.operation??"an operation"}`,path:a});else if(o.status==="unknown")i.push({severity:"warning",code:"lock-owner-unknown",message:"Native lock owner cannot be proven stale",path:a});else if(o.status==="stale")if(t&&r.length===0){let s=await bp(e,a,o);s.status==="removed"?i.push({severity:"info",code:"stale-lock-removed",message:"Removed a Native lock whose local owner process is absent",path:a}):s.status==="changed"&&i.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 i.push({severity:r.length>0?"error":"warning",code:"lock-stale",message:r.length>0?"Native lock is stale but an unfinished transaction still requires recovery":"Native lock owner process is absent",path:a})}catch(o){i.push({severity:"error",code:"lock-invalid",message:`Native lock metadata is invalid: ${o.message}`,path:a})}}return i}async function PB(e,t,r=5){let i=[],n=t?await Dv(e,{maxVerifyFailures:r}).then(a=>a.filter(o=>o.name===t)):await Dv(e,{maxVerifyFailures:r});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"){i.push({severity:"error",code:"change-invalid",message:a.error??`Native change ${a.name} is invalid`,path:Me.join(e.changesDir,a.name,Le)});continue}let o=await Hv(e,a.name,{details:!0,maxVerifyFailures:r});for(let s of o.findings??[])s.code==="trajectory-tail-incomplete"||s.code==="checkpoint-progress-incomplete"||i.push({severity:s.severity,code:s.code,message:`${a.name}: ${s.message}`,...s.path?{path:Me.join(e.projectRoot,s.path)}:{}})}return i}async function RB(e,t){let r=[],i=t.name?[t.name]:(await wn(e,e.changesDir,Io)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i)try{let a=await Qa(e,n);if(a.status!=="repairable")continue;if(!t.repair){r.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 Nk(e,n);o&&r.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){r.push({severity:"error",code:"trajectory-tail-repair-failed",message:`Native trajectory tail repair failed for ${n}: ${a.message}`,path:Me.join(M(e,n),"trajectory.jsonl")})}return r}async function CB(e,t){let r=[],i=t.name?[t.name]:(await wn(e,e.changesDir,Io)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a=await Ss(e,n);if(a.status==="missing"){r.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"){r.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=In(e,n),s=Ye(e,n);if(!t.repair){r.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 ja([e],`migrate Runtime layout for ${n}`,async()=>{let c=await fr({root:e.nativeRoot,directory:o,label:`Legacy Native Runtime ${n}`});await T(e.runtimeDir,s),await cf.mkdir(e.changesRuntimeDir,{recursive:!0});let l=await fr({root:e.runtimeDir,directory:e.changesRuntimeDir,label:`Native Runtime migration target parent ${n}`});try{throw await cf.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 cf.rename(o,s)}),r.push({severity:"info",code:"runtime-layout-migrated",message:`Moved Native Runtime for ${n} to project-local .comet storage`,path:s})}catch(c){r.push({severity:"error",code:"runtime-layout-migration-failed",message:`Native Runtime layout migration failed for ${n}: ${c.message}`,path:o})}}return r}async function xB(e,t){let r=[],i=t.name?[t.name]:(await wn(e,e.changesDir,Io)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i)try{if(!await om(e,n))continue;if(!t.repair){r.push({severity:"warning",code:"workspace-identity-migration-required",message:`Native workspace identity for ${n} uses legacy external-probe or hash-only metadata`,path:eo(e,n),repair:"migrate"});continue}let a=await We(e,n);await Ik({paths:e,name:n,revision:a.revision})&&r.push({severity:"info",code:"workspace-identity-migrated",message:`Replaced legacy workspace metadata for ${n} with process-free root identities`,path:eo(e,n)})}catch(a){r.push({severity:"error",code:"workspace-identity-migration-failed",message:`Native workspace identity migration failed for ${n}: ${a.message}`,path:eo(e,n)})}return r}async function AB(e,t){let r=[],i=t.name?[t.name]:(await wn(e,e.changesDir,Io)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a=_c(e,n);try{let o=await Ic(e,n),s=await Tr(e,n);if(!o&&s.status==="current")continue;if(s.status==="runtime-incompatible"){r.push({severity:"error",code:"change-runtime-incompatible",message:s.message??`Native change ${n} requires a newer runtime`,path:Me.join(e.changesDir,n,Le)});continue}if(!t.repair){r.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:Me.join(e.changesDir,n,Le),repair:"migrate"});continue}await ZP({paths:e,name:n}),r.push({severity:"info",code:o?"schema-migration-recovered":"schema-migrated",message:`Migrated Native change ${n} to the current schema`,path:Me.join(e.changesDir,n,Le)})}catch(o){if(o.code==="ENOENT")continue;r.push({severity:"error",code:"schema-migration-failed",message:`Native schema migration failed for ${n}: ${o.message}`,path:a})}}return r}async function _B(e,t){let r=[],i=t.name?[t.name]:(await wn(e,e.changesDir,Io)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a;try{a=await ni(e,n)}catch(o){if(o instanceof vc)continue;r.push({severity:"error",code:"transition-invalid",message:`Native transition journal is invalid: ${o.message}`,path:it(e,n)});continue}if(a){if(t.repair&&t.recoveryStrategy==="continue"){try{if(!await ja([e],`doctor transition recovery ${n}`,async()=>await lf([{paths:e,file:Me.join(e.locksDir,"root-move.lock")},{paths:e,file:Me.join(e.locksDir,`transition-${n}.lock`)}],r)?(await uE(e,n),!0):!1))continue;r.push({severity:"info",code:"transition-recovered",message:`Continued Native phase transition ${a.id} for ${n}`,path:it(e,n)})}catch(o){r.push({severity:"error",code:"transition-recovery-failed",message:`Native transition recovery failed: ${o.message}`,path:it(e,n)})}continue}r.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:it(e,n),repair:"continue"})}}return r}async function IB(e,t){let r=[],i=t.name?[t.name]:(await wn(e,e.changesDir,Io)).filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort();for(let n of i){let a=on(e,n),o;try{o=await sn(e,n)}catch(s){if(s.code==="ENOENT")continue;r.push({severity:"error",code:"checkpoint-progress-invalid",message:`Native progress checkpoint journal is invalid: ${s.message}`,path:a});continue}if(o){if(!t.repair){r.push({severity:"error",code:"checkpoint-progress-incomplete",message:`Native progress checkpoint ${o.id} is incomplete for ${n}`,path:a});continue}try{if(!await ja([e],`doctor checkpoint recovery ${n}`,async()=>await lf([{paths:e,file:Me.join(e.locksDir,"root-move.lock")},{paths:e,file:Me.join(e.locksDir,`transition-${n}.lock`)}],r)?(await kE(e,n),!0):!1))continue;r.push({severity:"info",code:"checkpoint-progress-recovered",message:`Continued Native progress checkpoint ${o.id} for ${n}`,path:a})}catch(s){r.push({severity:"error",code:"checkpoint-progress-recovery-failed",message:`Native progress checkpoint recovery failed: ${s.message}`,path:a})}}}return r}async function Oc(e){let t=e.repair??!1,r=[],i=e.paths,n;try{n=await Ee(i.projectRoot)}catch(c){return{healthy:!1,findings:[{severity:"error",code:"config-invalid",message:`Comet project config is invalid: ${c.message}`,path:i.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([Ke(i.projectRoot,c.fromArtifactRoot),Ke(i.projectRoot,c.toArtifactRoot)]);if(t&&e.recoveryStrategy)try{if(!await lf([{paths:l,file:Me.join(l.locksDir,"root-move.lock")},{paths:u,file:Me.join(u.locksDir,"root-move.lock")}],r))return{healthy:!1,findings:r};let f=await pR({projectRoot:i.projectRoot,strategy:e.recoveryStrategy});i=await Ke(i.projectRoot,f.config.native.artifact_root),a=!1,r.push({severity:"info",code:"root-move-recovered",message:`${e.recoveryStrategy==="continue"?"Continued":"Rolled back"} Native root move ${c.id}`})}catch(d){return r.push({severity:"error",code:"root-move-recovery-failed",message:`Native root recovery failed: ${d.message}`}),{healthy:!1,findings:r}}else r.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 kB(i);if(r.push(...o),o.length>0)return{healthy:!1,findings:r};let s=await SB(i,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy});return r.push(...s.findings),e.projectOnly||(r.push(...await CB(i,{name:e.name,repair:t})),r.push(...await AB(i,{name:e.name,repair:t})),r.push(...await xB(i,{name:e.name,repair:t})),r.push(...await RB(i,{name:e.name,repair:t})),r.push(...await _B(i,{name:e.name,repair:t,recoveryStrategy:e.recoveryStrategy})),r.push(...await IB(i,{name:e.name,repair:t})),r.push(...await sR({paths:i,name:e.name,repair:t,now:e.now,deferAll:a||s.unfinished.length>0}))),r.push(...await EB(i,t,s.unfinished)),r.push(...await bB(i,t)),e.projectOnly||r.push(...await PB(i,e.name,n?.native.max_verify_failures??5)),{healthy:r.every(c=>c.severity==="info"),findings:r}}Eo();Lt();ue();Ft();ke();ot();et();import{randomUUID as TB}from"node:crypto";import{promises as Je}from"node:fs";import Ge from"node:path";So();Pr();La();Q();var Gv=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 mR(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function vR(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let r=Ge.join(e.archiveDir,t);if(!D(e.archiveDir,r))throw new Error("Native Archive path escaped");return r}async function Hc(e){try{return await Je.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function gR(e,t){let r=Ge.normalize(Ge.resolve(e)),i=Ge.normalize(Ge.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}async function jB(e,t){let r;try{r=await Je.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let i=[];for(let n of r){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=Ge.join(e.archiveDir,n.name);try{let o=await Be(Ge.join(a,"comet-state.yaml"));o.name===t&&i.push({dir:a,state:o})}catch{}}if(i.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return i[0]??null}async function $B(e,t){let r=await Da(e,{kind:"archive",change:t});return r?.kind==="archive"?r.journal:null}async function aa(e,t){await Je.mkdir(e.transactionsDir,{recursive:!0}),await re(Li(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function OB(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let r=nr(e.paths.projectRoot);r.some(a=>gR(a,e.paths.projectRoot))||r.push(e.paths.projectRoot);let i=[];for(let a of r){let o=await Ee(a);if(!o)continue;let s=await Ke(a,o.native.artifact_root);i.some(c=>gR(c.changesDir,s.changesDir))||i.push(s)}i.length===0&&i.push(e.paths);let n=new Set;for(let a of i){let o;try{o=await Je.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 Be(Ge.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 Xu(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 HB(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 DB(e){let t=Ge.join(e.paths.specsDir,e.change.capability),r=Ge.join(t,"spec.md");if(!D(e.paths.specsDir,r))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let n;try{n=await Je.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 Je.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([Je.realpath(e.paths.specsDir),Je.realpath(t)]);if(!D(o,s))throw new Error("Native canonical capability path escaped");try{let c=await Je.lstat(r);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await Je.unlink(r)}catch(c){if(c.code!=="ENOENT")throw c}await Je.rmdir(t).catch(c=>{if(c.code!=="ENOENT"&&c.code!=="ENOTEMPTY")throw c});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);let i=Ge.join(Yt(e.paths,e.state.name),e.change.source);await ge(i,e.change.content,{containedRoot:e.paths.nativeRoot}),await Je.mkdir(t,{recursive:!0}),await ge(r,e.change.content,{containedRoot:e.paths.nativeRoot})}function yR(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 LB(e,t){let r=Yt(e,t.name),i=[];for(let n of t.spec_changes){if(n.source===null){i.push({...n,content:null});continue}let a=await te({root:r,ref:n.source,maxBytes:null,includeHash:!1});i.push({...n,content:a.text})}return i}function MB(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(yR(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function wR(e,t){for(let r of t.spec_changes.slice(0,t.next_spec_index)){let i=`${r.capability}/spec.md`,n=Ge.join(e.specsDir,i);if(r.operation==="remove"){if(!await Hc(n))continue}else try{if((await te({root:e.specsDir,ref:i,maxBytes:null,includeHash:!1})).text===r.content)continue}catch(a){if(a.code!=="ENOENT")throw a}throw new Error(`Canonical Spec ${i} changed after Archive applied it; preserve the concurrent edit and resolve it before resuming Archive`)}}async function Uv(e){return de(e.paths,`archive portable change ${e.name}`,async()=>{let t=HB(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let r=await $B(e.paths,e.name),i=Yt(e.paths,e.name),n=await Hc(i),a=n?null:await jB(e.paths,e.name),o;if(n)o=await ci(e.paths,e.name);else if(r)o=await Be(Ge.join(vR(e.paths,r.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);let s=await Ot(e.paths,e.name);if(n&&!o.archived&&r===null){let f=await _P({paths:e.paths,state:o});if(f.drifted){let h=f.reason??"Native confirmed requirements changed";throw await TP({paths:e.paths,state:o,reason:h}),new Error(`${h}; Native change returned to Shape and requires confirmation`)}}if(n&&!o.archived&&s?.finalVerification.status==="pending"&&o.verification_result==="pass"){let f=await IP({paths:e.paths,name:e.name});if(o=f.state,f.action==="rerun-final-verification")throw new Error("Native Supervisor final verification must be rerun for the current integration commit");f.action==="recorded-final-verification"&&(s=await Ot(e.paths,e.name))}let c=vR(e.paths,r?.archive_ref??mR(o)),l=await Hc(c);if(r&&MB(r,o),n&&l)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!r&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await Cc(e.paths,o.name),await Je.rm(Ye(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!r){if(!o.archived)yR(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let f=await OB({paths:e.paths,state:o});if(!o.archived&&f.length>0&&t!==o.name)throw new Gv(f);r={schema:Nu,id:TB(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:mR(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await LB(e.paths,o),created_at:new Date().toISOString()},await aa(e.paths,r)}if(!n&&l&&r.status==="report-aligned")r={...r,status:"moved"},await aa(e.paths,r);else if(!n&&l&&r.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${r.status}; doctor intervention is required`);await wR(e.paths,r);let u=r.spec_changes.slice(0,r.next_spec_index).map(({capability:f})=>Ge.relative(e.paths.projectRoot,Ge.join(e.paths.specsDir,f,"spec.md")).replaceAll("\\","/")),d=!1;if(r.status==="prepared"&&s&&!o.archived&&(s=(await Pc({paths:e.paths,state:s,archiveOwnedPaths:u})).state,d=!0),r.status==="prepared"){for(let f=r.next_spec_index;f<r.spec_changes.length;f+=1)await DB({paths:e.paths,state:o,change:r.spec_changes[f]}),r={...r,next_spec_index:f+1},await aa(e.paths,r),await e.hooks?.afterSpecApplied?.(f);r={...r,status:"specs-applied"},await aa(e.paths,r)}if(await wR(e.paths,r),r.status==="specs-applied"){if(s&&!o.archived&&!d&&(s=(await Pc({paths:e.paths,state:s,archiveOwnedPaths:u})).state,d=!0),!o.archived){let f={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await Hi({file:Ht(e.paths,o.name),expectedStateVersion:o.state_version,next:f,containedRoot:e.paths.nativeRoot})}r={...r,status:"state-finalized"},await aa(e.paths,r),await e.hooks?.afterFinalState?.()}if(r.status==="state-finalized"){let f=await Hc(i)?i:c;if(await Jd({file:Ge.join(f,"verification.md"),state:o,...s?{supervisor:s}:{}}),await zd({file:Ge.join(f,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");r={...r,status:"report-aligned"},await aa(e.paths,r),s&&!d&&(await Pc({paths:e.paths,state:s,archiveOwnedPaths:u}),d=!0),await e.hooks?.afterReportAligned?.()}if(r.status==="report-aligned"){if(s&&!d&&await Pc({paths:e.paths,state:s,archiveOwnedPaths:u}),await Je.mkdir(e.paths.archiveDir,{recursive:!0}),await Hc(c))throw new Error(`Native Archive target already exists: ${c}`);await Je.rename(i,c),r={...r,status:"moved"},await aa(e.paths,r),await e.hooks?.afterMove?.()}return r.status==="moved"&&(await Cc(e.paths,o.name),await Je.rm(Ye(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await Je.rm(Li(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:c,transactionId:r.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}_s();function Zt(e,t,r){return e.language==="zh-CN"?r:t}function FB(e,t){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:Zt(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:Zt(e,"Reply A or B","回复 A 或 B"),agentInstruction:Zt(e,"Relay the two coordination choices and wait for the user decision. After the user chooses, execute the prepare-shape-confirmation commandArgs with the selected --coordination-mode. Do not combine mode selection with final confirmation; confirmation of the complete Shape is a separate await-user step.","转述这两个推进方式并等待用户选择。用户选择后,使用对应的 --coordination-mode 执行 prepare-shape-confirmation 的完整 commandArgs;不要把推进方式选择和最终确认合并执行,完整 Shape 的确认是后续单独的 await-user 步骤。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return r(Zt(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return r(Zt(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:i})=>i==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{required:!0,message:Zt(e,"The reported verification passed, but this platform cannot confirm an independent Verifier execution. Review the result and choose whether to accept it for Archive, revise the implementation, or revise the requirements.","当前验收报告已通过,但当前平台无法确认验收是否独立执行。请检查结果,并选择接受结果进入归档、继续修改实现,或调整需求。"),suggestedReply:Zt(e,"Accept the result","接受结果"),agentInstruction:Zt(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")}:r(Zt(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 BB(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会先执行完整 dry-run,再给出唯一的 confirmed 命令;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"只向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 中包含 --dry-run --finish 的完整命令;选择 E 时停止,不运行任何 Archive 命令。不要直接运行 --confirmed,也不要自行猜测 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run a complete dry-run first, then return one confirmed command; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative containing --dry-run --finish; for E, stop without running an Archive command. Do not run --confirmed directly or guess a finish mode."}}function VB(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",e.name,"--dry-run","--finish",i],requiredInputs:[],inputOptions:[],description:Zt(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:Zt(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function bR(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function oa(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function qB(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function NR(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function WB(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function zB(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function yn(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:bR({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[oa("summary","--summary"),qB(e.name,e.flag)]}}function Kv(e){return[yn({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),yn({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function uf(e,t,r={}){let i=WB(t)&&e.coordination_mode===void 0,n=FB(e,i),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[oa("summary","--summary")],commandAlternatives:[yn({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[oa("summary","--summary")],commandAlternatives:[yn({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Kv({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[oa("summary","--summary")],commandAlternatives:[yn({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),yn({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[oa("summary","--summary")],commandAlternatives:[yn({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Kv({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[oa("summary","--summary")],commandAlternatives:Kv({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?bR({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:i?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:zB({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[NR("coordination-mode","--coordination-mode",eb)]:[]],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:u})=>u==="verified");if(s)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}]}}],runnerAction:o("none")};let c=t.children.some(({status:u})=>u==="blocked"||u==="needs-reverify"),l=t.children.some(({status:u})=>u==="ready"||u==="active");return{...a,disposition:c&&!l?"blocked":"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:c&&!l?["resolve-child-blocker"]:["ready-children"],inputOptions:[oa("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${Zt(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:c?[l]:[]}}],runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;return s==="blocked"?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:s==="preview"?r.archiveBlockers&&r.archiveBlockers.length>0?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}:l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[NR("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...VB(e)],userCommunication:BB(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[yn({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}Lt();ue();Ft();ke();et();Tp();La();pu();import{randomUUID as JB}from"node:crypto";import{promises as To}from"node:fs";import xR from"node:path";Pr();Q();_r();var Yv=["evidence.md","repair.md","archive.md","checkpoint.md"],GB="verification.md";async function UB(e){try{return await To.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Xv(e,t){let r=se(e,t),i=[Li(e,{kind:"migration",change:t}),In(e,t),...Yv.map(n=>xR.join(r,n))];return(await Promise.all(i.map(UB))).some(Boolean)}async function KB(e,t){let r=await Da(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function kR(e,t){await To.mkdir(e.transactionsDir,{recursive:!0}),await re(Li(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function SR(e,t,r={}){let i=r.removeVerificationReport===!1?Yv:[...Yv,GB];await Promise.all([To.rm(Ye(e,t),{recursive:!0,force:!0}),To.rm(In(e,t),{recursive:!0,force:!0}),...i.map(n=>To.rm(xR.join(se(e,t),n),{force:!0}))])}async function ER(e,t){await oi(mn(e,t.name),fn({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function PR(e,t){try{let r=await Tt(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function RR(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=ae(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function YB(e){let t=se(e.paths,e.state.name),r=await te({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await te({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return hu({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function CR(e,t){let r=await Xu(e,t);if(r.status==="runtime-incompatible")throw new Xr(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function Dc(e){return de(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await KB(e.paths,e.name),r=await vn(e.paths,e.name)?await Be(Ht(e.paths,e.name)):null;if(!t&&r)return await SR(e.paths,e.name,{removeVerificationReport:!1}),await ER(e.paths,r),r;let i=null,n=null;for(t||(i=await CR(e.paths,e.name),n=await PR(e.paths,e.name),RR(e.paths,n),t={schema:yu,id:JB(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await kR(e.paths,t));;){let a=ab(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await CR(e.paths,e.name),n??=await PR(e.paths,e.name),RR(e.paths,n),r=nb({state:i,acceptance:await YB({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await Ts(Ht(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await SR(e.paths,e.name):a.action==="commit-transaction"&&(r??=await Be(Ht(e.paths,e.name)),await ER(e.paths,r)),t={...t,status:a.nextStatus},await kR(e.paths,t)}return await To.rm(Li(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??Be(Ht(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}Lt();import{promises as _R}from"node:fs";import IR from"node:path";et();Eo();Xe();So();import{promises as Qv}from"node:fs";import XB from"node:path";var QB=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),ZB=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),eV=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task"]),tV=new Set(["status","summary"]);function df(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function ff(e,t,r){let i=new Set(Object.keys(e)),n=[...t].filter(o=>!i.has(o)),a=[...i].filter(o=>!t.has(o));return n.length===0&&a.length===0?null:`${r} fields must be exact (missing: ${n.join(", ")||"none"}; unexpected: ${a.join(", ")||"none"})`}function rV(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function sa(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function iV(e,t,r,i){let n=df(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=ff(n,QB,"Native Supervisor overlay");if(a)return a;if(i.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(i.parent!==t.name)return`Native Supervisor overlay parent ${i.parent} does not match ${t.name}`;let o=df(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=ff(o,ZB,"Native Supervisor integration");if(s)return s;if(i.integration.headCommit!==i.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=df(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=ff(c,tV,"Native Supervisor finalVerification");if(l)return l;if(i.finalVerification.status!=="pending"||i.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==r.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[u,d]of n.children.entries()){let f=df(d,`Native Supervisor child ${u}`);if(!f)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:h,contractHash:m,...p}=f,v=ff(p,eV,`Native Supervisor child ${u}`);if(v)return v;let g=r.children[u],N=g.covers.length>0?g.covers.map(w=>({id:w,source:r.acceptance_index?.[w]?.source??"brief.md",text:r.acceptance_index?.[w]?.text??w})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(h!==void 0&&JSON.stringify(h)!==JSON.stringify(N)||m!==void 0&&m!==O("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${g.name} acceptance scope does not match the legacy contract`;if(f.name!==g.name||f.summary!==g.summary||!rV(f.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let E=g.depends_on.length===0?"ready":"pending";if(f.status!==E)return`Native Supervisor child ${g.name} has progressed beyond its initial ${E} status`;if(f.baseCommit!==null||f.candidateCommit!==null||f.verifiedCommit!==null||f.integrationCommit!==null||f.verification!==null||f.blocker!==null||f.projectRoot!==null||f.task!==null)return`Native Supervisor child ${g.name} contains execution progress`;if(!Array.isArray(f.checks)||f.checks.length!==0)return`Native Supervisor child ${g.name} contains integration checks`}return null}async function ca(e){let t=$d(e.paths,e.state.name),r;try{let c=await Qv.lstat(t);if(!c.isFile()||c.isSymbolicLink())return sa(t,"","Native Supervisor overlay is not a regular file");r=await Qv.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:sa(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return sa(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=XB.join(e.paths.changesDir,e.state.name),a;try{a=await ea({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return sa(t,r,`Native children contract cannot be validated; restore children.yaml and retry next: ${c.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:r};let o;try{o=await Ot(e.paths,e.state.name)}catch(c){return sa(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return sa(t,r,"Native Supervisor overlay disappeared during inspection");let s=iV(i,e.state,a.contract,o);return s?sa(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}async function AR(e){let t=await ca({paths:e.paths,state:e.state});if(t.status!=="repairable-legacy-overlay"||t.snapshot!==e.expected.snapshot)throw new Error("Native Supervisor overlay changed before the safe repair could be applied");await Qv.rm(t.file,{force:!1})}Pr();js();function nV(e,t){let r=ae(e.projectRoot);if(t.workspace.change_branch!==null){if(!r.isGitWorktree)return"The portable change requires a Git branch/worktree";if(r.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:r.isGitWorktree?t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function aV(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function oV(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:Oi(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:Gr(t),completed_at:i});return Qe({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?aV(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 sV(e){try{let t=await Wd(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 TR(e){return de(e.paths,`recover portable change ${e.name}`,async()=>{let t=await ci(e.paths,e.name);if(t.status==="done")return await Gd({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let r=nV(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await ca({paths:e.paths,state:t});if(i.status==="incompatible")return{state:t,local:null,action:"await-user",reason:"overlay-incompatible",message:i.message};let n=!1;i.status==="repairable-legacy-overlay"&&(await AR({paths:e.paths,state:t,expected:i}),n=!0);let a=mn(e.paths,e.name),o=await sV(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason;if(s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed"&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(m=>m.status==="planned"||m.status==="running"?{...m,status:"interrupted"}:m)},await oi(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await Gd({paths:e.paths,state:t}),{state:t,local:o.local,action:"resume-stable-boundary",reason:s,message:n?"Removed a stale legacy Supervisor overlay and resumed the portable state.":"Native local execution overlay matches the portable state."};let l=s==="interrupted"?o.local?.checks.find(m=>m.status==="interrupted"&&!m.repeatable):void 0;if(l){let m=xv({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Hi({file:Ht(e.paths,t.name),expectedStateVersion:t.state_version,next:m,containedRoot:e.paths.nativeRoot}),await _R.rm(IR.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let p=fn({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await oi(a,p,{containedRoot:e.paths.runtimeDir}),{state:t,local:p,action:"resume-stable-boundary",reason:s,message:`Native check ${l.id} was not repeatable; the change returned to Build for a new candidate.`}}let u=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",d=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",f=u||d;if(f){let m=oV(t,d?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",d);t=await Hi({file:Ht(e.paths,t.name),expectedStateVersion:t.state_version,next:m,containedRoot:e.paths.nativeRoot})}let h=fn({portableState:t,projectRoot:e.paths.projectRoot,branch:ae(e.paths.projectRoot).currentBranch});return await _R.mkdir(IR.dirname(mn(e.paths,t.name)),{recursive:!0}),await oi(a,h,{containedRoot:e.paths.runtimeDir}),await Gd({paths:e.paths,state:t}),{state:t,local:h,action:f?"reverify":"resume-stable-boundary",reason:s,message:f?"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.`}})}Lt();Eo();So();import{promises as HR}from"node:fs";import cV from"node:path";import jR from"node:path";function $R(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function OR(e,t){let r=e.acceptance.reduce((i,n)=>({...i,[n.result]:i[n.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:r,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:$R(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},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(i=>i.outcome==="fail"&&i.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:$R(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(i=>i.source).filter(i=>i!==null)].slice(0,16).map(i=>jR.relative(t.projectRoot,jR.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}function lV(e,t,r){return`native-details-v2.${e}.${t}.${r.toString(36)}`}function uV(e,t,r){if(!e)return 0;let i=/^native-details-v2\.(\d+)\.(\d+)\.([0-9a-z]+)$/u.exec(e);if(!i||Number(i[1])!==t||Number(i[2])!==r)throw new Error("Native details cursor is stale or invalid");let n=Number.parseInt(i[3],36);if(!Number.isSafeInteger(n)||n<0)throw new Error("Native details cursor offset is invalid");return n}function dV(e,t,r){return[...e.acceptance.map(i=>({kind:"acceptance",value:i})),...e.spec_changes.map(i=>({kind:"spec-change",value:i})),...e.builder_handoff?[{kind:"builder-handoff",value:e.builder_handoff}]:[],...e.verification?[{kind:"verification",value:e.verification}]:[],...e.history.map(i=>({kind:"history",value:i})),{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(i=>({kind:"supervisor-child",value:pV(i,r)})),...t.history.map(i=>({kind:"supervisor-history",value:mV(i,r)}))]:[]]}function fV(e){return e.acceptance.reduce((t,r)=>({...t,[r.result]:t[r.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0})}function DR(e,t){let r=ae(e.projectRoot),i=null;return t.workspace.change_branch!==null&&(r.isGitWorktree?r.currentBranch!==t.workspace.change_branch&&(i=`Expected branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}.`):i="The Native change requires a registered Git worktree."),i===null&&t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree&&(i="The Native change requires its linked worktree."),{projectRoot:cV.resolve(e.projectRoot),isolation:t.workspace.isolation,bindingState:i===null?"aligned":"mismatch",changeBranch:t.workspace.change_branch,targetBranch:t.workspace.target_branch,finish:t.workspace.finish,message:i}}function hV(e,t){return[e.projectRoot,t.integration.worktree,...t.children.flatMap(r=>[r.projectRoot,r.task?.projectRoot])].filter(r=>!!r).map(r=>r.replaceAll("/","\\")).sort((r,i)=>i.length-r.length)}function hf(e,t){return e===null?null:t.reduce((r,i)=>r.replaceAll(i,"<worktree>").replaceAll(i.replaceAll("\\","/"),"<worktree>"),e)}function pV(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:hf(e.blocker,t),task:e.task?{...e.task,projectRoot:"<worktree>",baseCommit:"<redacted>",runId:"<redacted>"}:null}}function mV(e,t){return{...e,runId:e.runId?"<redacted>":null,summary:hf(e.summary,t)??""}}async function la(e){let t=await jP(e),r=OR(t.state),i=t.state.status==="active"&&t.state.loop.stage!=="done",n=await ta({paths:e.paths,state:t.state}),a=await ca({paths:e.paths,state:t.state}),o=a.status==="repairable-legacy-overlay"||a.status==="incompatible"?null:await Ot(e.paths,e.name,{diagnostics:!0}),s=o?{...DR(e.paths,t.state),projectRoot:"."}:DR(e.paths,t.state),c=uf(t.state,n),l=s.bindingState==="mismatch"?{...c,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["return-to-bound-workspace"],runnerAction:{...c.runnerAction,kind:"none"}}:c,u=o?hV(e.paths,o):[],d=o?(()=>{let m=o.children.filter(({status:w})=>w==="pending"||w==="ready").length,p=o.children.filter(({status:w})=>w==="active"||w==="verified").length,v=o.children.filter(({status:w})=>w==="integrated"||w==="archived").length,g=o.children.filter(({status:w})=>w==="blocked"||w==="needs-reverify").length,N=o.children.filter(({status:w})=>w==="active"||w==="blocked"||w==="needs-reverify").slice(0,16).map(w=>({name:w.name,summary:w.summary,projectRoot:w.task?.projectRoot??w.projectRoot?"<worktree>":null,reason:hf(w.blocker,u)})),E=o.children.flatMap(({blocker:w})=>{let S=hf(w,u);return S?[S]:[]}).slice(0,16);return{targetSpecs:t.state.spec_changes.length,implementationChildren:o.children.length,waiting:m,working:p,integrated:v,blocked:g,active:N,agents:{working:o.children.filter(({task:w})=>w!==null).length,completed:v},risks:E,nextAction:o.finalVerification.status==="passed"?"final-delivery":o.finalVerification.status==="pending"&&v===o.children.length?"parent-verification":m>0?"dispatch-ready-child":g>0?"resolve-blocker":"continue-supervisor"}})():null,f=e.details?(()=>{let m=o?.stateVersion??0,p=dV(t.state,o,u),v=uV(e.cursor,t.state.state_version,m),g=p.slice(v,v+32),N=v+g.length<p.length?lV(t.state.state_version,m,v+g.length):null;return{items:g,nextCursor:N,supervisorStateVersion:m}})():null,h=o?{schema:o.schema,parent:o.parent,integration:{branch:o.integration.branch,targetBranch:o.integration.targetBranch},finalVerification:{status:o.finalVerification.status,summary:o.finalVerification.summary},summary:d}: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:fV(t.state),unresolvedAcceptanceIds:r.unresolved_acceptance_ids,verificationResult:t.state.verification_result,blockers:o?[]:r.blockers,workspace:s,localExecution:{status:i?t.localStatus:"not-expected",operation:t.localStatus==="available"?t.local?.execution??null:null},...n?{childSummary:n.children.reduce((m,p)=>({...m,[p.status]:(m[p.status]??0)+1}),{total:n.children.length}),readyChildren:n.readyChildren}:{},...h?{supervisor:h}:{},...a.status==="repairable-legacy-overlay"||a.status==="incompatible"?{supervisorOverlay:{status:a.status,message:a.message,repairCommand:a.status==="repairable-legacy-overlay"?`comet native doctor ${e.name} --repair`:null}}:{},continuation:l,...e.details?{details:{stateVersion:t.state.state_version,...o?{supervisorStateVersion:f.supervisorStateVersion}:{},items:f.items,nextCursor:f.nextCursor,nextPageArgs:f.nextCursor?["comet","native","status",t.state.name,"--details","--cursor",f.nextCursor,"--json","--project-root",e.paths.projectRoot]:null}}:{}}}async function LR(e){let t;try{t=await HR.readdir(e.changesDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return[];throw i}let r=[];for(let i of t)if(!(!i.isDirectory()||i.isSymbolicLink()))try{let n=await HR.readFile(`${Yt(e,i.name)}/comet-state.yaml`,"utf8");/^schema:\s*comet\.native\.v4\s*$/mu.test(n)&&r.push(i.name)}catch(n){if(n.code!=="ENOENT")throw n}return r.sort((i,n)=>i.localeCompare(n,"en"))}La();ys();import Lc from"path";import{realpathSync as _V}from"fs";Lt();var di={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function MR(e){return e?e.command?`${di.next} ${e.command}`:e.ask_user?`${di.next} ${e.ask_user}`:null:null}function FR(e,t){let r=[e.summary],i=MR(e.next);return i&&r.push(i),e.user_message&&r.push("",di.relay,e.user_message),t!==void 0&&r.push("",di.details,JSON.stringify(t,null,2)),`${r.join(`
|
|
269
269
|
`)}
|
|
270
270
|
`}function BR(e,t,r){let i=[e.summary],n=MR(e.next);return n&&i.push(n),e.user_message&&i.push("",di.relay,e.user_message),i.push("",`${di.detail} ${t}`),r!==void 0&&i.push("",di.details,JSON.stringify(r,null,2)),i.join(`
|
|
271
|
-
`)}ke();Q();ot();function G(e,t,r){return e==="zh-CN"?r:t}var Zv={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function VR(e,t){return typeof e=="string"&&Zv[e]?G(t,Zv[e].en,Zv[e].zh):typeof e=="string"?e:""}function eg(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 vV(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function qR(e,t){let r=[];e.failed>0&&r.push(G(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(G(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(G(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=G(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function WR(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function tg(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function gV(e,t,r){return e==="done"?G(r,"complete","已完成"):e==="await-user"?G(r,"waiting for a user decision","等待用户决定"):e==="blocked"?G(r,"paused: needs attention","已暂停,需要处理"):t?G(r,"waiting for a user decision","等待用户决定"):G(r,"ready to continue","可继续推进")}function wV(e,t,r){let i=tg(e),n=[];r&&n.push(r);let a=G(i,`Change ${e.change}`,`需求 ${e.change}`),o=VR(e.phase,i),s=gV(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(qR(t,i));let c=e.userCommunication,l=zR(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function zR(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:G(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:G(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:G(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function yV(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function NV(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=VR(e.phase,t),n=e.status==="await-user"?G(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?G(t,"paused","已暂停"):e.status==="done"?G(t,"complete","已完成"):G(t,"in progress","进行中"),a=eg(e.acceptance)?`${G(t,", ",",")}${qR(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function bV(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function kV(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 SV(e){if(e.healthy){let i=e.repaired?G("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):G("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=EV(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:G("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:G("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function EV(e){return WR(e)?zR(e,tg(e)):void 0}function JR(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(kV(t))return SV(t);if(yV(t)){let i=bV(t.items);return{summary:[t.total===t.items.length?G(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):G(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>NV(a,i))].join(`
|
|
272
|
-
`)}}let r=t.continuation;if(WR(r))return wV(r,PV(t),RV(t,tg(r)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:G(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function PV(e){if(eg(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(eg(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return vV(r.acceptance)}return null}function RV(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return G(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?G(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function GR(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:G("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:G("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:G("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:G("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:G("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:G("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:G("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:G("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:G("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}vv();var UR=["--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."],ig=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.","
|
|
273
|
-
comet native spec sync <change-name> <capability> --input <json-file>`,purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal.","sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections without changing prose or acceptance."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},"spec sync":{usage:"comet native spec sync <change-name> <capability> --input <json-file>",purpose:"Sync local Markdown link destinations in an already confirmed target spec; semantic edits require Shape.",options:["--input <json-file> Fields: expectedStateVersion, actor, reason, affectedAcceptanceIds, replacements [{from,to}]. Include all acceptance IDs from the affected spec."],output:"The audited portable state, preserved unaffected acceptance results and Build continuation for re-verification."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"
|
|
271
|
+
`)}ke();Q();ot();function G(e,t,r){return e==="zh-CN"?r:t}var Zv={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function VR(e,t){return typeof e=="string"&&Zv[e]?G(t,Zv[e].en,Zv[e].zh):typeof e=="string"?e:""}function eg(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 vV(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function qR(e,t){let r=[];e.failed>0&&r.push(G(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(G(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(G(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=G(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function WR(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function tg(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function gV(e,t,r){return e==="done"?G(r,"complete","已完成"):e==="await-user"?G(r,"waiting for a user decision","等待用户决定"):e==="blocked"?G(r,"paused: needs attention","已暂停,需要处理"):t?G(r,"waiting for a user decision","等待用户决定"):G(r,"ready to continue","可继续推进")}function wV(e,t,r){let i=tg(e),n=[];r&&n.push(r);let a=G(i,`Change ${e.change}`,`需求 ${e.change}`),o=VR(e.phase,i),s=gV(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(qR(t,i));let c=e.userCommunication,l=zR(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function zR(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:G(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:G(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:r.required&&r.message?r.agentInstruction:G(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function yV(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function NV(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=VR(e.phase,t),n=e.status==="await-user"?G(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?G(t,"paused","已暂停"):e.status==="done"?G(t,"complete","已完成"):G(t,"in progress","进行中"),a=eg(e.acceptance)?`${G(t,", ",",")}${qR(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function bV(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function kV(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 SV(e){if(e.healthy){let i=e.repaired?G("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):G("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=EV(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:G("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:G("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function EV(e){return WR(e)?zR(e,tg(e)):void 0}function JR(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(kV(t))return SV(t);if(yV(t)){let i=bV(t.items);return{summary:[t.total===t.items.length?G(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):G(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>NV(a,i))].join(`
|
|
272
|
+
`)}}let r=t.continuation;if(WR(r))return wV(r,PV(t),RV(t,tg(r)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:G(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function PV(e){if(eg(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(eg(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return vV(r.acceptance)}return null}function RV(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return G(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?G(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function GR(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:G("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:G("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:G("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:G("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:G("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:G("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:G("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:G("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:G("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}vv();var UR=["--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."],ig=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","spec sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:UR,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>
|
|
273
|
+
comet native spec sync <change-name> <capability> --input <json-file>`,purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal.","sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections without changing prose or acceptance."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},"spec sync":{usage:"comet native spec sync <change-name> <capability> --input <json-file>",purpose:"Sync local Markdown link destinations in an already confirmed target spec; semantic edits require Shape.",options:["--input <json-file> Fields: expectedStateVersion, actor, reason, affectedAcceptanceIds, replacements [{from,to}]. Include all acceptance IDs from the affected spec."],output:"The audited portable state, preserved unaffected acceptance results and Build continuation for re-verification."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"A compact summary and NEXT action by default. Use --json to read the portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required. Fill command-template placeholders before executing NEXT commands."},check:{usage:"comet native check <change-name>",purpose:"Legacy-only verification command; not supported for current portable changes.",output:"For current changes, run comet native status <change-name> --json and follow the continuation to dispatch verification through comet native next."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page, or a named details/history page.","--details Include one fixed-size page of acceptance, Spec, handoff, verification, history, workspace, and report details."],output:"A compact v2 status page or one compact Loop projection with local execution availability. Use --details and --cursor to read fixed-size detail pages; parent changes expose childSummary and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--coordination-mode multi-session|single-session] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
|
|
274
274
|
comet native next <change-name> --summary <text> [--confirmed|--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--expected-state-version <n>] [--expected-action <action>]
|
|
275
275
|
comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm the persisted Shape boundary with both expected guards, or confirm an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Select how a multi-child Supervisor proceeds while preparing its Shape confirmation; final Shape confirmation is a later, separate step.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a failed or unavailable Verifier when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--max-parallel <n> Supervisor task concurrency cap; defaults to 2, use 1 for serial fallback.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits, review. review fields: status=passed, summary, reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."," Supervisor task fields: supervisor-builder-result (child, runId, candidateCommit), supervisor-builder-failure (child, runId, reason), supervisor-verifier-result (child, runId, verdict, verification data), supervisor-reconnect (child, runId), supervisor-cancel (child, runId, reason), or supervisor-integrate (child, checks)."," supervisor-checks fields: kind, child, runId, checks (non-empty repeatable Runtime check plans), materials [{name,content}]. Returns checkExecution with operationId, status and receiptRef. Repeated running plans return the same handle."," supervisor-verifier-result evidence fields: summary, checks (informal notes), acceptance [{id,result,reason}], receiptRef. verdict is pass, fail or blocked; every task acceptance ID must appear exactly once. Runtime receipts determine formal check status; receiptRef may be null for fail or blocked."," supervisor-integrate checks are non-empty Runtime check plans executed after the merge in the integration worktree, not declared statuses."],output:'A compact portable state summary, explicit skill-coordinated label, Runtime-owned check results, scoped verifierDispatch, bounded request-check response, continuation.runnerAction, machine-readable continuation.inputOptions, and continuation.userCommunication with a user-ready message and Agent relay guidance. Read acceptance text and other long fields from paged status --details output. Human-readable verification statuses include "Host independently verified", "Checks completed, but your confirmation is required", "Full verification was unavailable; only automatic checks completed", and "You accepted the incomplete verification result". This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.',examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed --expected-state-version <n> --expected-action confirm-shape','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
|
|
276
276
|
comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Run the complete read-only Archive and workspace-finish readiness check; it persists only an explicit --finish choice.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness, every blocker, and the exact next continuation, or the completed Archive transaction and workspace finish result. Execute the returned confirmed command only after ready is true; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function rg(e,t){return`${e}:
|
|
@@ -278,11 +278,11 @@ ${t.map(r=>` ${r}`).join(`
|
|
|
278
278
|
`)}`}function CV(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return ig[r]||t.length>1&&ig[t[0]]?.subcommands?r:t[0]}function xV(e=[]){let t=CV(e),r=ig[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.subcommands&&i.push("",rg("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...UR];return n&&n.length>0&&i.push("",rg("Options",n)),i.push("",`Output:
|
|
279
279
|
${r.output}`),r.examples&&i.push("",rg("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
|
|
280
280
|
`)}
|
|
281
|
-
`}}var AV=xV().usage;var AX=10*1024*1024,
|
|
282
|
-
`}function fi(e,t,r){return{command:e,exitCode:0,data:t,text:r??ZR(t)}}function TV(e,t){if(t instanceof
|
|
281
|
+
`}}var AV=xV().usage;var AX=10*1024*1024,er=class extends Error{};function Mc(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new er(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function pf(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new er(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new er(`${t} requires a value`);return e.splice(i,2),n}function YR(e){if(e.length>0)throw new er(`Unexpected argument: ${e[0]}`)}function ng(e,t){let r=Lc.normalize(KR(e)),i=Lc.normalize(KR(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function KR(e){let t=Lc.resolve(e);try{return _V.native(t)}catch{return t}}function IV(e){let t=Lc.resolve(e),r=ae(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=ae(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!ng(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||ng(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:ng(process.cwd(),r.currentWorktreeRoot)?Lc.resolve(process.cwd()):r.currentWorktreeRoot}async function XR(e){return e?IV(e):gp(process.cwd())}async function QR(e){let t=await Ee(e);return Ke(e,t?.native.artifact_root??"docs")}function ZR(e){return JSON.stringify(e,null,2)+`
|
|
282
|
+
`}function fi(e,t,r){return{command:e,exitCode:0,data:t,text:r??ZR(t)}}function TV(e,t){if(t instanceof er)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Kd)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 xc)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Xs)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 Qs)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 Td)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof ro)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 cn)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof yc)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function eC(e,t){let r=TV(e,t),i=r.error;if(!i)return r;let n=GR({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function tC(e,t,r=!1){let i=e.envelope??JR(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
|
|
283
283
|
`}:e.error?{exitCode:e.exitCode,stderr:i?BR(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:FR(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==ZR(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
|
|
284
284
|
${di.details}
|
|
285
285
|
${JSON.stringify(e.data,null,2)}
|
|
286
|
-
`}:{exitCode:e.exitCode,stdout:e.text}}async function Fc(e,t){let r=await ta({paths:e,state:t});return uf(t,r)}async function jV(e){let t;try{t=await nC.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return t.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort((r,i)=>r.localeCompare(i,"en"))}function $V(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function rC(e,t){let r;try{r=await nC.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return null;throw a}let i=new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${$V(t)}$`,"u"),n=r.find(a=>a.isDirectory()&&!a.isSymbolicLink()&&i.test(a.name));return n?{severity:"error",code:"portable-active-archive-conflict",message:`Native change ${t} exists in both active and Archive storage`,path:mf.join(e.archiveDir,n.name)}:null}function OV(e){let t=new Map;for(let r of e){let i=[r.severity,r.code,r.message,r.path??""].join("\0");t.set(i,r)}return[...t.values()]}function Bc(e){return{command:"doctor",exitCode:65,data:e,error:{code:"invalid-data",message:"Native project needs attention"}}}function iC(e,t){return{severity:"error",code:"portable-migration-incomplete",message:`Native portable migration is incomplete for ${t}`,path:mf.join(e.changesDir,t,"comet-state.yaml"),repair:"migrate"}}function HV(e,t){return t.status==="repairable-legacy-overlay"?{severity:"error",code:"portable-supervisor-overlay-stale",message:t.message,path:t.file,repair:"continue",repairCommand:`comet native doctor ${e} --repair`}:t.status==="incompatible"?{severity:"error",code:"portable-supervisor-overlay-incompatible",message:t.message,path:t.file}:null}async function DV(e,t){let r=[],i=[];for(let n of await ub(e)){let a=Dn(n);if(t&&a.change!==t)continue;let o=mf.join(e.transactionsDir,n);try{let s=await Os(e,n);if(!s)continue;r.push(s),i.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){i.push({severity:"error",code:"portable-transaction-invalid",message:`Native portable transaction ${n} is invalid: ${s.message}`,path:o})}}return{transactions:r,findings:i}}async function ag(e,t){let r=Mc(e,"--repair"),i=pf(e,"--strategy");if(i!==void 0&&i!=="continue"&&i!=="rollback")throw new
|
|
286
|
+
`}:{exitCode:e.exitCode,stdout:e.text}}async function Fc(e,t){let r=await ta({paths:e,state:t});return uf(t,r)}async function jV(e){let t;try{t=await nC.readdir(e.changesDir,{withFileTypes:!0})}catch(r){if(r.code==="ENOENT")return[];throw r}return t.filter(r=>r.isDirectory()&&!r.isSymbolicLink()).map(r=>r.name).sort((r,i)=>r.localeCompare(i,"en"))}function $V(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}async function rC(e,t){let r;try{r=await nC.readdir(e.archiveDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return null;throw a}let i=new RegExp(`^\\d{4}-\\d{2}-\\d{2}-${$V(t)}$`,"u"),n=r.find(a=>a.isDirectory()&&!a.isSymbolicLink()&&i.test(a.name));return n?{severity:"error",code:"portable-active-archive-conflict",message:`Native change ${t} exists in both active and Archive storage`,path:mf.join(e.archiveDir,n.name)}:null}function OV(e){let t=new Map;for(let r of e){let i=[r.severity,r.code,r.message,r.path??""].join("\0");t.set(i,r)}return[...t.values()]}function Bc(e){return{command:"doctor",exitCode:65,data:e,error:{code:"invalid-data",message:"Native project needs attention"}}}function iC(e,t){return{severity:"error",code:"portable-migration-incomplete",message:`Native portable migration is incomplete for ${t}`,path:mf.join(e.changesDir,t,"comet-state.yaml"),repair:"migrate"}}function HV(e,t){return t.status==="repairable-legacy-overlay"?{severity:"error",code:"portable-supervisor-overlay-stale",message:t.message,path:t.file,repair:"continue",repairCommand:`comet native doctor ${e} --repair`}:t.status==="incompatible"?{severity:"error",code:"portable-supervisor-overlay-incompatible",message:t.message,path:t.file}:null}async function DV(e,t){let r=[],i=[];for(let n of await ub(e)){let a=Dn(n);if(t&&a.change!==t)continue;let o=mf.join(e.transactionsDir,n);try{let s=await Os(e,n);if(!s)continue;r.push(s),i.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){i.push({severity:"error",code:"portable-transaction-invalid",message:`Native portable transaction ${n} is invalid: ${s.message}`,path:o})}}return{transactions:r,findings:i}}async function ag(e,t){let r=Mc(e,"--repair"),i=pf(e,"--strategy");if(i!==void 0&&i!=="continue"&&i!=="rollback")throw new er("--strategy must be continue or rollback");let n=e[0]?.startsWith("--")?void 0:e.shift();YR(e);let a=await QR(t),o=await DV(a,n);if(n&&o.findings.length>0){if(i)throw new er("--strategy is only available to the legacy transaction doctor");let d=await vn(a,n)?await la({paths:a,name:n,details:!0}):void 0;if(r&&o.transactions.length===1&&o.findings.length===1){if(o.transactions[0].kind==="archive"){let m=await Uv({paths:a,name:n});return fi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,archive:{recovered:!0,transactionId:m.transactionId},state:m.state,continuation:await Fc(a,m.state)})}let h=await Dc({paths:a,name:n});return fi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:h.schema,stateVersion:h.state_version},state:h,continuation:await Fc(a,h)})}return Bc({healthy:!1,workflow:"native-portable",change:n,repaired:!1,...d?{result:d,continuation:d.continuation}:{},findings:o.findings})}if(n&&await vn(a,n)){if(i)throw new er("--strategy is only available to the legacy transaction doctor");let[u,d]=await Promise.all([rC(a,n),Xv(a,n)]);if(u){let v=await la({paths:a,name:n,details:!0});return Bc({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:v,findings:[u],continuation:v.continuation})}if(d&&!r){let v=await la({paths:a,name:n,details:!0});return Bc({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:v,findings:[iC(a,n)],continuation:v.continuation})}let f=await ci(a,n),h=await ca({paths:a,state:f}),m=HV(n,h);if(m&&(h.status==="incompatible"||!r)){let v=await la({paths:a,name:n,details:!0});return Bc({healthy:!1,workflow:"native-portable",change:n,repaired:!1,result:v,findings:[m],continuation:v.continuation})}if(r){if(d){let g=await Dc({paths:a,name:n});return fi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{recovered:!0,to:g.schema,stateVersion:g.state_version},state:g,continuation:await Fc(a,g)})}let v=await TR({paths:a,name:n});return fi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,result:v,continuation:await Fc(a,v.state)})}let p=await la({paths:a,name:n,details:!0});return fi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!1,result:p,continuation:p.continuation})}if(n){if(r){let u=await Dc({paths:a,name:n});return fi("doctor",{healthy:!0,workflow:"native-portable",change:n,repaired:!0,migration:{from:"legacy",to:u.schema,stateVersion:u.state_version},state:u,continuation:await Fc(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 LR(a),c=o;if(s.length>0||c.findings.length>0){if(i)throw new er("--strategy is only available to the legacy transaction doctor");if(r){let S=await Oc({paths:a,repair:!0,projectOnly:!0}),k=[];for(let y of c.transactions)y.kind==="archive"?await Uv({paths:a,name:y.change}):await Dc({paths:a,name:y.change}),k.push({kind:y.kind,change:y.change,transactionId:y.journal.id});let R=await ag([],t),b=R.data&&typeof R.data=="object"&&!Array.isArray(R.data)?R.data:{};return{...R,data:{...b,repaired:!0,repairedPortableTransactions:k,repairFindings:S.findings}}}let u=await jV(a),d=new Set(s),f=new Set(c.transactions.filter(S=>S.kind==="migration").map(({change:S})=>S)),h=u.filter(S=>!d.has(S)),[m,p,v,g,N]=await Promise.all([Promise.all(s.map(S=>la({paths:a,name:S}))),Promise.all(s.map(S=>rC(a,S))),Promise.all(s.map(S=>Xv(a,S))),Promise.all(h.map(S=>Oc({paths:a,name:S}))),Oc({paths:a,projectOnly:!0})]),E=OV([...p.filter(S=>S!==null),...s.flatMap((S,k)=>v[k]&&!f.has(S)?[iC(a,S)]:[]),...c.findings,...h.map(S=>({severity:"error",code:"portable-migration-required",message:`Native active change ${S} requires migration to portable Runtime`,path:mf.join(a.changesDir,S,"comet-state.yaml"),repair:"migrate"})),...g.flatMap(({findings:S})=>S),...N.findings]),w={healthy:E.every(S=>S.severity==="info"),workflow:h.length>0?"native-mixed":"native-portable",changes:m,legacyChanges:h,findings:E};return w.healthy?fi("doctor",w):Bc(w)}let l=await Oc({paths:a,...n?{name:n}:{},repair:r,...i?{recoveryStrategy:i}:{}});return l.healthy?fi("doctor",l):{command:"doctor",exitCode:65,data:l,error:{code:"invalid-data",message:"Native project needs attention"}}}async function aC(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{Mc(n,"--json"),Mc(n,"--verbose"),c=pf(n,"--project-root");let d=[...n,...a],f=await XR(c);l=await t(d,f)}catch(d){l=eC(e,d)}let u=tC(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
|
|
287
287
|
`)?"":`
|
|
288
288
|
`)),u.exitCode}process.exitCode=await aC("doctor",ag);
|