@unbrained/pm-cli 2026.10.26 → 2026.10.28
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/.claude-plugin/marketplace.json +1 -1
- package/CHANGELOG.md +39 -1
- package/dist/cli/commander-usage.js +2 -2
- package/dist/cli/error-guidance.js +2 -2
- package/dist/cli/register-list-query.js +5 -5
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-2J7I54MQ.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-25MTQAHX.js → chunk-3KMYHYJV.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-7V37RC2L.js +114 -0
- package/dist/cli-bundle/chunks/chunk-AHVN4GHF.js +31 -0
- package/dist/cli-bundle/chunks/{chunk-VS2IIV3F.js → chunk-CS7QDSUX.js} +28 -28
- package/dist/cli-bundle/chunks/{chunk-T7T4WLUY.js → chunk-CXUQEZDX.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-ZT64RDMF.js → chunk-D3AIQZXF.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-7UDQAINZ.js → chunk-D6P6IBPN.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-TGOG5BFM.js → chunk-DKLEDWVW.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-MWCG25PO.js → chunk-DM3PICGU.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-Y42DYMZX.js → chunk-E5QBZ4HI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XAIR53QZ.js → chunk-JESLOJD7.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-57YPOOED.js → chunk-LWW4F4G2.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-PQLRKFPZ.js +20 -0
- package/dist/cli-bundle/chunks/{chunk-ONC4BBQP.js → chunk-RZQNFHXO.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-SPPHDVZE.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-ER7RLJW5.js → chunk-TH5KPAN4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-OCDRHIVQ.js → chunk-XHONSCLJ.js} +6 -6
- package/dist/cli-bundle/chunks/{chunk-NGKTROAO.js → chunk-YUBUNECD.js} +42 -42
- package/dist/cli-bundle/chunks/{chunk-Z35XAHUN.js → chunk-YYD5MNAV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-UF6EXZSP.js → chunk-ZX3XMTZG.js} +2 -2
- package/dist/cli-bundle/chunks/indexed-receipt-blobs-LHLE7PSG.js +4 -0
- package/dist/cli-bundle/chunks/{mutation-admission-VTNV6JV2.js → mutation-admission-GKDKHRTZ.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-LZDWUZS4.js → register-list-query-MHJJUM6M.js} +9 -9
- package/dist/cli-bundle/chunks/{register-mutation-M2A7PH42.js → register-mutation-SN425O3R.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-E7P2JTXM.js → register-operations-EYUIUGPW.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-DOV7KGSH.js → register-setup-WUZ2ZSMY.js} +2 -2
- package/dist/cli-bundle/chunks/{settlement-hook-SVD6CO7U.js → settlement-hook-MN3Y7LVX.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-LYLEOAQB.js → stage-2FYJGGG3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-3EHVI673.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-46WLWK73.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-E5C24MCV.js → chunk-4GN2ZPT5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NLZUI234.js → chunk-6L4KKRK7.js} +18 -18
- package/dist/cli-bundle/focused-chunks/{chunk-D5YQ4KAE.js → chunk-6VDRAJYX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-KTXU5WU6.js → chunk-7SZPZOIC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-YQKLKRMW.js → chunk-B4ZQJEMT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NE27VCU7.js → chunk-BZSACRVX.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-ADSBGYLW.js → chunk-C2GLO7HU.js} +55 -55
- package/dist/cli-bundle/focused-chunks/{chunk-UP765R2V.js → chunk-DRN4W3YJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-EGN2HFRU.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-CSCZYSNZ.js → chunk-F6UQJJYB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-I7H3XF25.js → chunk-I4X6AKOO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-IQKLJFJE.js +79 -0
- package/dist/cli-bundle/focused-chunks/{chunk-KERJNFXY.js → chunk-JTCGDODH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-IF6C43IP.js → chunk-L5GX2FGZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-PK5FJIVA.js → chunk-LPWZERVD.js} +11 -11
- package/dist/cli-bundle/focused-chunks/{chunk-YW5GHQN2.js → chunk-ML5JIUM6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-BL77VCRB.js → chunk-OASYSUOH.js} +16 -16
- package/dist/cli-bundle/focused-chunks/{chunk-BH7RE2ZY.js → chunk-ON5WFDCG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-WDWHUJQW.js → chunk-QUPGBO2L.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-226XKW3W.js → chunk-R3EA3SDW.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-B266DDBJ.js → chunk-TUN4M757.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-YTEC2EPM.js → chunk-Z26ZPQH6.js} +3 -3
- package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-5H6RMRTK.js +4 -0
- package/dist/cli-bundle/focused-chunks/{mutation-admission-L42E3U5U.js → mutation-admission-TM3SVU2O.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{settlement-hook-3CADO4XZ.js → settlement-hook-LBVWWSCF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-TUQHWU7N.js → stage-7ZBRX2Q2.js} +2 -2
- package/dist/cli-bundle/main.js +21 -21
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +34 -33
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +57 -57
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +11 -11
- package/dist/core/history/event-index.d.ts +6 -0
- package/dist/core/history/event-index.js +7 -6
- package/dist/core/history/read.d.ts +3 -1
- package/dist/core/history/read.js +1 -1
- package/dist/core/item/priority.js +1 -1
- package/dist/core/shared/errors.d.ts +2 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/mcp/tool-definitions.js +1 -1
- package/dist/sdk/agent/command-recovery.d.ts +5 -0
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/command-line.d.ts +6 -0
- package/dist/sdk/command-line.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/lifecycle/close.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/update-many.js +1 -1
- package/dist/sdk/lifecycle/update.js +1 -1
- package/dist/sdk/merge/indexed-receipt-blobs.d.ts +3 -1
- package/dist/sdk/merge/indexed-receipt-blobs.js +2 -2
- package/dist/sdk/merge/receipt-file-boundary.d.ts +2 -0
- package/dist/sdk/merge/receipt-file-boundary.js +1 -1
- package/dist/sdk/merge/receipts.js +2 -2
- package/dist/sdk/mutation-events.d.ts +6 -0
- package/dist/sdk/mutation-events.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/history.d.ts +4 -0
- package/dist/sdk/query/history.js +1 -1
- package/dist/sdk/runtime/actions.js +1 -1
- package/dist/sdk/runtime-extended-actions.js +1 -1
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/test/command-resolution.d.ts +5 -0
- package/dist/sdk/test/command-resolution.js +3 -0
- package/dist/sdk/test/execution.js +3 -3
- package/dist/sdk/test/receipt-index-snapshot.d.ts +2 -0
- package/dist/sdk/test/receipt-index-snapshot.js +2 -0
- package/dist/sdk/test/workspace-snapshot.d.ts +1 -1
- package/dist/sdk/test/workspace-snapshot.js +1 -1
- package/docs/COMMANDS.md +28 -1
- package/docs/PERFORMANCE.md +21 -6
- package/docs/RELEASING.md +11 -0
- package/docs/SDK.md +40 -0
- package/docs/SDK_CONTEXT_COORDINATION.md +35 -4
- package/docs/TESTING.md +42 -3
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +2 -2
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +4 -3
- package/marketplace.json +1 -1
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-N6FTEILW.js +0 -20
- package/dist/cli-bundle/chunks/chunk-OUDR2HWR.js +0 -113
- package/dist/cli-bundle/chunks/chunk-RUKSEZE7.js +0 -2
- package/dist/cli-bundle/chunks/chunk-YJBIPNDL.js +0 -2
- package/dist/cli-bundle/chunks/chunk-ZLVFUZI4.js +0 -30
- package/dist/cli-bundle/chunks/indexed-receipt-blobs-NWQIDTH7.js +0 -4
- package/dist/cli-bundle/focused-chunks/chunk-ABMNYWV6.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-NFN2P4TW.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-UHWTPOM4.js +0 -78
- package/dist/cli-bundle/focused-chunks/chunk-VVRXF4JO.js +0 -2
- package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-YFDNGHCM.js +0 -4
|
@@ -1,113 +0,0 @@
|
|
|
1
|
-
import{A as h,C as g,E as ft,F as Se,G as me,H as we,I as td,J as Li,K as mt,L as rd,a as xe,b as ji,c as Yc,e as Pn,f as Mn,g as $n,h as Xc,i as jn,j as Bt,k as Jc,m as Ee,n as Zc,o as Qc,p as Ln,q as Fn,u as xr,v as ed,y as S,z as Nr}from"./chunk-ONC4BBQP.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="451b262c-a9b6-5f1c-b397-2686a5fd953a")}catch{}})();var z_=[["history-redact","history redact"],["history-repair","history repair"],["history-compact","history compact"],["activity","history activity"],["restore","history restore"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!0,registration:"commander",owner:"pm-tqel"})),U_=[...["next","focus"].map(e=>({alias:e,canonical:`context ${e}`,owner:"pm-kcs4"})),...["stats","health","validate","gc","telemetry","eval","test-all"].map(e=>({alias:e,canonical:`ops ${e}`,owner:"pm-6apl"})),...["normalize","reindex"].map(e=>({alias:e,canonical:`ops ${e}`,owner:"pm-3i9q8g"})),{alias:"events",canonical:"history events",owner:"pm-3i9q8g"}].map(e=>({...e,canonical_argv:e.canonical.split(" "),lifecycle:"permanent",hidden:!0,registration:"bootstrap"})),H_=[["update-many","update many"],["close-many","close many"],["delete","close delete"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!0,registration:"bootstrap",owner:"pm-ik19"})),q_=[...U_,...H_,...["init","config","schema","profile"].map(e=>({alias:e,canonical:`workspace ${e}`,canonical_argv:["workspace",e],lifecycle:"permanent",hidden:!0,registration:"bootstrap",owner:"pm-npr3"})),...[...["comments","notes","learnings","files","docs","deps","append","test"].map(e=>[e,`item ${e}`,"pm-yql1"]),["test-runs-worker","item test worker","pm-lp4j"],...["statuses","tags","types"].map(e=>[`completion-${e}`,`completion ${e}`,"pm-szdc"]),["history-author-acknowledge","history acknowledge","pm-djyvbk"],["copy","item copy","pm-m6g87m"],["merge","workspace merge","pm-m6g87m"],["duplicates","item duplicates","pm-fmy9ih"],["dedupe-audit","item duplicates audit","pm-fmy9ih"],["dedupe-merge","item duplicates merge","pm-fmy9ih"],["comments-audit","item audit-comments","pm-fmy9ih"],["search-advanced","search advanced","pm-wfskfn"],...["meet","event","remind"].map(e=>[e,`calendar ${e}`,"pm-o3fh"])].map(([e,t,r])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!0,registration:"bootstrap",owner:r}))],Fi=[{alias:"history-attest",canonical:"history attest",canonical_argv:["history","attest"],lifecycle:"permanent",hidden:!0,registration:"commander",owner:"pm-3z0k"},...z_,...q_,...["discover","lookup"].map(e=>({alias:`files ${e}`,canonical:`item files ${e}`,canonical_argv:["item","files",e],lifecycle:"permanent",hidden:!0,registration:"bootstrap",owner:"pm-yql1"}))];function iT(e){let t;for(let r of Fi)r.canonical_argv.length<=(t?.canonical_argv.length??0)||r.canonical_argv.every((n,o)=>n===(o===0&&e[o]==="ctx"?"context":e[o]))&&(t=r);return t}function V_(e){let t=e.trim().replace(/\s+/gu," ");return Fi.find(r=>r.canonical===t.replace(/^ctx /u,"context "))?.alias??t}function Dr(e){return V_(e)}var zn=[...Fi,...[["ctx","context"],["packages","package"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:[t],lifecycle:"permanent",hidden:!1,registration:"commander",owner:"pm-pbyu"})),...[["start-task","claim","--start"],["pause-task","release","--pause"],["close-task","close","--release-assignment"]].map(([e,t,r])=>({alias:e,canonical:t,canonical_argv:[t,r],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-eq4x"})),{alias:"tests",canonical:"item test",canonical_argv:["item","test"],lifecycle:"permanent",hidden:!1,registration:"bootstrap",owner:"pm-u4t9gp"},...[["fetch","get"],["read","get"],["show","get"],["view","get"],["comment","comments"],["note","notes"],["learning","learnings"]].map(([e,t])=>({alias:e,canonical:["comments","notes","learnings"].includes(t)?`item ${t}`:t,canonical_argv:["comments","notes","learnings"].includes(t)?["item",t]:[t],lifecycle:"permanent",hidden:!1,registration:"bootstrap",owner:"pm-pbyu"})),...[["extension list","extension catalog"],["extension scaffold","extension init"],["package list","package catalog"],["package scaffold","package init"],["packages list","package catalog"],["packages scaffold","package init"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!1,registration:"commander",owner:"pm-ya7x55"})),{alias:"list-all",canonical:"list",canonical_argv:["list","--all"],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-pfqi"},...[["list-draft","draft"],["list-open","open"],["list-in-progress","in_progress"],["list-blocked","blocked"],["list-closed","closed"],["list-canceled","canceled"]].map(([e,t])=>({alias:e,canonical:"list",canonical_argv:["list","--status",t],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-pfqi"})),...[["extension","package"],["install","package install"],["upgrade","package upgrade"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-tnud"}))],sT=Object.fromEntries(zn.filter(e=>e.registration==="bootstrap").map(e=>[e.alias,e.canonical]));function aT(e){let t=e.trim().toLowerCase();return zn.find(r=>r.alias===t)}function cT(e){return`Deprecated command \`${e.alias}\`; use \`pm ${e.canonical_argv.join(" ")}\`.`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2ea7934f-4751-5245-a5ba-492681aa3794")}catch{}})();var zi=[{kind:"blocked_by",direction:"directed",traversal:"ordering",inverse:"blocks",ordering:!0,precedence:"target_before_source",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",aliases:["depends_on"],compatibilityVersion:1,allowSelf:!1},{kind:"blocks",direction:"directed",traversal:"ordering",inverse:"blocked_by",ordering:!0,precedence:"source_before_target",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"parent",direction:"directed",traversal:"hierarchy",outcomeTraversal:"source_to_target",inverse:"child",ordering:!1,hierarchy:!0,hierarchyDirection:"target_parent",outgoing:"one",incoming:"many",lifecycle:"supersedable",aliases:["child_of","epic"],compatibilityVersion:1,allowSelf:!1},{kind:"child",direction:"directed",traversal:"hierarchy",outcomeTraversal:"target_to_source",inverse:"parent",ordering:!1,hierarchy:!0,hierarchyDirection:"source_parent",outgoing:"many",incoming:"one",lifecycle:"supersedable",aliases:["parent_child","task"],compatibilityVersion:1,allowSelf:!1},{kind:"related",direction:"undirected",traversal:"association",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",aliases:["related_to"],compatibilityVersion:1,allowSelf:!1},{kind:"discovered_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"incident_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"implements",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"recurs_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,temporalOrder:"source_after_target",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"verifies",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"supersedes",direction:"directed",traversal:"semantic",outcomeTraversal:"both",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"supersedable",compatibilityVersion:1,allowSelf:!1}];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="418b3f7f-6350-5878-a362-3948de287baf")}catch{}})();function qn(e){return e.trim().toLowerCase().replaceAll("-","_")}function B_(e){if(e===void 0)return;let t=qn(e);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid inverse relationship kind: ${e}`);return t}function Hi(e,t=new Set){if(e===null||typeof e!="object"||t.has(e))return e;if(t.add(e),Array.isArray(e)){for(let r of e)Hi(r,t);return Object.freeze(e)}for(let r of Object.values(e))Hi(r,t);return Object.freeze(e)}function W_(e,t){if(e.precedence!==void 0&&e.precedence!=="source_before_target"&&e.precedence!=="target_before_source")throw new TypeError(`Invalid relationship precedence for ${t}`);if(!e.ordering&&e.precedence!==void 0)throw new TypeError(`Non-ordering relationship kind cannot declare precedence: ${t}`)}function G_(e,t){if(e.temporalOrder!==void 0&&e.temporalOrder!=="source_after_target")throw new TypeError(`Invalid relationship temporal order for ${t}`);if(e.direction!=="directed"&&e.temporalOrder!==void 0)throw new TypeError(`Undirected relationship kind cannot declare temporal order: ${t}`)}function K_(e,t){if(e.hierarchyDirection!==void 0&&e.hierarchyDirection!=="source_parent"&&e.hierarchyDirection!=="target_parent")throw new TypeError(`Invalid relationship hierarchy direction for ${t}`);if(!e.hierarchy&&e.hierarchyDirection!==void 0)throw new TypeError(`Non-hierarchy relationship kind cannot declare hierarchy direction: ${t}`)}function Y_(e){if(typeof e!="object"||e===null)throw new TypeError("Relationship kind definition requires an object");if(typeof e.kind!="string")throw new TypeError("Relationship kind requires a string identifier");let t=qn(e.kind);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid relationship kind: ${e.kind}`);if(!Number.isInteger(e.compatibilityVersion)||e.compatibilityVersion<1)throw new TypeError(`Invalid compatibility version for ${t}`);return t}function X_(e,t){if(!["directed","undirected"].includes(e.direction))throw new TypeError(`Invalid relationship direction for ${t}`);if(typeof e.ordering!="boolean")throw new TypeError(`Invalid relationship ordering flag for ${t}`);if(![void 0,!0,!1].includes(e.hierarchy))throw new TypeError(`Invalid relationship hierarchy flag for ${t}`);if(!["one","many"].includes(e.outgoing))throw new TypeError(`Invalid outgoing relationship cardinality for ${t}`);if(!["one","many"].includes(e.incoming))throw new TypeError(`Invalid incoming relationship cardinality for ${t}`);if(!["persistent","supersedable","ephemeral"].includes(e.lifecycle))throw new TypeError(`Invalid relationship lifecycle for ${t}`);if(typeof e.allowSelf!="boolean")throw new TypeError(`Invalid relationship self-edge flag for ${t}`);if(e.traversal!==void 0&&!["hierarchy","ordering","semantic","association"].includes(e.traversal))throw new TypeError(`Invalid relationship traversal family for ${t}`);if(e.outcomeTraversal!==void 0&&!["source_to_target","target_to_source","both"].includes(e.outcomeTraversal))throw new TypeError(`Invalid outcome traversal for ${t}`);if(e.direction==="undirected"&&e.outcomeTraversal!==void 0&&e.outcomeTraversal!=="both")throw new TypeError(`Undirected relationship kind cannot declare directional outcome traversal: ${t}`)}function J_(e,t){if(e.payloadSchema!==void 0&&(typeof e.payloadSchema!="object"||e.payloadSchema===null||Array.isArray(e.payloadSchema)))throw new TypeError(`Invalid relationship payload schema for ${t}`);if(e.aliases!==void 0&&(!Array.isArray(e.aliases)||e.aliases.some(r=>typeof r!="string")))throw new TypeError(`Invalid relationship aliases for ${t}`)}function Z_(e){return e.traversal?e.traversal:e.ordering?"ordering":e.hierarchy?"hierarchy":e.direction==="undirected"?"association":"semantic"}var qi=class{#e=new Map;#r=new Map;constructor(t=zi){for(let r of t)this.register(r)}register(t){let r=Y_(t);if(X_(t,r),J_(t,r),W_(t,r),G_(t,r),K_(t,r),this.#e.has(r)||this.#r.has(r))throw new TypeError(`Relationship kind already registered: ${r}`);let n=B_(t.inverse),o=[...new Set((t.aliases??[]).map(qn))].sort();for(let s of o){if(!/^[a-z][a-z0-9_]*$/.test(s))throw new TypeError(`Invalid relationship alias: ${s}`);if(s===r||this.#e.has(s)||this.#r.has(s))throw new TypeError(`Relationship alias already registered: ${s}`)}let i=Object.freeze({...t,kind:r,traversal:Z_(t),hierarchy:t.hierarchy??!1,hierarchyDirection:t.hierarchy?t.hierarchyDirection??"source_parent":void 0,inverse:n,aliases:Object.freeze(o),payloadSchema:t.payloadSchema?Hi(structuredClone(t.payloadSchema)):void 0});this.#e.set(r,i);for(let s of o)this.#r.set(s,r);return this}resolve(t){if(typeof t!="string")return;let r=qn(t);return this.#e.get(this.#r.get(r)??r)}require(t){let r=this.resolve(t);if(!r)throw new TypeError(`Unknown relationship kind: ${t}`);return r}list(){return Object.freeze([...this.#e.values()].sort((t,r)=>t.kind.localeCompare(r.kind)))}};function Vi(){return new qi}var pt=Vi();function mT(e){return pt.require(e).kind}function pT(e){return pt.resolve(e)?.kind}function _T(e,t=pt){return t.resolve(e)?.ordering===!0}function Q_(e,t,r,n=pt){let o=Pr(e),i=Pr(t);if(!o||!i)throw new TypeError("Relationship endpoint must not be empty");let s=n.require(r);if(o===i&&!s.allowSelf)throw new TypeError(`Self relationship is not allowed for ${s.kind}`);return s}function Un(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.kind.localeCompare(t.kind)}function ey(e,t,r){let n=typeof e.source=="string"?e.source.trim():"",o=typeof e.target=="string"?e.target.trim():"";if(!t.has(n)||!t.has(o))throw new TypeError(`Relationship endpoint not found: ${n} -> ${o}`);let i=Q_(n,o,e.kind,r),s=Object.freeze({...e,source:n,target:o,kind:i.kind}),a=i.direction==="undirected"?[n,o].sort().join("\0"):`${n}\0${o}`;return{edge:s,identity:`${i.kind}\0${a}`}}function Hn(e,t,r){let n=e.get(t);n?n.push(r):e.set(t,[r])}function Pr(e){return typeof e=="string"?e.trim():""}function Ui(e,t){let r=Pr(e);return r&&t.has(r)?r:void 0}function ty(e,t,r){let n=[t],o=t;for(;o!==e;)o=r.get(o),n.push(o);return n.reverse()}var nd=class e{#e;#r;#o;#n;#s=new Map;#a=new Map;constructor(t,r,n=pt){this.#e=n,this.#r=new Set([...t].filter(i=>typeof i=="string").map(i=>i.trim()).filter(Boolean)),this.#o=Object.freeze([...this.#r].sort());let o=new Map;for(let i of r){let{edge:s,identity:a}=ey(i,this.#r,n);o.set(a,s)}this.#n=Object.freeze([...o.values()].sort(Un));for(let i of this.#n)Hn(this.#s,i.source,i),Hn(this.#a,i.target,i),n.require(i.kind).direction==="undirected"&&(Hn(this.#s,i.target,i),Hn(this.#a,i.source,i))}static fromItems(t,r=pt){let n=new Set(t.map(i=>Pr(i.id)).filter(Boolean)),o=[];for(let i of t){let s=Pr(i.id);if(!s)continue;let a=Ui(i.parent,n);a&&o.push({source:s,target:a,kind:"parent"});let c=Ui(i.blocked_by,n);c&&o.push({source:s,target:c,kind:"blocked_by"});for(let d of i.dependencies??[]){let l=Ui(d.id,n);l&&r.resolve(d.kind)&&o.push({source:s,target:l,kind:d.kind,createdAt:d.created_at,author:d.author})}}return new e(n,o,r)}edges(){return this.#n}incidentEdges(t){this.#i(t);let r=this.#s.get(t)??[],n=this.#a.get(t)??[];if(r.length===0)return Object.freeze([...n]);if(n.length===0)return Object.freeze([...r]);let o=[],i=0,s=0;for(;i<r.length||s<n.length;){let a=r[i],c=n[s],d=a===void 0?c:c===void 0||Un(a,c)<=0?a:c;o.at(-1)!==d&&o.push(d),a===d&&(i+=1),c===d&&(s+=1)}return Object.freeze(o)}nodes(){return this.#o}hasNode(t){return this.#r.has(t)}registry(){return this.#e}#i(t){if(!this.#r.has(t))throw new TypeError(`Relationship node not found: ${t}`)}#c(t,r){if(!r)return!0;let n=this.#e.require(t.kind);return r.has(t.kind)||n.inverse!==void 0&&r.has(n.inverse)}#t(t,r,n){let o=[...r==="incoming"?[]:this.#s.get(t)??[],...r==="outgoing"?[]:this.#a.get(t)??[]];return[...new Set(o)].filter(i=>this.#c(i,n)).map(i=>({id:i.source===t?i.target:i.source,edge:i})).sort((i,s)=>i.id.localeCompare(s.id)||Un(i.edge,s.edge))}adjacency(t,r={}){this.#i(t),r.signal?.throwIfAborted();let n=r.kinds?new Set(r.kinds.map(c=>this.#e.require(c).kind)):void 0,o=this.#t(t,r.direction??"outgoing",n),i=r.limit??Number.POSITIVE_INFINITY,s=[...new Set(o.map(c=>c.id))],a=s.slice(0,i);return{value:a,meta:{visitedNodes:1,inspectedEdges:o.length,truncated:a.length<s.length,nextCursor:a.at(-1)}}}neighborEdges(t,r={}){this.#i(t),r.signal?.throwIfAborted();let n=r.kinds?new Set(r.kinds.map(a=>this.#e.require(a).kind)):void 0,o=this.#t(t,r.direction??"outgoing",n),i=r.limit??Number.POSITIVE_INFINITY,s=o.slice(0,i);return{value:s,meta:{visitedNodes:1,inspectedEdges:o.length,truncated:s.length<o.length,nextCursor:s.at(-1)?.id}}}closure(t,r={}){this.#i(t);let n=r.kinds?new Set(r.kinds.map(m=>this.#e.require(m).kind)):void 0,o=r.direction??"outgoing",i=r.limit??Number.POSITIVE_INFINITY,s=r.maxDepth??Number.POSITIVE_INFINITY,a=new Set([t]),c=[],d=[{id:t,depth:0}],l=0,u=0,f=!1;e:for(let m=0;m<d.length;m+=1){r.signal?.throwIfAborted();let _=d[m];l+=1;let y=this.#t(_.id,o,n);if(u+=y.length,_.depth>=s){y.some(w=>!a.has(w.id))&&(f=!0);continue}for(let w of y)if(!a.has(w.id)){if(c.length>=i){f=!0;break e}a.add(w.id),c.push(w.id),d.push({id:w.id,depth:_.depth+1})}}return{value:c,meta:{visitedNodes:l,inspectedEdges:u,truncated:f,nextCursor:c.at(-1)}}}shortestPath(t,r,n={}){if(this.#i(t),this.#i(r),t===r)return{value:[t],meta:{visitedNodes:1,inspectedEdges:0,truncated:!1}};let o=n.kinds?new Set(n.kinds.map(m=>this.#e.require(m).kind)):void 0,i=n.direction??"outgoing",s=n.maxDepth??Number.POSITIVE_INFINITY,a=[{id:t,depth:0}],c=new Map,d=new Set([t]),l=0,u=0,f=!1;for(let m=0;m<a.length;m+=1){n.signal?.throwIfAborted();let _=a[m];l+=1;let y=this.#t(_.id,i,o);if(u+=y.length,_.depth>=s){y.some(w=>!d.has(w.id))&&(f=!0);continue}for(let w of y)if(!d.has(w.id)){if(c.set(w.id,_.id),w.id===r)return{value:ty(t,r,c),meta:{visitedNodes:l,inspectedEdges:u,truncated:!1}};d.add(w.id),a.push({id:w.id,depth:_.depth+1})}}return{value:[],meta:{visitedNodes:l,inspectedEdges:u,truncated:f}}}subgraph(t,r={}){let n=this.closure(t,r),o=[t,...n.value].sort(),i=new Set(o),s=r.kinds?new Set(r.kinds.map(c=>this.#e.require(c).kind)):void 0,a=new Set;for(let c of o)for(let d of this.#s.get(c)??[])i.has(d.source)&&i.has(d.target)&&this.#c(d,s)&&a.add(d);return{value:{nodes:o,edges:[...a].sort(Un)},meta:n.meta}}};function yT(e,t,r=pt){return{source:e,target:t.id,kind:r.require(t.kind).kind,createdAt:t.created_at,author:t.author}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32aa20df-edf7-543d-b733-841130466f00")}catch{}})();var ry="__pm_suppress_host_output",Bi="@unbrained/pm-cli:suppress-host-output:v1";function od(e){return e===void 0?{__pm_suppress_host_output:Bi}:{__pm_suppress_host_output:Bi,result:e}}function Vn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[ry]===Bi}import Wt from"node:fs";import Ne from"node:path";import{fileURLToPath as ny}from"node:url";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="efea1aa1-1ad1-5f53-a3a5-b83803d9deb1")}catch{}})();var oy="@unbrained/pm-cli";function iy(e){try{return JSON.parse(Wt.readFileSync(e,"utf8")).name===oy}catch{return!1}}function sy(e){let t=Wt.existsSync(e)&&Wt.statSync(e).isDirectory()?Ne.resolve(e):Ne.dirname(Ne.resolve(e));for(;;){let r=Ne.join(t,"package.json");if(Wt.existsSync(r)&&iy(r))return t;let n=Ne.dirname(t);if(n===t)return;t=n}}function Bn(e,t=[]){let r=ny(e);return sy(r)||Ne.resolve(Ne.dirname(r),...t)}function ET(e,t=[]){try{let r=Ne.join(Bn(e,t),"package.json");if(!Wt.existsSync(r))return;let n=JSON.parse(Wt.readFileSync(r,"utf8"));return typeof n.version=="string"&&n.version.trim().length>0?n.version:void 0}catch{return}}function kT(e=process.env,t="PM_CLI_PACKAGE_ROOT",r,n=[]){let o=e[t];return typeof o=="string"&&o.trim().length>0?Ne.resolve(o.trim()):r?Bn(r,n):process.cwd()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a797572f-fbc6-5e62-a9b5-5a0bd6ef22b4")}catch{}})();function ay(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function OT(e){return ay(e)??void 0}function AT(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return t===e.length?e:e.slice(0,t)}function IT(e){return Array.isArray(e)&&e.every(t=>typeof t=="number"&&Number.isFinite(t))}function sd(e){if(e instanceof Error){let t=e.message.trim();return t.length>0?t:e.name}return String(e)}function Wn(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;return Number.isFinite(t)?t:null}function TT(e){let t=Wn(e);return t===null||t<=0||!Number.isInteger(t)?null:t}function CT(e,t,r){let n=Wn(e);return n===null||n<t||n>r?null:n}function RT(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}function ze(e){return typeof e!="object"||e===null?null:e}function id(e){return typeof e!="object"&&typeof e!="function"||e===null?null:e}function ad(e){let t=id(e);if(!t)return null;if(typeof t.activate=="function")return t;let r=id(t.default);return typeof r?.activate=="function"?r:null}function xT(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?{...e}:{}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c05a5a9e-282c-5ca7-97dc-e48c8df7977e")}catch{}})();var cy=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],cd=cy,Gt=["draft","open","in_progress","blocked","closed","canceled"],Gn=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],Kt=["string","number","boolean","string_array","array","object"],Kn=["create","update","update_many","list","search","calendar","context"],Yn=["allow","warn","reject"],DT=["blocks","parent","child","parent_child","child_of","related","related_to","discovered_from","blocked_by","incident_from","epic","implements","recurs_from","supersedes","task","verifies"],PT=["project","global"],MT=["low","medium","high","critical"],Xn=["low","medium","high","critical"],Jn=["low","medium","high"];var dd=["minimal","default","strict","custom"],$T=["none","warn","strict"],jT=["progressive","strict"],LT=["off","warn","strict"],FT=["off","warn","strict"];var Zn=["daily","weekly","monthly","yearly"],Mr=["mon","tue","wed","thu","fri","sat","sun"];function Wi(e){return Mr.indexOf(e)}var zT=["draft","research","review","approved","executing","paused","completed","superseded"],ld=["pending","in_progress","completed","blocked","skipped","superseded"],UT=["codex","claude-code","cursor","generic"],HT=["related","blocks","blocked_by","depends_on","discovered_from","implements","recurs_from","verifies","supersedes"],qT=["brief","standard","deep","full"],VT=["hierarchy","activity","progress","recently_created","unparented","blockers","files","workload","staleness","tests"];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0ca7f52c-fb31-5cd9-b689-a918f4e61816")}catch{}})();import my from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="75f74db3-9547-5c78-8561-f371c016b90d")}catch{}})();function Ue(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}function dy(e){let t=e.key.trim();if(t.length===0)return null;let r=Ue(e.aliases),n=e.description?.trim();return{key:t,values:Ue(e.values),required:e.required===!0?!0:void 0,aliases:r.length>0?r:void 0,description:n&&n.length>0?n:void 0}}var ly=e=>e,fd=e=>{let t=e.trim().toLowerCase();return t==="create"||t==="update"?t:null};function uy(e,t){let r=t(e.command);if(r===null)return null;let n=e.option.trim();return n.length===0?null:{command:r,option:n,required:e.required,visible:e.visible,enabled:e.enabled}}function fy(e,t){let r=new Map;for(let n of e??[]){let o=uy(n,t);o&&r.set(`${o.command}:${o.option.toLowerCase()}`,o)}return[...r.values()].sort((n,o)=>n.command===o.command?n.option.localeCompare(o.option):n.command.localeCompare(o.command))}function ud(e,t){return t?Ue(e):void 0}function Gi(e){let t=e?.trim();return t&&t.length>0?t:void 0}function Ki(e){if(e===void 0||e==="agent"||e==="human"||e==="gate")return e;throw new Error("Item type execution_role must be agent, human, or gate.")}function Qn(e,t={}){let r=t.resolvePolicyCommand??ly,n=e.name.trim();if(n.length===0)return null;let o=e.required_create_fields!==void 0,i=e.required_create_repeatables!==void 0,s=e.options!==void 0,a=e.command_option_policies!==void 0,c=Ue(e.aliases),d=(e.options??[]).map(u=>dy(u)).filter(u=>u!==null).sort((u,f)=>u.key.localeCompare(f.key)),l=fy(e.command_option_policies,r);return{name:n,description:Gi(e.description),default_status:Gi(e.default_status),...e.execution_role===void 0?{}:{execution_role:Ki(e.execution_role)},folder:Gi(e.folder),aliases:c.length>0?c:void 0,required_create_fields:ud(e.required_create_fields,o),required_create_repeatables:ud(e.required_create_repeatables,i),options:s?d:void 0,command_option_policies:a?l:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f40ddc8e-1dd5-5f26-b2ba-fbbac30a1781")}catch{}})();var py=Object.freeze({decision:"human",milestone:"gate"}),_y=["title","description","status","priority","tags","body","deadline","estimatedMinutes","acceptanceCriteria","author","message","assignee"],yy=["dep","comment","note","learning","file","test","doc"],pd=["deadline","estimatedMinutes","acceptanceCriteria","definitionOfReady","order","goal","objective","value","impact","outcome","whyNow","assignee","parent","reviewer","risk","confidence","sprint","release","blockedBy","blockedReason","unblockNote","reporter","severity","environment","reproSteps","resolution","expectedResult","actualResult","affectedVersion","fixedVersion","component","regression","customerImpact"],hy=["title","description","type","status","priority","tags","body",...pd,"author","message","dep","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],gy=["title","description","body","status","closeReason","priority","type","tags",...pd,"author","message","comment","note","learning","file","test","doc","reminder","event","typeOption","field","ownershipMetadataBypass","ownershipDependencyBypass","force"],_d={"close-reason":"closeReason",close_reason:"closeReason","estimated-minutes":"estimatedMinutes",estimated_minutes:"estimatedMinutes",estimate:"estimatedMinutes","acceptance-criteria":"acceptanceCriteria",acceptance_criteria:"acceptanceCriteria",ac:"acceptanceCriteria","definition-of-ready":"definitionOfReady",definition_of_ready:"definitionOfReady",rank:"order","why-now":"whyNow",why_now:"whyNow","blocked-by":"blockedBy",blocked_by:"blockedBy","blocked-reason":"blockedReason",blocked_reason:"blockedReason","unblock-note":"unblockNote",unblock_note:"unblockNote","repro-steps":"reproSteps",repro_steps:"reproSteps","expected-result":"expectedResult",expected_result:"expectedResult","actual-result":"actualResult",actual_result:"actualResult","affected-version":"affectedVersion",affected_version:"affectedVersion","fixed-version":"fixedVersion",fixed_version:"fixedVersion","customer-impact":"customerImpact",customer_impact:"customerImpact","type-option":"typeOption",type_option:"typeOption",type_options:"typeOption"},by={..._d},wy={..._d},yd=[["deadline","--deadline"],["estimatedMinutes","--estimate/--estimated-minutes"],["acceptanceCriteria","--acceptance-criteria/--ac"],["definitionOfReady","--definition-of-ready"],["order","--order/--rank"],["goal","--goal"],["objective","--objective"],["value","--value"],["impact","--impact"],["outcome","--outcome"],["whyNow","--why-now"],["assignee","--assignee"],["parent","--parent"],["reviewer","--reviewer"],["risk","--risk"],["confidence","--confidence"],["sprint","--sprint"],["release","--release"],["blockedBy","--blocked-by"],["blockedReason","--blocked-reason"],["unblockNote","--unblock-note"],["reporter","--reporter"],["severity","--severity"],["environment","--environment"],["reproSteps","--repro-steps"],["resolution","--resolution"],["expectedResult","--expected-result"],["actualResult","--actual-result"],["affectedVersion","--affected-version"],["fixedVersion","--fixed-version"],["component","--component"],["regression","--regression"],["customerImpact","--customer-impact"]],hd=[["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"]];function gd(e){return Object.fromEntries(e)}var vy=gd([["title","--title"],["description","--description"],["type","--type"],["status","--status"],["priority","--priority"],["tags","--tags"],["body","--body"],...yd,["author","--author"],["message","--message"],["dep","--dep"],...hd]),Ey=gd([["title","--title"],["description","--description"],["body","--body"],["status","--status"],["closeReason","--close-reason"],["priority","--priority"],["type","--type"],["tags","--tags"],...yd,...hd,["author","--author"],["message","--message"],["force","--force"]]);function ky(e){return e.trim().replace(/^--+/,"").toLowerCase()}function Sy(e){return e==="create"?hy:gy}function Oy(e){return e==="create"?by:wy}function bd(e,t){let r=ky(t);return r.length===0?void 0:Oy(e)[r]||Sy(e).find(n=>n.toLowerCase()===r)}function QT(e,t){return(e==="create"?vy:Ey)[t]??`--${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}function Xi(e){let t=Iy(e);return t.length===0?"items":t.endsWith("s")?t:`${t}s`}function Ay(e){let t=e.trim(),r=t.replaceAll("\\","/").replace(/^\/+/,""),n=my.posix.normalize(r);if(t.includes("\0")||/^[A-Za-z]:/.test(n)||n==="."||n===".."||n.startsWith("../"))throw new Error(`Item type folder "${e}" must stay inside the pm tracker root.`);return n}function Iy(e){let t=e.trim().toLowerCase(),r="",n=!1;for(let o of t){let i=o.charCodeAt(0),s=i>=97&&i<=122,a=i>=48&&i<=57;if(s||a){n&&r.length>0&&(r+="-"),r+=o,n=!1;continue}r.length>0&&(n=!0)}return r}function Ty(e){return Qn(e,{resolvePolicyCommand:fd})}function $r(e,t){let r=e[t];return Array.isArray(r)?r.filter(n=>typeof n=="string"):void 0}function Cy(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;return typeof t.key!="string"?null:{key:t.key,values:$r(t,"values")??[],required:t.required===void 0?void 0:!!t.required,aliases:$r(t,"aliases"),description:typeof t.description=="string"?t.description:void 0}}function Ry(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;if(typeof t.command!="string"||typeof t.option!="string")return null;let r=t.command.trim().toLowerCase();return r!=="create"&&r!=="update"?null:{command:r,option:t.option,required:t.required===void 0?void 0:!!t.required,visible:t.visible===void 0?void 0:!!t.visible,enabled:t.enabled===void 0?void 0:!!t.enabled}}function xy(e){if(Array.isArray(e.options))return e.options.map(t=>Cy(t)).filter(t=>t!==null)}function Ny(e){if(Array.isArray(e.command_option_policies))return e.command_option_policies.map(t=>Ry(t)).filter(t=>t!==null)}function Dy(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e,r=typeof t.name=="string"?t.name:"";if(r.trim().length===0)return null;let n=typeof t.folder=="string"?t.folder:void 0,o=typeof t.description=="string"?t.description:void 0,i=typeof t.default_status=="string"?t.default_status:void 0;return{name:r,description:o,default_status:i,execution_role:Ki(t.execution_role),folder:n,aliases:$r(t,"aliases"),required_create_fields:$r(t,"required_create_fields"),required_create_repeatables:$r(t,"required_create_repeatables"),options:xy(t),command_option_policies:Ny(t)}}function Py(e,t){return e.required_create_fields?Ue(e.required_create_fields):t?.required_create_fields??[]}function My(e,t){return e.required_create_repeatables?Ue(e.required_create_repeatables):t?.required_create_repeatables??[]}function $y(e,t){return e.options?e.options:t?.options?[...t.options]:[]}function jy(e,t){return e.command_option_policies?e.command_option_policies:t?.command_option_policies?[...t.command_option_policies]:[]}function Ly(e,t){let r=t?.name??e.name,n=e.description??t?.description,o=e.default_status??t?.default_status,i=Ay(e.folder??t?.folder??Xi(r)),s={name:r,execution_role:e.execution_role,folder:i,aliases:Ue([...t?.aliases??[],...e.aliases??[]]),required_create_fields:Py(e,t),required_create_repeatables:My(e,t),options:$y(e,t),command_option_policies:jy(e,t)};return n&&(s.description=n),o&&(s.default_status=o),s}function md(e,t){for(let r of e){let n=Ty(r);if(!n)continue;let o=n.name.toLowerCase(),i=t.get(o);t.set(o,Ly({...n,execution_role:n.execution_role??i?.execution_role},i))}}function Fy(e){if(!e)return[];let t=[];for(let r of e.item_types??[]){let n=r.types;if(Array.isArray(n))for(let o of n){let i=Dy(o);i&&t.push(i)}}return t}function eC(e,t=null){let r=new Map;for(let c of cd)r.set(c.toLowerCase(),{name:c,execution_role:py[c.toLowerCase()]??"agent",folder:xr[c],aliases:[],required_create_fields:[..._y],required_create_repeatables:[...yy],options:[],command_option_policies:[]});md(e.item_types?.definitions??[],r),md(Fy(t),r);let n=[...r.values()].sort((c,d)=>c.name.localeCompare(d.name)),o={},i={},s={};for(let c of n){o[c.name]=c,s[c.name]=c.folder,i[c.name.toLowerCase()]=c.name;for(let d of c.aliases)i[d.toLowerCase()]=c.name}let a=[...new Set(n.map(c=>c.folder))].sort((c,d)=>c.localeCompare(d));return{types:n.map(c=>c.name),folders:a,type_to_folder:s,by_type:o,alias_to_type:i}}function zy(e,t){if(e!==void 0)return t.alias_to_type[e.trim().toLowerCase()]}function Uy(e,t){let r=zy(e,t);if(r)return t.by_type[r]}function Hy(e,t,r,n){for(let o of n){let i=bd(r,o);if(i){e.required.add(i);continue}e.errors.push(`Unsupported base required option "${o}" for command "${r}" on type "${t.name}"`)}}function Yi(e,t,r){if(r){e.add(t);return}e.delete(t)}function qy(e,t,r,n){let o=bd(r,n.option);if(!o){e.errors.push(`Unsupported command_option_policies option "${n.option}" for command "${r}" on type "${t.name}"`);return}n.required!==void 0&&Yi(e.required,o,n.required),n.visible!==void 0&&Yi(e.hidden,o,!n.visible),n.enabled!==void 0&&Yi(e.disabled,o,!n.enabled)}function Vy(e,t,r){for(let n of t.command_option_policies)n.command===r&&qy(e,t,r,n)}function By(e,t,r){for(let n of e.required)e.disabled.has(n)&&e.errors.push(`Option "${n}" cannot be both required and disabled for command "${r}" on type "${t.name}"`)}function tC(e,t,r){let n=[],o=new Set,i=new Set,s=new Set,a={required:o,hidden:i,disabled:s,errors:n};return Hy(a,e,t,r),Vy(a,e,t),By(a,e,t),{required:[...o],hidden:[...i].sort((c,d)=>c.localeCompare(d)),disabled:[...s].sort((c,d)=>c.localeCompare(d)),errors:n}}function Wy(e){let t=new Map;for(let r of e.options){t.set(r.key.toLowerCase(),r);for(let n of r.aliases??[])t.set(n.toLowerCase(),r)}return t}function Gy(e,t,r){let n=e.values;if(n.length===0)return t;let o=new Map(n.map(i=>[i.toLowerCase(),i])).get(t.toLowerCase());if(!o){r.push(`Invalid value "${t}" for type option "${e.key}". Allowed: ${n.join(", ")}`);return}return o}function rC(e,t,r){let n=Uy(e,r);if(!n)return{normalized:void 0,errors:[`Unknown type "${e}"`]};let o=[],i=Wy(n),s={};for(let[c,d]of Object.entries(t??{})){let l=c.trim(),u=d.trim();if(l.length===0){o.push("type option keys must not be empty");continue}if(u.length===0){o.push(`type option "${l}" must not be empty`);continue}let f=i.get(l.toLowerCase());if(!f){let _=n.options.map(y=>y.key).join(", ");o.push(n.options.length>0?`Unknown type option "${l}" for type "${n.name}". Allowed: ${_}`:`Type "${n.name}" does not define any configurable type options`);continue}let m=Gy(f,u,o);m!==void 0&&(s[f.key]=m)}for(let c of n.options)c.required&&!(c.key in s)&&o.push(`Missing required type option "${c.key}" for type "${n.name}"`);let a=Object.keys(s).sort((c,d)=>c.localeCompare(d));return a.length===0?{normalized:void 0,errors:o}:{normalized:Object.fromEntries(a.map(c=>[c,s[c]])),errors:o}}import{readFileSync as Ky,readdirSync as Yy,realpathSync as wd,statSync as vd}from"node:fs";import Xy from"node:os";import C from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7f4b8abe-997c-549c-9791-87c78506c8b5")}catch{}})();var Jy={json_markdown:".md",toon:".toon"},Zy={".md":"json_markdown",".toon":"toon"},Qy=new Set([".git","coverage","dist","node_modules"]),uC=[".md",".toon"];function jr(e){try{return vd(e),!0}catch{return!1}}function eh(e){let t=C.resolve(e),r=[];for(;C.dirname(t)!==t;)try{return C.join(wd(t),...r)}catch(n){if(!Se(n))throw n;r.unshift(C.basename(t)),t=C.dirname(t)}return C.join(wd(t),...r)}function th(e){try{return vd(e),!0}catch(t){if(Se(t))return!1;throw t}}function Ed(e){try{let t=JSON.parse(Ky(e,"utf8"));return typeof t!="object"||t===null||Array.isArray(t)?!1:"id_prefix"in t||"item_format"in t}catch{return!1}}function rh(e){let t=eh(e);for(;;){let r=C.join(t,Ln),n=C.join(r,Fn);if(jr(n))return r;let o=C.join(t,Fn);if(jr(o)&&Ed(o))return t;if(th(C.join(t,".git")))return r;let i=C.dirname(t);if(i===t)return;t=i}}function nh(e){return rh(e)??C.resolve(e,Ln)}function fC(e,t){let r=t?C.resolve(t):void 0;try{return Yy(C.resolve(e),{withFileTypes:!0}).filter(n=>n.isDirectory()&&!Qy.has(n.name)).map(n=>C.join(C.resolve(e),n.name)).filter(n=>n!==r).filter(n=>jr(Oe(n))).filter(n=>Ed(Oe(n))).sort((n,o)=>n.localeCompare(o))[0]}catch{return}}function mC(e,t){let r=process.env.PM_PATH,n=t?.trim()||r?.trim();if(n){let o=C.resolve(e,n);if(!jr(Oe(o))){let i=C.join(o,Ln);if(jr(Oe(i)))return i}return o}return nh(e)}function pC(e){let t=C.resolve(e),r=C.dirname(t);return C.basename(t)==="pm"&&C.basename(r)===".agents"?C.dirname(r):t}function kd(e){let t=process.env.PM_GLOBAL_PATH?.trim(),r=t&&t.length>0?t:C.join(Xy.homedir(),".pm-cli");return C.resolve(e,r)}function Oe(e){return C.join(e,Fn)}function oh(e,t,r=xr){let n=r[t]??Xi(t);return C.join(e,n)}function _C(e,t,r,n="toon",o=xr){return C.join(oh(e,t,o),`${r}${Jy[n]}`)}function yC(e){let t=e.replaceAll("\\","/"),r=C.posix.extname(t).toLowerCase();return Zy[r]??null}function hC(e,t){if(!/^(?!\.{1,2}$)[^/\\:\0]+$/.test(t))throw new g("Invalid history item id: expected a single filename.",h.USAGE);return C.join(e,"history",`${t}.jsonl`)}function Ji(e,t){return C.join(e,"locks",`${t}.lock`)}function Zi(e){return C.join(e,"runtime")}function eo(e){return C.join(Zi(e),"test-runs")}function ih(e){return C.join(eo(e),"runs")}function gC(e,t){return C.join(ih(e),`${t}.json`)}function sh(e){return C.join(eo(e),"stdout")}function ah(e){return C.join(eo(e),"stderr")}function bC(e,t){return C.join(sh(e),`${t}.log`)}function wC(e,t){return C.join(ah(e),`${t}.log`)}function ch(e){return C.join(eo(e),"results")}function vC(e,t){return C.join(ch(e),`${t}.json`)}import dh from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="77f9d61e-e78b-5b6a-a769-1ad6e5b91777")}catch{}})();function lh(e){if(e===null)return null;if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="bigint")return e.toString();if(e===void 0)return"undefined";if(typeof e=="symbol")return e.toString();if(typeof e=="function")return`[function:${e.name||"anonymous"}]`}function uh(e){let t=Object.keys(e).sort(),r={};for(let n of t){let o=e[n];o!==void 0&&(r[n]=to(o))}return r}function to(e){let t=lh(e);if(t!==void 0)return t;if(Array.isArray(e))return e.map(n=>to(n));if(e instanceof Date)return e.toISOString();let r=e;if(typeof r.toJSON=="function"){let n=r.toJSON();if(n!==e)return to(n)}return uh(e)}function R(e){return JSON.stringify(to(e))}function Sd(e,t,r,n){for(let o=0;o<t.length;o+=1)if(!r.has(o)&&n(e,t[o]))return r.add(o),!0;return!1}function fh(e,t){if(e instanceof RegExp||t instanceof RegExp)return e instanceof RegExp&&t instanceof RegExp&&e.toString()===t.toString()}function mh(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime()}function ph(e,t){if(!(e instanceof Set||t instanceof Set))return;if(!(e instanceof Set&&t instanceof Set)||e.size!==t.size)return!1;let r=[...t],n=new Set;for(let o of e)if(!Sd(o,r,n,W))return!1;return!0}function _h(e,t){if(!(e instanceof Map||t instanceof Map))return;if(!(e instanceof Map&&t instanceof Map)||e.size!==t.size)return!1;let r=[...t.entries()],n=new Set;for(let[o,i]of e.entries())if(!Sd([o,i],r,n,([s,a],[c,d])=>W(s,c)&&W(a,d)))return!1;return!0}function yh(e,t){if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((r,n)=>W(r,t[n]))}function hh(e,t){let r=Object.keys(e).sort((o,i)=>o.localeCompare(i)),n=Object.keys(t).sort((o,i)=>o.localeCompare(i));if(r.length!==n.length)return!1;for(let o=0;o<r.length;o+=1){let i=r[o];if(i!==n[o]||!W(e[i],t[i]))return!1}return!0}var gh=[fh,mh,ph,_h,yh];function W(e,t){if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;for(let r of gh){let n=r(e,t);if(n!==void 0)return n}return hh(e,t)}function ro(e){return dh.createHash("sha256").update(e,"utf8").digest("hex")}function A(e,t){let r={};for(let o of t){let i=e[o];i!==void 0&&(r[o]=i)}let n=Object.keys(e).filter(o=>!t.includes(o)).sort((o,i)=>o.localeCompare(i));for(let o of n){let i=e[o];i!==void 0&&(r[o]=i)}return r}import{createHash as Ad}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f675993f-c483-5751-baed-d968b4fd24c0")}catch{}})();var bh=["policies","policy-put","policy-remove","policy-mode","policy-check","policy-approve","policy-presets"],Od=256,Qi=64;function ce(e){throw new g(`Invalid workflow policy: ${e}`,h.USAGE,{code:"workflow_policy_invalid",nextSteps:["Inspect pm schema policies and correct the declaration using pm schema policy-put."]})}function De(e,t,r){if(typeof e!="object"||e===null||Array.isArray(e))return ce(`${r} must be an object`);let n=e;return Object.keys(n).some(o=>!t.includes(o))?ce(`${r} contains an unknown key`):n}function _t(e,t,r=128){return typeof e!="string"||!e.trim()||e.length>r?ce(`${t} must be nonempty text of at most ${r} characters`):e.trim()}function Lr(e,t){if(!Array.isArray(e)||e.length===0||e.length>Qi)return ce(`${t} requires 1-${Qi} terms`);let r=e.map(n=>_t(n,t));return t==="fields"&&r.some(n=>!/^[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$/.test(n)||n.split(".").some(o=>["__proto__","constructor","prototype"].includes(o)))?ce("fields must be safe metadata paths of at most eight segments"):[...new Set(r)]}function wh(e){let t=De(e,["kind","fields","authors","allowed"],"rule");return t.kind==="transition"?(De(t,["kind","allowed"],"transition rule"),!Array.isArray(t.allowed)||t.allowed.length>Qi?ce("transition.allowed must be a bounded array"):{kind:"transition",allowed:t.allowed.map(r=>!Array.isArray(r)||r.length!==2?ce("transition pairs need two statuses"):[_t(r[0],"from"),_t(r[1],"to")])}):t.kind==="authors"?(De(t,["kind","authors"],"authors rule"),{kind:"authors",authors:Lr(t.authors,"authors")}):t.kind==="require_fields"?(De(t,["kind","fields"],"require_fields rule"),{kind:"require_fields",fields:Lr(t.fields,"fields")}):t.kind==="field_writers"||t.kind==="approval"?(De(t,["kind","fields","authors"],"field rule"),{kind:t.kind,fields:Lr(t.fields,"fields"),authors:Lr(t.authors,"authors")}):ce("unknown rule kind")}function vh(e){let t={},r=De(e,["types","tags","statuses","operations","parents","dependency"],"subject");for(let n of["types","tags","statuses","operations","parents"])r[n]!==void 0&&(t[n]=Lr(r[n],n));if(r.dependency!==void 0){let n=De(r.dependency,["kind","id"],"dependency");t.dependency={kind:_t(n.kind,"dependency kind"),...n.id===void 0?{}:{id:_t(n.id,"dependency id")}}}return t}function Eh(e){let t=De(e,["id","description","subject","effect","rule"],"policy"),r=_t(t.id,"id");return/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(r)?t.effect!==void 0&&(typeof t.effect!="string"||!["advise","warn","refuse"].includes(t.effect))?ce("effect must be advise, warn, or refuse"):{id:r,rule:wh(t.rule),...t.subject===void 0?{}:{subject:vh(t.subject)},...t.description===void 0?{}:{description:_t(t.description,"description",500)},...t.effect===void 0?{}:{effect:t.effect}}:ce("id must be a stable token")}function kh(e){let t=De(e,["version","enforcement","policies"],"document");if(t.version!==1)return ce("unsupported version");if(t.enforcement!==void 0&&t.enforcement!=="advise"&&t.enforcement!=="refuse")return ce("enforcement must be advise or refuse");if(!Array.isArray(t.policies)||t.policies.length>Od)return ce(`policies must contain at most ${Od} declarations`);let r=t.policies.map(Eh);return new Set(r.map(n=>n.id)).size!==r.length?ce("duplicate policy id"):{version:1,enforcement:t.enforcement??"advise",policies:r}}function no(e,t){let r=e;for(let n of t.split(".")){if(typeof r!="object"||r===null||!Object.hasOwn(r,n))return;r=r[n]}return r}function Sh(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function Id(e){return Ad("sha256").update(R(e)).digest("hex")}function Oh(e,t){let r=e.rule.kind==="approval"?e.rule.fields:[];return Ad("sha256").update(R({id:t.id,fields:r.map(n=>[n,no(t,n)])})).digest("hex")}function Ah(e,t){return Array.isArray(t)&&t.some(r=>typeof r=="object"&&r!==null&&"kind"in r&&r.kind===e.kind&&(e.id===void 0||"id"in r&&r.id===e.id))}function Ih(e,t,r){return!(e.types&&!e.types.some(n=>n.toLowerCase()===String(t.type).toLowerCase())||e.statuses&&!e.statuses.includes(String(t.status))||e.operations&&!e.operations.includes(r)||e.parents&&!e.parents.includes(String(t.parent))||e.tags&&(!Array.isArray(t.tags)||!e.tags.some(n=>t.tags.includes(n)))||e.dependency&&!Ah(e.dependency,t.dependencies))}function Th(e,t){if(t.completeness_only&&(e.rule.kind!=="require_fields"||e.subject?.operations!==void 0)||e.rule.kind==="approval"&&t.before===null)return!1;let r=e.subject??{},n=t.after?.status??t.before?.status;return[t.before,t.after].some(o=>o!==null&&Ih(r,{...o,status:n},t.operation))}function Ch(e,t,r,n){let o=["type","tags","parent","dependencies"].some(i=>!W(t.before?.[i],t.after?.[i]));return t.after&&(t.completeness_only||r||n||o)?e.filter(i=>!Sh(no(t.after,i))):[]}function Rh(e,t,r,n){let o=t.after??t.before,i=Oh(e,o);return t.approvals?.some(s=>s.policy_fingerprint===n&&s.content_fingerprint===i&&s.author!==t.author&&r.includes(s.author))??!1}function xh(e,t,r){let n=e.rule,o=t.before?.status!==t.after?.status,i="fields"in n&&n.fields.some(s=>!W(no(t.before,s),no(t.after,s)));switch(n.kind){case"require_fields":{let s=Ch(n.fields,t,o,i);return{satisfied:s.length===0,missing_fields:s,remediation:"Supply the declared required fields before this lifecycle transition."}}case"transition":return{satisfied:!o||n.allowed.some(([s,a])=>s===String(t.before?.status??"$create")&&a===String(t.after?.status??"$delete")),missing_fields:[],remediation:"Choose a declared allowed transition; inspect pm schema policies."};case"authors":return{satisfied:n.authors.includes(t.author),missing_fields:[],remediation:"Have a declared workflow actor perform this operation."};case"field_writers":return{satisfied:!i||n.authors.includes(t.author),missing_fields:[],remediation:"Have a declared field writer change the protected fields."};case"approval":return{satisfied:!o||Rh(e,t,n.authors,r),missing_fields:[],remediation:`Record an independent approval with pm schema policy-approve <item-id> --policy ${e.id} after preparing the reviewed fields.`}}}function Td(e,t,r){let n=e.policies.filter(o=>Th(o,t)).map(o=>{let i=o.effect??"advise",s=r(o);return{policy_id:o.id,policy_fingerprint:s,rule:o.rule.kind,effect:i==="refuse"&&e.enforcement!=="refuse"?"warn":i,...xh(o,t,s)}});return{allowed:!n.some(o=>!o.satisfied&&o.effect==="refuse"),decisions:n,warnings:n.filter(o=>!o.satisfied).map(o=>`workflow_policy:${o.effect}:${o.policy_id}:${o.rule}`)}}function CC(e,t){return Td(e,t,Id)}function RC(e){let t=kh(e),r=new Map(t.policies.map(n=>[n,Id(n)]));return n=>Td(t,n,o=>r.get(o))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="432226a6-9df4-5de6-b9af-5c06ec2eed66")}catch{}})();var Nh=[...xe],Dh=[...Bt],Ph=[...Pn],MC=[...Mn],$C=[...$n],Mh=[...jn],oo=["init","config","extension","package","packages","install","upgrade","create","item","copy","focus","list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","aggregate","context","ctx","get","graph","search","duplicates","eval","next","history","events","history-redact","history-repair","history-compact","history-attest","history-author-acknowledge","merge","schema","profile","activity","restore","update","update-many","close","close-many","delete","append","comments","notes","learnings","files","docs","deps","plan","test","test-all","telemetry","stats","health","validate","assurance","gc","workspace","contracts","claim","release","start-task","pause-task","close-task","meet","event","remind","help"],jC=["ancestors","descendants","predecessors","successors","paths","impact","analyze","audit","communities","redundancy","dominators","slack","centrality","articulation","plan","index"],LC=["install","reconcile","report","driver"],$h=["init","install","uninstall","explore","manage","describe","reload","doctor","catalog","adopt","adopt-all","activate","deactivate"],jh=["upgrade"],Lh=["reopen"],Cd={help:"Commander help rendering has no SDK operation result.",packages:"The plural package alias only renders package-oriented help."},Yt=Object.freeze(oo.flatMap(e=>e in Cd?[]:e==="extension"||e==="package"?[...$h.map(t=>`${e}-${t}`),...e==="package"?jh.map(t=>`package-${t}`):[],e]:e==="item"?Lh.map(t=>`item-${t}`):[e])),Fh=Object.freeze(zn.filter(e=>e.lifecycle==="deprecated"&&e.registration==="commander"&&Yt.includes(e.alias)).map(e=>e.alias)),FC=Object.freeze(Yt.filter(e=>!Fh.includes(e)));function zC(e=oo,t=Yt,r=Cd){let n=new Set(t),o=new Set(e);return{missing_cli_actions:e.filter(i=>!n.has(i)&&!t.some(s=>s.startsWith(`${i}-`))&&r[i]===void 0),waived_cli_actions:e.filter(i=>!n.has(i)&&!t.some(s=>s.startsWith(`${i}-`))&&r[i]!==void 0),stale_waivers:Object.keys(r).filter(i=>!o.has(i)||n.has(i)||t.some(s=>s.startsWith(`${i}-`)))}}function UC(e){return Yt.includes(e)}function HC(e){return Nh.includes(e)}function qC(e){return Dh.includes(e)}function VC(e){return Ph.includes(e)}function BC(e){return Mh.includes(e)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="53865a81-4c96-51e2-a378-ae0e2781a50f")}catch{}})();var io={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"},so=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]),Xt=["list","context","search","get","next","health","deps","graph","history","activity","validate","events","contracts","comments","notes","files","docs","stats","aggregate","duplicates","package-catalog","package-manage","comments-audit","assurance"];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f8657910-1392-5fae-afda-614b96dc8320")}catch{}})();function F(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function zh(){return{json:!1,quiet:!1,noExtensions:!1,profile:!1}}function pe(e){return e?D(e):{}}function _e(e){return e?D(e):zh()}function D(e){return structuredClone(e)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="615b4955-a30d-5d45-a86d-4bcf7bd9bd7a")}catch{}})();var Uh=new Set(["commands","command_overrides","command_handlers","flag_commands","parser_overrides"]),Hh=["commands","command_overrides","command_handlers","hooks","flag_commands","item_types","item_fields","relationship_kinds","migrations","profiles","importers","exporters","search_providers","vector_store_adapters","assurance_providers","parser_overrides","service_overrides","renderer_overrides"];function qh(e,t){for(let r of Hh){let n=e[r];if(n===void 0)continue;if(!Array.isArray(n)||n.some(i=>typeof i!="string"))return!1;let o=n.map(i=>Uh.has(r)?F(i):i.trim()).filter(i=>i.length>0);t[r]=[...new Set(o)].sort((i,s)=>i.localeCompare(s))}return!0}function Vh(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="object"||r===null)return null;let n=r;if(n.format!=="json"&&n.format!=="toon"||!Array.isArray(n.commands)||n.commands.some(o=>typeof o!="string")||typeof n.result_discriminator!="boolean")return null;t.push({format:n.format,commands:[...new Set(n.commands.map(o=>F(o)))].sort((o,i)=>o.localeCompare(i)),result_discriminator:n.result_discriminator})}return t.sort((r,n)=>r.format.localeCompare(n.format))}function Bh(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="object"||r===null)return null;let n=r.commands;if(!Array.isArray(n)||n.some(o=>typeof o!="string"))return null;t.push({commands:[...new Set(n.map(o=>F(o)))].filter(o=>o.length>0).sort((o,i)=>o.localeCompare(i))})}return t}function ao(e){if(e==null)return;if(typeof e!="object"||Array.isArray(e))return null;let t=e;if(t.schema_version!==1)return null;let r={schema_version:1};if(!qh(t,r))return null;let n=t.preflight_overrides;if(n!==void 0&&(!Number.isInteger(n)||n<0))return null;typeof n=="number"&&(r.preflight_overrides=n);let o=t.renderer_ownership;if(o!==void 0){let s=Vh(o);if(s===null)return null;r.renderer_ownership=s}let i=t.preflight_ownership;if(i!==void 0){let s=Bh(i);if(s===null)return null;r.preflight_ownership=s}return r}function XC(e){return{schema_version:1,commands:e.commands,command_overrides:e.command_overrides,command_handlers:e.command_handlers,hooks:e.hooks,flag_commands:e.flag_commands,item_types:e.item_types,item_fields:e.item_fields,...e.relationship_kinds?{relationship_kinds:e.relationship_kinds}:{},migrations:e.migrations,profiles:e.profiles,importers:e.importers,exporters:e.exporters,search_providers:e.search_providers,vector_store_adapters:e.vector_store_adapters,...e.assurance_providers?{assurance_providers:e.assurance_providers}:{},parser_overrides:e.parser_overrides,service_overrides:e.service_overrides,renderer_overrides:e.renderer_overrides,...e.renderer_ownership?{renderer_ownership:e.renderer_ownership}:{},preflight_overrides:e.preflight_overrides,...e.preflight_ownership?{preflight_ownership:e.preflight_ownership}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="628615ea-5be3-5753-a6c5-3eba8400a8da")}catch{}})();function co(e,t,r){if(e===t)return 0;if(Math.abs(e.length-t.length)>r)return null;let n=t.length+1,o=new Array(n),i=new Array(n),s=new Array(n);for(let c=0;c<n;c+=1)o[c]=0,i[c]=c;for(let c=1;c<=e.length;c+=1){s[0]=c;let d=s[0];for(let l=1;l<=t.length;l+=1){let u=e[c-1]===t[l-1]?0:1,f=i[l-1]+u,m=s[l-1]+1,_=i[l]+1,y=Math.min(f,m,_);c>1&&l>1&&e[c-1]===t[l-2]&&e[c-2]===t[l-1]&&(y=Math.min(y,o[l-2]+1)),s[l]=y,y<d&&(d=y)}if(d>r)return null;for(let l=0;l<n;l+=1)o[l]=i[l],i[l]=s[l]}let a=i[t.length];return a<=r?a:null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7359c10a-4c56-57ea-8254-fc26b19e5c84")}catch{}})();function Fr(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}function He(e){return xe.includes(e)}function Rd(e){let t=e.trim().toLowerCase();return He(t)?t:null}function xd(e){return e.filter(t=>!He(t))}function es(e){let t=e.trim().toLowerCase();return t.length===0?null:Yc[t]??null}function Nd(e){let t=Fr([...e].map(i=>i.toLowerCase())),r=[],n=[];for(let i of t){let s=es(i);if(s){r.push(s),n.push({alias:i,target:s});continue}r.push(i)}let o=[...new Map(n.map(i=>[`${i.alias}>${i.target}`,i])).values()].sort((i,s)=>i.alias.localeCompare(s.alias));return{capabilities:Fr(r),legacy_aliases:o}}function Wh(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let r=es(t);if(r)return r;let n=Math.max(1,Math.floor(t.length*.34)),o=null,i=Number.POSITIVE_INFINITY;for(let s of xe){let a=co(t,s,n);a!==null&&a<i&&(i=a,o=s)}return o}function Dd(e,t,r){let n=xe.join(","),o=Wh(r)??"none";return`extension_capability_unknown:${e}:${t}:${r}:allowed=${n}:suggested=${o}`}function Pd(e,t,r){let n=r.map(o=>`${o.alias}>${o.target}`).join(",");return`extension_capability_legacy_alias:${e}:${t}:aliases=${n}`}function Gh(e){let t=/^extension_capability_unknown:(global|project):([^:]+):([^:]+):allowed=([^:]+):suggested=([^:]+)$/.exec(e.trim());if(!t)return null;let[,r,n,o,i,s]=t,a=r,c=i.split(",").map(u=>u.trim()).filter(u=>u.length>0),d=es(o),l=(s==="none"?void 0:s)??d??void 0;return{layer:a,name:n,capability:o,allowed_capabilities:c,capability_contract_version:ji,suggested_capability:l,suggestion_source:l?d===l?"legacy_alias":"nearest_match":void 0,legacy_alias_target:d??void 0}}function Kh(e){let t=/^extension_capability_legacy_alias:(global|project):([^:]+):aliases=(.+)$/.exec(e.trim());if(!t)return[];let[,r,n,o]=t,i=r,s=[...xe],a=[];for(let c of o.split(",")){let[d,l]=c.split(">"),u=d?.trim(),f=l?.trim().toLowerCase();!u||!f||!He(f)||a.push({layer:i,name:n,capability:u,allowed_capabilities:s,capability_contract_version:ji,suggested_capability:f,suggestion_source:"legacy_alias",legacy_alias_target:f})}return a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01116a5e-62d1-591b-9fd0-84ac6e99f8d0")}catch{}})();function zr(){return{beforeCommand:[],beforeMutation:[],afterCommand:[],onWrite:[],onRead:[],onIndex:[]}}function ts(){return{overrides:[],handlers:[]}}function rs(){return{overrides:[]}}function ns(){return{overrides:[]}}function os(){return{overrides:[]}}function is(){return{overrides:[]}}function ss(){return{commands:[],flags:[],item_fields:[],item_types:[],relationship_kinds:[],migrations:[],profiles:[],importers:[],exporters:[],search_providers:[],vector_store_adapters:[],assurance_providers:[]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="67511565-01f8-58a6-ad06-45b5d0ce831b")}catch{}})();var Yh=new Set(["name","version","entry","priority","description","author","capabilities","manifest_version","pm_min_version","pm_max_version","engines","trusted","provenance","sandbox_profile","permissions","activation","contributions","legacy_capability_aliases"]);function Xh(e){return{unknownKeys:Object.keys(e).filter(t=>!Yh.has(t)).sort((t,r)=>t>r?1:-1),missingVersionBounds:e.pm_min_version===void 0&&e.pm_max_version===void 0}}function Jh(e){let t=Xh(e),r=t.unknownKeys.map(n=>({code:"manifest_unknown_key",path:n,...n==="compatibility"?{suggested_key:"pm_min_version"}:{},message:n==="compatibility"?'Manifest key "compatibility" is ignored; declare the canonical pm_min_version and optional pm_max_version fields instead.':`Manifest key "${n}" is not part of the extension manifest contract and will be ignored.`}));return t.missingVersionBounds&&r.push({code:"no_version_bounds_declared",path:"$",suggested_key:"pm_min_version",message:"No canonical pm version bounds are declared; add pm_min_version so compatibility intent is explicit."}),{ok:r.length===0,findings:r}}function Md(e,t,r){return Jh(r).findings.map(n=>n.code==="manifest_unknown_key"?`extension_manifest_unknown_key:${e}:${t.name}:key=${n.path}${n.suggested_key?`:suggested=${n.suggested_key}`:""}`:`extension_manifest_no_version_bounds:${e}:${t.name}:suggested=pm_min_version`)}import{constants as qe}from"node:os";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="151124a3-cefa-55d3-bf4f-bd8f2553ad72")}catch{}})();var $d=new Map([["EACCES",{summary:"was denied filesystem permission",recovery:"Grant the required filesystem access, then retry.",category:"permission"}],["EDQUOT",{summary:"exceeded the filesystem quota",recovery:"Raise or reclaim the filesystem quota, then retry.",category:"capacity"}],["EMFILE",{summary:"exhausted the process file-descriptor limit",recovery:"Close unused file handles or raise the process limit, then retry.",category:"resource"}],["ENFILE",{summary:"exhausted the host file-descriptor limit",recovery:"Free host file descriptors or raise the host limit, then retry.",category:"resource"}],["ENOMEM",{summary:"ran out of available memory",recovery:"Free memory or reduce concurrent work, then retry.",category:"resource"}],["ENOSPC",{summary:"ran out of storage space",recovery:"Free storage on the filesystem holding the project, then retry.",category:"capacity"}],["EPERM",{summary:"was denied by the host permission policy",recovery:"Grant the required filesystem permission, then retry.",category:"permission"}],["EROFS",{summary:"targeted a read-only filesystem",recovery:"Use a writable project filesystem or remount it read-write, then retry.",category:"permission"}]]),Zh=/^[a-z][a-z0-9_]{0,63}$/u,Qh=new Map([[qe.errno.EACCES,"EACCES"],[qe.errno.EDQUOT,"EDQUOT"],[qe.errno.EMFILE,"EMFILE"],[qe.errno.ENFILE,"ENFILE"],[qe.errno.ENOMEM,"ENOMEM"],[qe.errno.ENOSPC,"ENOSPC"],[qe.errno.EPERM,"EPERM"],[qe.errno.EROFS,"EROFS"]].filter(([e])=>Number.isInteger(e))),eg={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function tg(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.code=="string"&&$d.has(t.code)?t.code:typeof t.errno!="number"||!Number.isInteger(t.errno)?null:Qh.get(Math.abs(t.errno))??null}function rg(e,t,r={}){let n=tg(e);if(n===null)return null;if(!Zh.test(t))throw new g("Host environment operation labels must be bounded identifiers.",h.USAGE,{code:"host_environment_operation_invalid",field:"operation"});let o=$d.get(n);return new g(`Host filesystem operation ${t} ${o.summary}.`,h.GENERIC_FAILURE,{code:r.codes?.[o.category]??eg[o.category].code,reason:n,required:o.recovery,why:r.why??"The operating system refused a required project filesystem operation.",nextSteps:[o.recovery,...r.nextSteps??[]],...r.suggestedRetry?{recovery:{suggested_retry:r.suggestedRetry}}:{}})}async function jd(e,t,r={}){try{return await t()}catch(n){throw rg(n,e,r)??n}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c24357cc-5dad-5cd7-aa89-cddd2945aab7")}catch{}})();var ng=Object.freeze([{flag:"--json"},{flag:"--lean"},{flag:"--token-accounting"},{flag:"--output-include",value_name:"fields"},{flag:"--output-limit",value_name:"count"},{flag:"--output-budget",value_name:"tokens"},{flag:"--output-format",value_name:"toon|json"},{flag:"--output-session",value_name:"state"},{flag:"--output-cursor",value_name:"cursor"},{flag:"--output-row-contract"},{flag:"--quiet"},{flag:"--no-changed-fields"},{flag:"--full-changed-fields"},{flag:"--id-only"},{flag:"--pm-path",aliases:["--path"]},{flag:"--no-extensions"},{flag:"--no-pager"},{flag:"--profile"},{flag:"--help"},{flag:"--author",value_name:"id"}]),as=new Set(ng.flatMap(e=>[e.flag,...e.aliases??[]]));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="896ebde0-4ca1-50ed-bb8e-2a8c2d978d94")}catch{}})();var Ld=/^(--[a-z0-9][a-z0-9_-]*)(?:[ =](<[^<>]+>|\[[^[\]]+\]))?$/;function cs(e){if(typeof e!="string")return null;let t=Ld.exec(e.trim());if(!t)return null;let r=t[2];return{name:t[1],valueName:r?r.slice(1,-1):null,optional:r?.startsWith("[")??!1}}function lR(e){let t=cs(e);return t?t.name:typeof e=="string"&&e.trim()||null}function og(e){if(typeof e!="string")return null;let t=e.trim(),r=t.split(/[ =]/,1)[0];return as.has(r)?"host_owned_flag_collision":Ld.test(t)?null:"malformed_long_flag"}function Fd(e,t){let r=[e,t].find(i=>typeof i=="string"&&as.has(i.trim().split(/[ =]/,1)[0]));if(typeof r=="string")return{token:r.trim().split(/[ =]/,1)[0],failure:"host_owned_flag_collision"};if(typeof e!="string")return null;let n=e.trim(),o=og(n);return o===null?null:{token:n,failure:o}}function zd(e,t){return t==="host_owned_flag_collision"?`cannot shadow host-owned global flag "${e}"; read it from context.global instead`:`long flag "${e}" must start with a double-dash name such as "--my-flag" or "--my-flag <value>"`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5c3049c3-1d5a-5e7e-a070-35340737a6ab")}catch{}})();var Ud=Object.freeze({string:"string",number:"number",int:"number",integer:"number",float:"number",boolean:"boolean",bool:"boolean"});function lo(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.hasOwn(Ud,t)?Ud[t]:null}function ig(e,t,r){return!!(e.value_name?.trim()||t||r||e.required===!0||e.list===!0||e.repeatable===!0)}function sg(e){return(e.value_type?.trim()||e.type?.trim())?.toLowerCase()}function mR(e){let t=sg(e),r=lo(t),n=cs(e.long),o=e.value_name?.trim()||null,i=!(r==="boolean"&&t!=="bool")&&ig(e,n?.valueName,t),s=n?.valueName?n.optional:t==="bool";return{value_type:r,value_arity:i?s?"optional":"required":"none",value_name:i?o??n?.valueName??"value":null}}function Hd(e){let t=[],r=n=>{if(Array.isArray(n)){for(let o of n)r(o);return}if(typeof n=="string"){for(let o of n.split(",")){let i=o.trim();i.length>0&&t.push(i)}return}n!=null&&t.push(n)};return r(e),t}function qd(e,t){return t==="string"?!0:t==="number"?typeof e=="number"?Number.isFinite(e):typeof e=="string"&&e.trim().length>0&&Number.isFinite(Number(e)):typeof e=="boolean"?!0:typeof e=="string"&&["true","false","1","0"].includes(e.trim().toLowerCase())}function pR(e,t){return t==="number"?typeof e=="number"&&Number.isFinite(e)?null:{kind:t,received:e,expected:"a finite number"}:typeof e=="boolean"?null:{kind:t,received:e,expected:"true, false, 1, or 0"}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1dcf5e56-cb0c-5e4c-b0e8-e4dbd06187dd")}catch{}})();var ag=5e3;async function Ur(e,t,r){let n=[];for(let o of e)try{await o.run(D(r))}catch{n.push(`extension_hook_failed:${o.layer}:${o.name}:${t}`)}return n}async function cg(e,t){return Ur(e.beforeCommand,"beforeCommand",t)}function dg(e,t,r){if(e===void 0)return;if(typeof e!="object"||e===null||!("allow"in e)||e.allow!==!0&&e.allow!==!1)throw new g(`Extension mutation guard ${t.name} returned an invalid decision.`,h.CONFLICT,{code:"extension_mutation_guard_invalid_decision",reason:`${t.layer}:${t.name}`,nextSteps:["Return { allow: true } or a structured denial from the guard."]});if(e.allow)return;let n=e,o=typeof n.code=="string"?n.code.trim():"",i=typeof n.remediation=="string"?n.remediation.trim():"";if(o.length===0||i.length===0)throw new g(`Extension mutation guard ${t.name} returned an invalid denial.`,h.CONFLICT,{code:"extension_mutation_guard_invalid_denial",reason:`${t.layer}:${t.name}`,nextSteps:["Return non-empty code and remediation fields from the guard."]});let s=typeof n.message=="string"?n.message.trim():"";throw new g(s||`Extension mutation guard ${t.name} denied ${r}.`,h.CONFLICT,{code:o,reason:`${t.layer}:${t.name}`,nextSteps:[i]})}async function ds(e,t){for(let r of e.beforeMutation??[]){let n,o;try{let i=Promise.resolve().then(()=>r.run({pm_root:t.pm_root,operation:t.operation,before:t.before===null?null:D(t.before),after:t.after===null?null:D(t.after),changed_fields:[...t.changed_fields],sdk:t.sdk}));i.catch(()=>{}),n=await Promise.race([i,new Promise((s,a)=>{o=setTimeout(()=>{a(new g(`Extension mutation guard ${r.name} timed out before ${t.operation}.`,h.CONFLICT,{code:"extension_mutation_guard_timed_out",reason:`${r.layer}:${r.name}`,nextSteps:["Fix or disable the stalled extension guard, then retry the mutation."]}))},ag),o.unref?.()})])}catch(i){throw i instanceof g?i:new g(`Extension mutation guard ${r.name} failed before ${t.operation}.`,h.CONFLICT,{code:"extension_mutation_guard_failed",reason:`${r.layer}:${r.name}`,nextSteps:["Fix or disable the failing extension guard, then retry the mutation."]})}finally{clearTimeout(o)}dg(n,r,t.operation)}}async function lg(e,t){return Ur(e.afterCommand,"afterCommand",t)}async function ls(e,t){return Ur(e.onWrite,"onWrite",t)}async function us(e,t){return Ur(e.onRead,"onRead",t)}async function fs(e,t){return Ur(e.onIndex,"onIndex",t)}function ug(e){let t="";e instanceof Error&&typeof e.message=="string"?t=e.message:typeof e=="string"?t=e:typeof e=="object"&&e!==null&&typeof e.message=="string"&&(t=e.message);let r=t.replace(/\s+/gu," ").trim();if(r.length===0)return"";let n=300;return r.length>n?`${r.slice(0,n-1)}\u2026`:r}function uo(e,t){if(typeof e!="object"||e===null||typeof e[t]!="string")return;let r=String(e[t]).replace(/\s+/gu," ").trim();return r.length>0?r.slice(0,300):void 0}function fg(e){if(typeof e!="object"||e===null||!Object.hasOwn(e,"exit_code"))return;let t=e.exit_code;if(typeof t!="number"||!Number.isInteger(t)||t<1||t>255)throw new TypeError("Extension command result exit_code must be an integer from 1 to 255.");return t}async function ms(e,t){let r=F(t.command);if(r.length===0)return{handled:!1,result:null,warnings:[]};let n=[...e.handlers].reverse().find(o=>o.command===r);if(!n)return{handled:!1,result:null,warnings:[]};try{let o=await n.run({command:r,args:D(t.args),options:D(t.options),global:D(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel,...t.sdk===void 0?{}:{sdk:t.sdk}});return{handled:!0,result:o,warnings:[],...Object.fromEntries([["exitCode",fg(o)],["errorCode",uo(o,"code")],["remediation",uo(o,"remediation")]].filter(i=>i[1]!==void 0))}}catch(o){let i=typeof o=="object"&&o!==null&&"exitCode"in o?o.exitCode:void 0;if(typeof i=="number"&&Number.isFinite(i))throw o;return{handled:!1,result:null,warnings:[`extension_command_handler_failed:${n.layer}:${n.name}:${n.command}`],errorMessage:ug(o),...Object.fromEntries([["errorCode",uo(o,"code")],["remediation",uo(o,"remediation")]].filter(s=>s[1]!==void 0))}}}async function ps(e,t){let r=F(t.command);if(r.length===0)return{overridden:!1,context:{command:r,args:D(t.args),options:pe(t.options),global:_e(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel},warnings:[]};let n=[...e.overrides].reverse().find(o=>o.command===r);if(!n)return{overridden:!1,context:{command:r,args:D(t.args),options:pe(t.options),global:_e(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel},warnings:[]};try{let o=await Promise.resolve(n.run({command:r,args:D(t.args),options:pe(t.options),global:_e(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel}))??{},i=Array.isArray(o.args)?D(o.args):D(t.args),s=o.options?pe(o.options):pe(t.options),a=o.global?_e(o.global):_e(t.global);return{overridden:!0,context:{command:r,args:i,options:s,global:a,pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel},warnings:[]}}catch{return{overridden:!1,context:{command:r,args:D(t.args),options:pe(t.options),global:_e(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel},warnings:[`extension_parser_override_failed:${n.layer}:${n.name}:${n.command}`]}}}async function _s(e,t){let r={command:F(t.command),args:D(t.args),options:pe(t.options),global:_e(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel},n=D(t.decision),o=[...e.overrides].reverse().find(i=>!i.commands?.length||i.commands.includes(r.command));if(!o)return{overridden:!1,context:r,decision:n,warnings:[]};try{let i=await Promise.resolve(o.run({command:r.command,args:D(r.args),options:pe(r.options),global:_e(r.global),pm_root:r.pm_root,source_workspace_root:r.source_workspace_root,repo_root:r.repo_root,pm_root_rel:r.pm_root_rel,decision:D(n)}))??{},s={command:r.command,args:Array.isArray(i.args)?D(i.args):r.args,options:i.options?pe(i.options):r.options,global:i.global?_e(i.global):r.global,pm_root:r.pm_root,source_workspace_root:r.source_workspace_root,repo_root:r.repo_root,pm_root_rel:r.pm_root_rel},a={enforce_item_format_gate:typeof i.enforce_item_format_gate=="boolean"?i.enforce_item_format_gate:n.enforce_item_format_gate,run_preflight_item_format_sync:typeof i.run_preflight_item_format_sync=="boolean"?i.run_preflight_item_format_sync:n.run_preflight_item_format_sync,run_extension_migrations:typeof i.run_extension_migrations=="boolean"?i.run_extension_migrations:n.run_extension_migrations,enforce_mandatory_migration_gate:typeof i.enforce_mandatory_migration_gate=="boolean"?i.enforce_mandatory_migration_gate:n.enforce_mandatory_migration_gate};return{overridden:!0,context:s,decision:a,warnings:[]}}catch{return{overridden:!1,context:r,decision:n,warnings:[`extension_preflight_override_failed:${o.layer}:${o.name}`]}}}function Vd(e){return{handled:!1,result:e.payload,warnings:[]}}function Bd(e,t){return[...e.overrides].reverse().filter(r=>r.service===t)}function Wd(e){return{service:e.service,command:e.command?F(e.command):void 0,args:e.args?D(e.args):void 0,options:e.options?pe(e.options):void 0,global:e.global?_e(e.global):void 0,pm_root:e.pm_root,source_workspace_root:e.source_workspace_root,repo_root:e.repo_root,pm_root_rel:e.pm_root_rel,payload:D(e.payload)}}function mg(e){if(typeof e!="object"||e===null||!Object.hasOwn(e,"handled"))return!1;let t=e.handled;return t===!0?Object.hasOwn(e,"result"):t===!1&&Reflect.ownKeys(e).length===1}function Gd(e,t){return mg(e)?e.handled?{handled:!0,result:e.result}:{handled:!1,result:t.payload}:t.service==="output_format"&&e==null?{handled:!1,result:t.payload}:{handled:!0,result:e}}function Kd(e,t,r){return t.service==="output_format"&&typeof e=="object"&&e!==null&&W(e,r.payload)}function Yd(e,t,r){if(t.handled){if(e.passThrough===!0){r.push(`extension_service_pass_through_contract_violated:${e.layer}:${e.name}:${e.service}`);return}return{handled:!0,result:t.result,warnings:r}}}function ys(e,t){let r=Bd(e,t.service);if(r.length===0)return Vd(t);let n=[];for(let o of r)try{let i=Wd(t),s=o.run(i);if(s instanceof Promise){n.push(`extension_service_override_async_unsupported:${o.layer}:${o.name}:${o.service}`);continue}if(Kd(s,t,i)){n.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=Yd(o,Gd(s,t),n);if(a)return a}catch{n.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:n}}async function hs(e,t){let r=Bd(e,t.service);if(r.length===0)return Vd(t);let n=[];for(let o of r)try{let i=Wd(t),s=await Promise.resolve(o.run(i));if(Kd(s,t,i)){n.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=Yd(o,Gd(s,t),n);if(a)return a}catch{n.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:n}}function gs(e,t){let r=F(t.command);if(r.length===0)return{overridden:!1,result:t.result,warnings:[]};let n=[...e.overrides].reverse().find(o=>o.command===r);if(!n)return{overridden:!1,result:t.result,warnings:[]};try{let o=pe(t.options),i=_e(t.global),s=n.run({command:r,args:D(t.args),options:o,global:i,pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel,result:D(t.result)});return s instanceof Promise?{overridden:!1,result:t.result,warnings:[`extension_command_override_async_unsupported:${n.layer}:${n.name}:${n.command}`]}:{overridden:!0,result:s,warnings:[]}}catch{return{overridden:!1,result:t.result,warnings:[`extension_command_override_failed:${n.layer}:${n.name}:${n.command}`]}}}function pg(e,t,r){if((e.commands?.length??0)>0&&!e.commands?.includes(t))return!1;if(e.resultDiscriminator===void 0)return!0;try{return e.resultDiscriminator(D(r))}catch{return!1}}function bs(e,t){let r=typeof t.command=="string"?F(t.command):"",n=[...e.overrides].reverse().find(o=>o.format===t.format&&pg(o,r,t.result));if(!n)return{overridden:!1,rendered:null,warnings:[]};try{let o=Array.isArray(t.args)?D(t.args):[],i=pe(t.options),s=_e(t.global),a=typeof t.pm_root=="string"?t.pm_root:"",c=n.run({format:t.format,command:r,args:o,options:i,global:s,pm_root:a,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel,result:D(t.result)});return c==null?{overridden:!1,rendered:null,warnings:[]}:typeof c!="string"?{overridden:!1,rendered:null,warnings:[`extension_renderer_invalid_result:${n.layer}:${n.name}:${n.format}`]}:{overridden:!0,rendered:c,warnings:[]}}catch{return{overridden:!1,rendered:null,warnings:[`extension_renderer_failed:${n.layer}:${n.name}:${n.format}`]}}}import wt from"node:fs/promises";import bt from"node:path";import{pathToFileURL as Xg}from"node:url";import Xd from"path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01422574-583a-5fd1-bc00-f61f430073cd")}catch{}})();function ws(e,t){let r=Xd.relative(e,t);return r.length===0?!0:!r.startsWith("..")&&!Xd.isAbsolute(r)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="559b05dc-0290-5a7c-97b9-ef1e5e8670ba")}catch{}})();function Jd(e){let t={beforeCommand:e.hooks.beforeCommand.length,beforeMutation:e.hooks.beforeMutation.length,afterCommand:e.hooks.afterCommand.length,onWrite:e.hooks.onWrite.length,onRead:e.hooks.onRead.length,onIndex:e.hooks.onIndex.length,commandOverrides:e.commands.overrides.length,commandHandlers:e.commands.handlers.length,parserOverrides:e.parsers.overrides.length,preflightOverrides:e.preflight.overrides.length,serviceOverrides:e.services.overrides.length,rendererOverrides:e.renderers.overrides.length,registrations:Object.fromEntries(Object.entries(e.registrations).map(([r,n])=>[r,n.length]))};return()=>{e.hooks.beforeCommand.length=t.beforeCommand,e.hooks.beforeMutation.length=t.beforeMutation,e.hooks.afterCommand.length=t.afterCommand,e.hooks.onWrite.length=t.onWrite,e.hooks.onRead.length=t.onRead,e.hooks.onIndex.length=t.onIndex,e.commands.overrides.length=t.commandOverrides,e.commands.handlers.length=t.commandHandlers,e.parsers.overrides.length=t.parserOverrides,e.preflight.overrides.length=t.preflightOverrides,e.services.overrides.length=t.serviceOverrides,e.renderers.overrides.length=t.rendererOverrides;for(let[r,n]of Object.entries(t.registrations))e.registrations[r].length=n}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="17ae377d-20c2-5e45-825a-48a79c6c7601")}catch{}})();function K(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return t}function Q(e,t){if(t!==void 0&&typeof t!="boolean")throw new TypeError(`${e} must be a boolean when provided`)}function V(e,t){if(t!==void 0&&(typeof t!="string"||t.trim().length===0))throw new TypeError(`${e} must be a non-empty string when provided`)}function Zd(e,t){if(t===void 0)return;let r=n=>typeof n=="string"||typeof n=="number"||typeof n=="boolean";if(Array.isArray(t)){for(let[n,o]of t.entries())if(!r(o))throw new TypeError(`${e}[${n}] must be a string, number, or boolean`);return}if(!r(t))throw new TypeError(`${e} must be a string, number, or boolean, or an array of these when provided`)}function yt(e,t){if(t!==void 0){if(!Array.isArray(t))throw new TypeError(`${e} must be an array of non-empty strings when provided`);for(let[r,n]of t.entries())if(typeof n!="string"||n.trim().length===0)throw new TypeError(`${e}[${r}] must be a non-empty string`)}}function Hr(e,t){if(yt(e,t),!Array.isArray(t))return[];let r=[],n=new Set;for(let o of t){let i=o.trim();i.length===0||n.has(i)||(n.add(i),r.push(i))}return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="34536eba-0f92-5599-a807-5b39b000e733")}catch{}})();var vs=Object.freeze(["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="60fd882d-7c92-5be5-bf46-7e3c128bfb58")}catch{}})();var _g=new Set(vs);function yg(e){if(e!==void 0&&!_g.has(String(e)))throw new Error(`registerCommand definition.family must be one of: ${vs.join(", ")}`)}function Qd(e){V("registerCommand definition.action",e.action),V("registerCommand definition.family",e.family),V("registerCommand definition.description",e.description),V("registerCommand definition.intent",e.intent),V("registerCommand definition.tier",e.tier);let t=e.tier;if(t!==void 0&&t!=="core"&&t!=="standard"&&t!=="full"&&t!=="internal")throw new Error("registerCommand definition.tier must be core, standard, full, or internal");yg(e.family)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="095ea29d-eda3-5287-b54d-8a961658f7bc")}catch{}})();function el(e,t="",r=""){if(e===void 0)return;if(Jt(t)||Jt(r))throw new TypeError("Native pm commands and actions cannot declare read_output");let n=K("registerCommand definition.read_output",e);if(Object.keys(n).some(s=>s!=="row_keys")||!Array.isArray(n.row_keys))throw new TypeError("registerCommand definition.read_output requires only row_keys: string[]");let o=Array.from(n.row_keys),i=new Set(["__proto__","constructor","prototype","row_contract","read_output","read_session","omission_receipt","output_budget_truncation"]);if(o.some(s=>typeof s!="string"||!/^[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*$/u.test(s)||s.split(".").some(a=>i.has(a))))throw new TypeError("registerCommand definition.read_output row_keys must be safe dot-delimited property paths");if(new Set(o).size!==o.length||o.some(s=>o.some(a=>a.startsWith(`${s}.`))))throw new TypeError("registerCommand definition.read_output row_keys must be unique and non-overlapping");return Object.freeze({row_keys:Object.freeze([...o])})}function Jt(e){let t=e.trim().toLowerCase().replace(/\s+/gu,"-");return Yt.includes(t)||Xt.includes(t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="07cb237c-3956-5997-85f8-972d2ee490d0")}catch{}})();function hg(e){let t=K("registerExporter options.output",e),r=new Set(["channel","receipt","media_type"]);for(let n of Object.keys(t))if(!r.has(n))throw new TypeError(`registerExporter options.output contains unsupported field ${n}`);if(t.channel!=="stdout"&&t.channel!=="file")throw new TypeError("registerExporter options.output.channel must be stdout|file");if(t.receipt!==void 0&&t.receipt!=="suppress"&&t.receipt!=="render")throw new TypeError("registerExporter options.output.receipt must be suppress|render");if(t.channel==="stdout"&&t.receipt==="render")throw new TypeError("registerExporter stdout artifacts cannot render a host receipt");return V("registerExporter options.output.media_type",t.media_type),{channel:t.channel,receipt:t.receipt??(t.channel==="stdout"?"suppress":"render"),...typeof t.media_type=="string"?{media_type:t.media_type}:{}}}function tl(e,t,r){if(e==="registerImporter"&&t.output!==void 0)throw new TypeError("registerImporter options.output is exporter-only");if(e!=="registerExporter"||t.output===void 0)return;let n=hg(t.output);return!r&&n.channel==="stdout"&&(t.description="Export items with the registered extension adapter. Artifact bytes are written exclusively to stdout and the host receipt is suppressed by default."),n}function Es(e,t,r){return{registration:t,action:r,command:e.command,args:D(e.args),options:D(e.options),global:D(e.global),pm_root:e.pm_root,source_workspace_root:e.source_workspace_root,repo_root:e.repo_root,pm_root_rel:e.pm_root_rel,...e.sdk===void 0?{}:{sdk:e.sdk}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fc2e7eac-cd1c-5885-aa27-e98455008a4f")}catch{}})();function rl(e){return!e.extensionReady||!e.enabledForLoad?null:{layer:e.layer,directory:e.directory,manifest_path:e.manifestPath,entry_path:e.entryPath,manifest:e.manifest,source_package:e.sourceIdentity?.package_name,source_aliases:e.sourceIdentity?.aliases,contributions:e.sourceIdentity?.contributions}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bb1b4879-079c-50d4-afa5-e8a36ead2e5c")}catch{}})();function ve(e){return typeof e!="string"?"":e.trim().toLowerCase()}function P(e){return new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))}function gg(e){let t=e.trim().toLowerCase();if(t.length===0)return"";let r=t.split(/[.:/]/).map(n=>n.replace(/[\s_-]+/g,"")).filter(n=>n.length>0);return r.length===0?"":r.length===1?r[0]:`${r[0]}.${r.slice(1).join("")}`}function Zt(e){return new Set((e??[]).map(t=>gg(t)).filter(t=>t.length>0))}function nl(e){let t=ve(e);return Pn.includes(t)?t:"off"}function ol(e){let t=ve(e);return Mn.includes(t)?t:"off"}function qr(e){let t=ve(e);return $n.includes(t)?t:"none"}function ks(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return Xc.includes(t)?t:void 0}function il(e){if(typeof e=="string"){let t=ks(e)??"block";return{global:t,project:t}}return typeof e=="object"&&e!==null&&!Array.isArray(e)?{global:ks(e.global)??"block",project:ks(e.project)??"block"}:{global:"block",project:"block"}}function bg(e){return e.global===e.project?e.global:{global:e.global,project:e.project}}function $(e){return[...new Set(e)].sort((t,r)=>t.localeCompare(r))}function wg(e){let t=ve(e.name);return t.length===0?null:{name:t,normalized:{name:t,disabled:e.disabled===!0,requireTrusted:e.require_trusted===!0,requireProvenance:e.require_provenance===!0,sandboxProfile:e.sandbox_profile!==void 0?qr(e.sandbox_profile):void 0,allowedCapabilities:P(e.allowed_capabilities),blockedCapabilities:P(e.blocked_capabilities),allowedSurfaces:Zt(e.allowed_surfaces),blockedSurfaces:Zt(e.blocked_surfaces),allowedCommands:P(e.allowed_commands),blockedCommands:P(e.blocked_commands),allowedActions:P(e.allowed_actions),blockedActions:P(e.blocked_actions),allowedServices:P(e.allowed_services),blockedServices:P(e.blocked_services)}}}function sl(e){let t=new Map;for(let r of e??[]){let n=wg(r);n&&t.set(n.name,n.normalized)}return t}function vg(e){let t=[],r=[...e.overridesByName.values()].sort((o,i)=>o.name.localeCompare(i.name));for(let o of $([...e.allowedCapabilities,...e.blockedCapabilities]))He(o)||t.push(`extension_policy_unknown_capability:${o}`);for(let o of r)for(let i of $([...o.allowedCapabilities,...o.blockedCapabilities]))He(i)||t.push(`extension_policy_unknown_capability:${o.name}:${i}`);let n=new Set(jn);for(let o of $([...e.allowedSurfaces,...e.blockedSurfaces]))n.has(o)||t.push(`extension_policy_unknown_surface:${o}`);for(let o of r)for(let i of $([...o.allowedSurfaces,...o.blockedSurfaces]))n.has(i)||t.push(`extension_policy_unknown_surface:${o.name}:${i}`);return[...new Set(t)].sort((o,i)=>o.localeCompare(i))}function al(e){let t=e.extensions?.policy??{},r=P(t.allowed_capabilities),n=P(t.blocked_capabilities),o=Zt(t.allowed_surfaces),i=Zt(t.blocked_surfaces),s=sl(t.extension_overrides);return{mode:nl(t.mode),trustMode:ol(t.trust_mode),pmMaxVersionExceededMode:il(t.pm_max_version_exceeded_mode),requireProvenance:t.require_provenance===!0,trustedExtensions:P(t.trusted_extensions),defaultSandboxProfile:qr(t.default_sandbox_profile),allowedExtensions:P(t.allowed_extensions),blockedExtensions:P(t.blocked_extensions),allowedCapabilities:r,blockedCapabilities:n,allowedSurfaces:o,blockedSurfaces:i,allowedCommands:P(t.allowed_commands),blockedCommands:P(t.blocked_commands),allowedActions:P(t.allowed_actions),blockedActions:P(t.blocked_actions),allowedServices:P(t.allowed_services),blockedServices:P(t.blocked_services),overridesByName:s,warnings:vg({allowedCapabilities:r,blockedCapabilities:n,allowedSurfaces:o,blockedSurfaces:i,overridesByName:s})}}function cl(e){let t=[...e.overridesByName.values()].sort((r,n)=>r.name.localeCompare(n.name)).map(r=>({name:r.name,...r.disabled?{disabled:!0}:{},...r.requireTrusted?{require_trusted:!0}:{},...r.requireProvenance?{require_provenance:!0}:{},...r.sandboxProfile?{sandbox_profile:r.sandboxProfile}:{},...r.allowedCapabilities.size>0?{allowed_capabilities:$(r.allowedCapabilities)}:{},...r.blockedCapabilities.size>0?{blocked_capabilities:$(r.blockedCapabilities)}:{},...r.allowedSurfaces.size>0?{allowed_surfaces:$(r.allowedSurfaces)}:{},...r.blockedSurfaces.size>0?{blocked_surfaces:$(r.blockedSurfaces)}:{},...r.allowedCommands.size>0?{allowed_commands:$(r.allowedCommands)}:{},...r.blockedCommands.size>0?{blocked_commands:$(r.blockedCommands)}:{},...r.allowedActions.size>0?{allowed_actions:$(r.allowedActions)}:{},...r.blockedActions.size>0?{blocked_actions:$(r.blockedActions)}:{},...r.allowedServices.size>0?{allowed_services:$(r.allowedServices)}:{},...r.blockedServices.size>0?{blocked_services:$(r.blockedServices)}:{}}));return{mode:e.mode,trust_mode:e.trustMode,pm_max_version_exceeded_mode:bg(e.pmMaxVersionExceededMode),require_provenance:e.requireProvenance,trusted_extensions:$(e.trustedExtensions),default_sandbox_profile:e.defaultSandboxProfile,allowed_extensions:$(e.allowedExtensions),blocked_extensions:$(e.blockedExtensions),allowed_capabilities:$(e.allowedCapabilities),blocked_capabilities:$(e.blockedCapabilities),allowed_surfaces:$(e.allowedSurfaces),blocked_surfaces:$(e.blockedSurfaces),allowed_commands:$(e.allowedCommands),blocked_commands:$(e.blockedCommands),allowed_actions:$(e.allowedActions),blocked_actions:$(e.blockedActions),allowed_services:$(e.allowedServices),blocked_services:$(e.blockedServices),extension_overrides:t}}function dl(e){let t=sl(e.extension_overrides);return{mode:nl(e.mode),trustMode:ol(e.trust_mode),pmMaxVersionExceededMode:il(e.pm_max_version_exceeded_mode),requireProvenance:e.require_provenance===!0,trustedExtensions:P(e.trusted_extensions),defaultSandboxProfile:qr(e.default_sandbox_profile),allowedExtensions:P(e.allowed_extensions),blockedExtensions:P(e.blocked_extensions),allowedCapabilities:P(e.allowed_capabilities),blockedCapabilities:P(e.blocked_capabilities),allowedSurfaces:Zt(e.allowed_surfaces),blockedSurfaces:Zt(e.blocked_surfaces),allowedCommands:P(e.allowed_commands),blockedCommands:P(e.blocked_commands),allowedActions:P(e.allowed_actions),blockedActions:P(e.blocked_actions),allowedServices:P(e.allowed_services),blockedServices:P(e.blocked_services),overridesByName:t,warnings:[]}}function Ve(e,t){return e.overridesByName.get(ve(t))??null}function Qt(e,t,r,n,o){return t.has(r)?o:e.size>0&&!e.has(r)?n:null}function ll(e,t,r){let n=r.trim().toLowerCase(),o=Ve(e,t.name),i=o&&o.allowedCapabilities.size>0?o.allowedCapabilities:e.allowedCapabilities,s=new Set([...e.blockedCapabilities,...o?o.blockedCapabilities:[]]);return Qt(i,s,n,"capability_not_allowlisted","capability_blocked")}function Eg(e,t,r){let n=Ve(e,t.name),o=n&&n.allowedSurfaces.size>0?n.allowedSurfaces:e.allowedSurfaces,i=new Set([...e.blockedSurfaces,...n?n.blockedSurfaces:[]]);return Qt(o,i,r,"surface_not_allowlisted","surface_blocked")}function kg(e,t,r){let n=F(r);if(n.length===0)return null;let o=Ve(e,t.name),i=o&&o.allowedCommands.size>0?o.allowedCommands:e.allowedCommands,s=new Set([...e.blockedCommands,...o?o.blockedCommands:[]]);return Qt(i,s,n,"command_not_allowlisted","command_blocked")}function Sg(e,t,r){let n=ve(r).replace(/\s+/g,"-");if(n.length===0)return null;let o=Ve(e,t.name),i=o&&o.allowedActions.size>0?o.allowedActions:e.allowedActions,s=new Set([...e.blockedActions,...o?o.blockedActions:[]]);return Qt(i,s,n,"action_not_allowlisted","action_blocked")}function Og(e,t,r){let n=ve(r);if(n.length===0)return null;let o=Ve(e,t.name),i=o&&o.allowedServices.size>0?o.allowedServices:e.allowedServices,s=new Set([...e.blockedServices,...o?o.blockedServices:[]]);return Qt(i,s,n,"service_not_allowlisted","service_blocked")}function Ag(e,t){let r=ve(t.name);return Ve(e,t.name)?.disabled===!0?"extension_override_disabled":Qt(e.allowedExtensions,e.blockedExtensions,r,"extension_not_allowlisted","extension_blocked")}function Ig(e,t){if(e.trustMode==="off")return null;let r=Ve(e,t.name),n=ve(t.name),o=t.trusted===!0,i=t.provenanceVerified===!0;return e.trustedExtensions.size>0&&!e.trustedExtensions.has(n)?"extension_not_trusted":(r?.requireTrusted===!0||e.trustMode==="warn"||e.trustMode==="enforce")&&!o?"extension_untrusted":(e.requireProvenance||r?.requireProvenance===!0)&&!i?"provenance_missing_or_unverified":null}function Tg(e,t){if(e.mode==="off")return null;let r=Ve(e,t.name)?.sandboxProfile??t.sandboxProfile??e.defaultSandboxProfile;if(r==="none")return null;let n=t.permissions;if(!n)return"sandbox_permissions_missing";let o=i=>n[i]===!0;return r==="restricted"?o("process_spawn")?"sandbox_restricted_disallows_process_spawn":o("env_write")?"sandbox_restricted_disallows_env_write":null:o("process_spawn")?"sandbox_strict_disallows_process_spawn":o("network")?"sandbox_strict_disallows_network":o("fs_write")?"sandbox_strict_disallows_fs_write":o("env_write")?"sandbox_strict_disallows_env_write":null}function fo(e,t,r,n,o={}){let i=Object.entries(o).sort((a,c)=>a[0].localeCompare(c[0])).map(([a,c])=>`${a}=${c}`).join(":"),s=i.length>0?`:${i}`:"";return`extension_policy_${e}_${t}:${r.layer}:${r.name}:reason=${n}${s}`}function ul(e,t){if(e.mode==="off"&&e.trustMode==="off")return{allowed:!0,warning:null};let r=[],n=Ag(e,t);n&&r.push({reason:n,scope:"extension",mode:e.mode});let o=Ig(e,t);o&&r.push({reason:o,scope:"trust",mode:e.trustMode});let i=Tg(e,t);i&&r.push({reason:i,scope:"extension",mode:e.mode});let s=r.find(c=>c.mode==="enforce");if(s)return{allowed:!1,warning:fo("blocked",s.scope,t,s.reason)};let a=r.find(c=>c.mode==="warn");return a?{allowed:!0,warning:fo("violation",a.scope,t,a.reason)}:{allowed:!0,warning:null}}function fl(e,t,r){if(e.mode==="off")return{allowed:!0,warning:null};let n=ll(e,t,r);return n?{allowed:e.mode==="warn",warning:fo(e.mode==="warn"?"violation":"blocked","capability",t,n,{capability:r.trim().toLowerCase()})}:{allowed:!0,warning:null}}function Cg(e,t,r,n,o){let i=typeof n=="string"?ll(e,t,n):null,s=Eg(e,t,r),a=o.command?kg(e,t,o.command):null,c=o.action?Sg(e,t,o.action):null,d=o.service?Og(e,t,o.service):null;return i??s??a??c??d}function Rg(e,t,r,n){let o={method:ve(e).replace(/\s+/g,"_"),surface:t};return r&&(o.capability=r),n.command&&(o.command=F(n.command)),n.action&&(o.action=ve(n.action).replace(/\s+/g,"-")),n.service&&(o.service=ve(n.service)),o}function ml(e,t,r,n,o,i){if(e.mode==="off")return{allowed:!0,warning:null};let s=i??{},a=Cg(e,t,r,o,s);if(!a)return{allowed:!0,warning:null};let c=fo(e.mode==="warn"?"violation":"blocked","registration",t,a,Rg(n,r,o,s));return{allowed:e.mode==="warn",warning:c}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cd1de600-27e4-522b-842e-1993c12e9f0e")}catch{}})();var _l=100;function pl(e,t){let r=e[t];if(r!=null)return typeof r!="string"||r.trim().length===0?null:r.trim()}function xg(e){if(e==null)return;let t=ze(e);if(!t)return null;let r={};for(let n of Object.keys(t).sort((o,i)=>o.localeCompare(i))){if(n.trim().length===0)return null;let o=t[n];if(typeof o!="string"||o.trim().length===0)return null;r[n.trim()]=o.trim()}return Object.keys(r).length>0?r:void 0}function Ss(e,t){let r=e[t];return typeof r!="string"||r.trim().length===0?null:r.trim()}function yl(e){if(e!=null)return typeof e!="number"||!Number.isInteger(e)?null:e}function ht(e){if(e!=null)return typeof e!="boolean"?null:e}function Ng(e){let t=yl(e.priority);return t===void 0?_l:t}function Dg(e){let t=e.sandbox_profile;if(t==null)return;if(typeof t!="string")return null;let r=qr(t);return r!==t.trim().toLowerCase()?null:r}function Os(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function Pg(e){if(e==null)return;let t=ze(e);if(!t)return null;let r=Os(t.source),n=Os(t.signature),o=Os(t.attestation),i=t.verified===void 0||t.verified===null?void 0:typeof t.verified=="boolean"?t.verified:null;return i===null?null:{...r?{source:r}:{},...n?{signature:n}:{},...o?{attestation:o}:{},...typeof i=="boolean"?{verified:i}:{}}}function Mg(e){if(e==null)return;let t=ze(e);if(!t)return null;let r=ht(t.fs_read),n=ht(t.fs_write),o=ht(t.network),i=ht(t.env_read),s=ht(t.env_write),a=ht(t.process_spawn);return[r,n,o,i,s,a].includes(null)?null:{...typeof r=="boolean"?{fs_read:r}:{},...typeof n=="boolean"?{fs_write:n}:{},...typeof o=="boolean"?{network:o}:{},...typeof i=="boolean"?{env_read:i}:{},...typeof s=="boolean"?{env_write:s}:{},...typeof a=="boolean"?{process_spawn:a}:{}}}function $g(e){if(e==null)return{capabilities:[],legacy_aliases:[]};if(!Array.isArray(e)||e.some(r=>typeof r!="string"))return null;let t=Nd(e);return{capabilities:t.capabilities,legacy_aliases:t.legacy_aliases}}function jg(e){if(e==null)return;let t=ze(e);if(!t)return null;let r=t.commands;if(r==null)return;if(!Array.isArray(r)||r.some(o=>typeof o!="string"))return null;let n=[...new Set(r.map(o=>F(o)).filter(o=>o.length>0))].sort((o,i)=>o.localeCompare(i));return n.length>0?{commands:n}:void 0}function Lg(e){let t=yl(e.manifest_version);if(t===null)return null;let r=pl(e,"pm_min_version");if(r===null)return null;let n=pl(e,"pm_max_version");if(n===null)return null;let o=xg(e.engines);if(o===null)return null;let i=ht(e.trusted);if(i===null)return null;let s=Dg(e);if(s===null)return null;let a=Pg(e.provenance);if(a===null)return null;let c=Mg(e.permissions);if(c===null)return null;let d=$g(e.capabilities);if(d===null)return null;let l=jg(e.activation);if(l===null)return null;let u=ao(e.contributions);return u===null?null:{manifest_version:t,pm_min_version:r,pm_max_version:n,engines:o,trusted:i,sandbox_profile:s,provenance:a,permissions:c,capabilities:d.capabilities,legacy_capability_aliases:d.legacy_aliases,activation:l,contributions:u}}function As(e){if(typeof e!="object"||e===null)return null;let t=e,r=Ss(t,"name");if(r===null)return null;let n=Ss(t,"version");if(n===null)return null;let o=Ss(t,"entry");if(o===null)return null;let i=Ng(t);if(i===null)return null;let s=Lg(t);return s===null?null:{name:r,version:n,entry:o,priority:i,manifest_version:s.manifest_version,pm_min_version:s.pm_min_version,pm_max_version:s.pm_max_version,engines:s.engines,trusted:s.trusted,provenance:s.provenance,sandbox_profile:s.sandbox_profile,permissions:s.permissions,activation:s.activation,contributions:s.contributions,capabilities:s.capabilities,legacy_capability_aliases:s.legacy_capability_aliases.length>0?s.legacy_capability_aliases:void 0}}import Fg from"node:fs/promises";import Vr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="029e0066-2ef5-5204-92ad-4866321710f4")}catch{}})();async function hl(e,t){let r=Vr.dirname(t.manifest_path),n=Vr.relative(r,t.entry_path);if(n.startsWith("..")||Vr.isAbsolute(n))throw new Error(`Cannot snapshot extension entry outside its package directory: ${t.entry_path}`);let o=Vr.join(e,`${t.layer}-${t.directory.replace(/[^a-zA-Z0-9._-]/gu,"_")}`);return await jd("extension_module_graph_snapshot",()=>Fg.cp(r,o,{recursive:!0,force:!0})),Vr.join(o,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bf5c3834-b388-507e-a13c-3beb5d096abb")}catch{}})();function gl(e){let t=typeof e=="function"?e:e.run;if(typeof t!="function")throw new TypeError("registerPreflight override requires a function handler");let r=[...new Set((typeof e=="function"?[]:e.commands??[]).map(n=>{if(typeof n!="string"||n.trim().length===0)throw new TypeError("registerPreflight ownership.commands must contain non-empty command paths");return F(n)}))];return{run:t,...r.length>0?{commands:r}:{}}}function bl(e){let t=[];for(let r=1;r<e.overrides.length;r+=1){let n=e.overrides[r];for(let o of e.overrides.slice(0,r))n.commands?.length&&o.commands?.length&&!o.commands.some(i=>n.commands.includes(i))||t.push(`extension_preflight_override_collision:${n.layer}:${n.name}:${o.layer}:${o.name}`)}return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="47d10c23-88f8-5ba1-bcc2-458f339121a8")}catch{}})();var mo=Kt;function wl(e){let t=e.trim().toLowerCase();return mo.includes(t)?t:null}function vl(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let r=Math.max(1,Math.floor(t.length*.34));for(let n of mo)if(co(t,n,r)!==null)return n;return null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="355fe619-e6f3-51d9-b88c-0b57267c25be")}catch{}})();function El(e){return e==="toon"||e==="json"}function kl(e){return Bt.includes(e)}function gt(e,t){if(typeof t!="function")throw new TypeError(`api.hooks.${e} requires a function handler`)}var Sl=Symbol("extension_registration_trace");function Pe(e,t){let r=new TypeError(e);return Object.defineProperty(r,Sl,{value:t,enumerable:!1,configurable:!1,writable:!1}),r}function Ol(e){return e instanceof Error?e[Sl]:void 0}function Br(e){if(e===null)return null;if(Array.isArray(e))return e.map(t=>Br(t));if(typeof e=="function")return"[Function]";if(typeof e=="bigint"||typeof e=="symbol")return e.toString();if(typeof e=="object"){let t=e,r={};for(let n of Object.keys(t).sort((o,i)=>o.localeCompare(i)))r[n]=Br(t[n]);return r}return e}function Wr(e){if(Array.isArray(e))return e.map(t=>Wr(t));if(typeof e=="object"&&e!==null){let t=e,r={};for(let n of Object.keys(t).sort((o,i)=>o.localeCompare(i)))r[n]=Wr(t[n]);return r}return e}function er(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return Br(t)}function Gr(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return Wr(t)}function Kr(e,t){if(!Array.isArray(t))throw new TypeError(`${e} requires an array of object definitions`);return t.map(r=>er(e,r))}function te(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function Yr(e,t){if(typeof t!="function")throw new TypeError(`${e} requires a function handler`)}function Is(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Ts(e,t){return F(`${e} ${t}`)}function Xr(e,t){return Object.defineProperty(e,"runtime_definition",{value:t,enumerable:!1,writable:!1,configurable:!1}),e}var zg=new Set(["low","medium","high"]),Ug=new Set(["number","string_set"]),Hg=new Set(["string","number","boolean"]);function Al(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function qg(e,t,r){let n=`registerAssuranceMeasurementProvider provider.keys.${t}`,o=K(n,r);if(!Ug.has(String(o.value_type)))throw new TypeError(`${n}.value_type must be number or string_set`);if(V(`${n}.description`,o.description),o.parameters===void 0)return;let i=K(`${n}.parameters`,o.parameters);for(let[s,a]of Object.entries(i)){let c=`${n}.parameters.${s}`;Al(`${c}.name`,s);let d=K(c,a);if(!Hg.has(String(d.type)))throw new TypeError(`${c}.type must be string, number, or boolean`);Q(`${c}.required`,d.required),V(`${c}.description`,d.description)}if(Object.keys(i).length>50)throw new TypeError(`assurance provider ${e} key ${t} exceeds 50 parameters`)}function Il(e){let t=K("registerAssuranceMeasurementProvider provider",e),r=Al("registerAssuranceMeasurementProvider provider.id",t.id);if(!/^[a-z0-9][a-z0-9-]*$/u.test(r))throw new TypeError("registerAssuranceMeasurementProvider provider.id must be a stable lowercase id");if(!zg.has(String(t.cost_class)))throw new TypeError("registerAssuranceMeasurementProvider provider.cost_class must be low, medium, or high");if(typeof t.network!="boolean")throw new TypeError("registerAssuranceMeasurementProvider provider.network must be boolean");let n=K("registerAssuranceMeasurementProvider provider.keys",t.keys);if(Object.keys(n).length===0)throw new TypeError("registerAssuranceMeasurementProvider provider.keys requires at least one key");for(let[o,i]of Object.entries(n)){if(!/^[a-z0-9][a-z0-9-]*$/u.test(o))throw new TypeError(`registerAssuranceMeasurementProvider provider key ${o} must be a stable lowercase id`);qg(r,o,i)}if(t.timeout_ms!==void 0&&(typeof t.timeout_ms!="number"||!Number.isInteger(t.timeout_ms)||t.timeout_ms<1||t.timeout_ms>3e5))throw new TypeError("registerAssuranceMeasurementProvider provider.timeout_ms must be an integer from 1 through 300000");if(typeof t.resolve!="function")throw new TypeError("registerAssuranceMeasurementProvider provider.resolve requires a function handler")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4abca948-e9ba-52b5-b63c-a20fc344980a")}catch{}})();var Vg=new Set(["default","description","enabled","list","long","repeatable","required","short","type","value_name","value_type","value_validation","visible"]);function po(e,t){return Kr(e,t).map(r=>(r.repeatable===!0&&(r.list=!0),r))}function Bg(e){return e.trim().toLowerCase().replace(/[\s_]+/g,"-").replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Cs(e,t){if(t===void 0)return e.replace(/\s+/g,"-");if(typeof t!="string"||t.trim().length===0)throw new TypeError("registerCommand definition.action must be a non-empty string when provided");let r=Bg(t);if(r.length===0)throw new TypeError("registerCommand definition.action must contain alphanumeric characters");return r}function Rs(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("registerCommand definition.arguments must be an array when provided");let t=[];for(let[n,o]of e.entries()){let i=K(`registerCommand definition.arguments[${n}]`,o),s=te(`registerCommand definition.arguments[${n}].name`,i.name);if(Q(`registerCommand definition.arguments[${n}].required`,i.required),Q(`registerCommand definition.arguments[${n}].variadic`,i.variadic),V(`registerCommand definition.arguments[${n}].description`,i.description),s.includes(" "))throw new TypeError(`registerCommand definition.arguments[${n}].name must not contain spaces`);let a={name:s};i.required===!0&&(a.required=!0),i.variadic===!0&&(a.variadic=!0),typeof i.description=="string"&&(a.description=i.description.trim()),t.push(a)}let r=t.map((n,o)=>n.variadic?o:-1).filter(n=>n>=0);if(r.length>1)throw new TypeError("registerCommand definition.arguments supports at most one variadic argument");if(r.length===1&&r[0]!==t.length-1)throw new TypeError("registerCommand definition.arguments variadic argument must be the final argument");return t}function _o(e){if(!Array.isArray(e))throw new TypeError("registerFlags flags requires an array of object definitions");for(let[t,r]of e.entries()){let n=K(`registerFlags flags[${t}]`,r),o=Object.keys(n).filter(c=>!Vg.has(c)).sort((c,d)=>c.localeCompare(d));if(o.length>0)throw new TypeError(`registerFlags flags[${t}] contains unknown field(s): ${o.join(", ")}`);let i=n.long,s=n.short;if(i===void 0&&s===void 0)throw new TypeError(`registerFlags flags[${t}] requires at least one of long or short`);V(`registerFlags flags[${t}].long`,i),V(`registerFlags flags[${t}].short`,s);let a=Fd(i,s);if(a!==null)throw new TypeError(`registerFlags flags[${t}] ${zd(a.token,a.failure)}`);if(V(`registerFlags flags[${t}].value_name`,n.value_name),V(`registerFlags flags[${t}].description`,n.description),Q(`registerFlags flags[${t}].required`,n.required),Q(`registerFlags flags[${t}].enabled`,n.enabled),Q(`registerFlags flags[${t}].visible`,n.visible),Q(`registerFlags flags[${t}].list`,n.list),Q(`registerFlags flags[${t}].repeatable`,n.repeatable),n.list!==void 0&&n.repeatable!==void 0&&n.list!==n.repeatable)throw new TypeError(`registerFlags flags[${t}].list and repeatable must match when both are provided`);if(Zd(`registerFlags flags[${t}].default`,n.default),Array.isArray(n.default)&&n.list!==!0&&n.repeatable!==!0)throw new TypeError(`registerFlags flags[${t}].default cannot be an array unless list is true.`);Tl(`registerFlags flags[${t}]`,n),Wg(`registerFlags flags[${t}]`,n)}}function Wg(e,t){if(t.value_validation===void 0)return;if(t.value_validation!=="coerce"&&t.value_validation!=="strict")throw new TypeError(`${e}.value_validation must be "coerce" or "strict" (received ${JSON.stringify(t.value_validation)}).`);if(t.value_validation!=="strict")return;let r=(typeof t.value_type=="string"?t.value_type:void 0)??(typeof t.type=="string"?t.type:void 0),n=r===void 0?null:lo(r);if(n!=="number"&&n!=="boolean")throw new TypeError(`${e}.value_validation "strict" requires value_type "number" or "boolean" (string values are never malformed).`)}function Tl(e,t){let r=(typeof t.value_type=="string"?t.value_type:void 0)??(typeof t.type=="string"?t.type:void 0);if(r===void 0)return;let n=lo(r);if(n===null)throw new TypeError(`${e} value_type "${r}" is not a known flag value type (expected one of: string, number, boolean).`);if(t.default===void 0)return;let o=t.list===!0||t.repeatable===!0?Hd(t.default):[t.default];for(let[i,s]of o.entries())if(!qd(s,n)){let a=o.length>1?`default[${i}]`:"default";throw new TypeError(`${e}.${a} (${JSON.stringify(s)}) is not coercible to ${n}.`)}}function Cl(e){if(!Array.isArray(e))throw new TypeError("registerItemFields fields requires an array of object definitions");for(let[t,r]of e.entries()){let n=K(`registerItemFields fields[${t}]`,r);te(`registerItemFields fields[${t}].name`,n.name);let o=te(`registerItemFields fields[${t}].type`,n.type);if(wl(o)===null){let i=vl(o),s=i?` Did you mean "${i}"?`:"";throw new TypeError(`registerItemFields fields[${t}].type "${o}" is not a known field type (expected one of: ${mo.join(", ")}).${s}`)}Q(`registerItemFields fields[${t}].optional`,n.optional)}}function Gg(e,t){if(t===void 0)return;let r=`registerItemTypes types[${e}].command_option_policies`;if(!Array.isArray(t))throw new TypeError(`${r} must be an array when provided`);for(let[n,o]of t.entries()){let i=`${r}[${n}]`,s=K(i,o);te(`${i}.command`,s.command),te(`${i}.option`,s.option),Q(`${i}.enabled`,s.enabled),Q(`${i}.required`,s.required),Q(`${i}.visible`,s.visible)}}function Kg(e,t){if(t===void 0)return;let r=`registerItemTypes types[${e}].options`;if(!Array.isArray(t))throw new TypeError(`${r} must be an array when provided`);for(let[n,o]of t.entries()){let i=`${r}[${n}]`,s=K(i,o);te(`${i}.key`,s.key),yt(`${i}.values`,s.values),Q(`${i}.required`,s.required),yt(`${i}.aliases`,s.aliases)}}function Rl(e){if(!Array.isArray(e))throw new TypeError("registerItemTypes types requires an array of object definitions");for(let[t,r]of e.entries()){let n=`registerItemTypes types[${t}]`,o=K(n,r);te(`${n}.name`,o.name),V(`${n}.folder`,o.folder),yt(`${n}.aliases`,o.aliases),yt(`${n}.required_create_fields`,o.required_create_fields),yt(`${n}.required_create_repeatables`,o.required_create_repeatables),Gg(t,o.command_option_policies),Kg(t,o.options)}}function xl(e){let t=K("registerMigration definition",e);if(t.id!==void 0&&typeof t.id!="string")throw new TypeError("registerMigration definition.id must be a string when provided");if(t.description!==void 0&&typeof t.description!="string")throw new TypeError("registerMigration definition.description must be a string when provided");if(t.status!==void 0&&typeof t.status!="string")throw new TypeError("registerMigration definition.status must be a string when provided");if(Q("registerMigration definition.mandatory",t.mandatory),t.run!==void 0&&typeof t.run!="function")throw new TypeError("registerMigration definition.run must be a function when provided")}var Nl=["types","statuses","fields","workflows","config","templates","packages"],Yg={types:(e,t)=>{if(t.name!==void 0&&typeof t.name!="string")throw new TypeError(`${e}.name must be a string when provided`)},workflows:(e,t)=>{if(typeof t.type!="string")throw new TypeError(`${e}.type must be a string`);if(!Array.isArray(t.allowed_transitions))throw new TypeError(`${e}.allowed_transitions must be an array`);for(let[r,n]of t.allowed_transitions.entries())if(!Array.isArray(n))throw new TypeError(`${e}.allowed_transitions[${r}] must be a [from, to] array`)},templates:(e,t)=>{if(typeof t.name!="string")throw new TypeError(`${e}.name must be a string`);if(typeof t.options!="object"||t.options===null||Array.isArray(t.options))throw new TypeError(`${e}.options must be an object`)},packages:(e,t)=>{if(typeof t.spec!="string")throw new TypeError(`${e}.spec must be a string`)}};function Dl(e){let t=K("registerProfile profile",e);if(te("registerProfile profile.name",t.name),te("registerProfile profile.title",t.title),t.summary!==void 0&&typeof t.summary!="string")throw new TypeError("registerProfile profile.summary must be a string when provided");for(let r of Nl){let n=t[r];if(n!==void 0){if(!Array.isArray(n))throw new TypeError(`registerProfile profile.${r} must be an array when provided`);for(let[o,i]of n.entries()){if(typeof i!="object"||i===null||Array.isArray(i))throw new TypeError(`registerProfile profile.${r}[${o}] must be an object`);Yg[r]?.(`registerProfile profile.${r}[${o}]`,i)}}}}function Pl(e){e.summary===void 0&&(e.summary="");for(let t of Nl)e[t]===void 0&&(e[t]=[]);return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="45ff820c-32af-5bdb-a570-3059684129ce")}catch{}})();function Ml(e){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("registerService ownership must be an object");if(Reflect.ownKeys(e).some(t=>t!=="passThrough"))throw new TypeError("registerService ownership supports only passThrough");if(e.passThrough!==void 0&&typeof e.passThrough!="boolean")throw new TypeError("registerService ownership.passThrough must be a boolean when provided");return e.passThrough===!0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b5de5028-f981-599b-8d11-0fc7b07beda4")}catch{}})();function $l(e){return typeof e=="string"?e:String(e)}function Jr(e){let t=e.trim().replace(/^>=\s*/,"").replace(/^v/i,"").split(/[+-]/,1)[0];return/^\d+(?:[.-]\d+)*$/.test(t)?t.split(/[.-]/).map(r=>Number(r)):null}function xs(e,t){let r=Jr(e),n=Jr(t);if(!r||!n)return null;let o=Math.max(r.length,n.length);for(let i=0;i<o;i+=1){let s=r[i]??0,a=n[i]??0;if(s>a)return 1;if(s<a)return-1}return 0}function jl(e,t){if(e==null)return{kind:"pm_min_version",status:"absent",allowed:!0,required:"",current:t};let r=$l(e);if(typeof e!="string"||r.trim().length===0)return{kind:"pm_min_version",status:"invalid",allowed:!1,required:r,current:t};if(!Jr(r))return{kind:"pm_min_version",status:"invalid",allowed:!1,required:r,current:t};if(t===null)return{kind:"pm_min_version",status:"unchecked",allowed:!0,required:r,current:null};let n=xs(t,r);return n===null?{kind:"pm_min_version",status:"unchecked",allowed:!0,required:r,current:t}:n<0?{kind:"pm_min_version",status:"unmet",allowed:!1,required:r,current:t}:{kind:"pm_min_version",status:"ok",allowed:!0,required:r,current:t}}function Ll(e,t,r){if(e==null)return{kind:"pm_max_version",status:"absent",allowed:!0,required:"",current:t};let n=$l(e);if(typeof e!="string"||n.trim().length===0)return{kind:"pm_max_version",status:"invalid",allowed:!1,required:n,current:t};if(/^[<>=~^]/.test(n.trim())||!Jr(n))return{kind:"pm_max_version",status:"invalid",allowed:!1,required:n,current:t};if(t===null)return{kind:"pm_max_version",status:"unchecked",allowed:!0,required:n,current:null};let o=xs(t,n);return o===null?{kind:"pm_max_version",status:"unchecked",allowed:!0,required:n,current:t}:o>0?r==="warn"?{kind:"pm_max_version",status:"exceeded_warn",allowed:!0,required:n,current:t}:{kind:"pm_max_version",status:"exceeded",allowed:!1,required:n,current:t}:{kind:"pm_max_version",status:"ok",allowed:!0,required:n,current:t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d3066947-0087-5732-8511-74a31056b6e1")}catch{}})();var Fl=null,Jg=Object.freeze(Jc()),zl=0;function Zg(e=Date.now()){return zl+=1,`${zl}-${e}`}function Qg(e,t,r){return r.has(e)?!1:t.size===0?!0:t.has(e)}async function eb(e,t){let[r,n]=await Promise.all([wt.realpath(e),wt.realpath(t)]);return ws(r,n)}function tb(e,t=process.cwd()){return{global:bt.join(kd(t),"extensions"),project:bt.join(e,"extensions")}}async function rb(e){try{return(await wt.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).sort((t,r)=>t.localeCompare(r))}catch{return[]}}function nb(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.manifest.name,version:e.manifest.version,entry:e.manifest.entry,priority:e.manifest.priority,entry_path:e.entry_path,manifest_version:e.manifest.manifest_version,pm_min_version:e.manifest.pm_min_version,pm_max_version:e.manifest.pm_max_version,engines:e.manifest.engines,trusted:e.manifest.trusted,provenance:e.manifest.provenance,sandbox_profile:e.manifest.sandbox_profile,permissions:e.manifest.permissions,capabilities:[...e.manifest.capabilities],activation:e.manifest.activation?{commands:[...e.manifest.activation.commands]}:void 0,contributions:e.manifest.contributions??e.contributions};return e.source_package&&(t.source_package=e.source_package),e.source_aliases&&(t.source_aliases=[...e.source_aliases]),t}function Ul(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}async function ob(e){let t=new Map;try{let r=JSON.parse(await wt.readFile(bt.join(e,".managed-extensions.json"),"utf8")),n=ze(r)?.entries;if(!Array.isArray(n))return t;for(let o of n){if(typeof o!="object"||o===null)continue;let i=o,s=Ul(i.source?.package),a=[i.source?.input,i.source?.name,s].map(l=>Ul(l)).filter(l=>l!==void 0),c=ao(i.contributions),d={aliases:[...new Set(a)],...s?{package_name:s}:{},...c?{contributions:c}:{}};typeof i.directory=="string"&&i.directory.trim().length>0&&t.set(`directory:${i.directory.trim()}`,d),typeof i.name=="string"&&i.name.trim().length>0&&t.set(`name:${i.name.trim()}`,d)}}catch{return t}return t}function Hl(e){return[...e].sort((t,r)=>{if(t.manifest.priority!==r.manifest.priority)return t.manifest.priority-r.manifest.priority;let n=t.manifest.name.localeCompare(r.manifest.name);return n!==0?n:t.directory.localeCompare(r.directory)})}function ib(e,t){let r=[...Hl(e),...Hl(t)],n=[];for(let o of r){let i=n.findIndex(s=>s.manifest.name===o.manifest.name);i>=0&&n.splice(i,1),n.push(o)}return n}async function ql(e,t,r,n,o){let i=[],s=[],a=[],c=await rb(t),d=await ob(t);for(let l of c){let u=await cb(e,t,l,r,n,d,o);i.push(u.diagnostic),s.push(...u.warnings),u.candidate&&a.push(u.candidate)}return{diagnostics:i,warnings:s,candidates:a}}function sb(){return{diagnostics:[],warnings:[],candidates:[]}}function Vl(e,t,r,n){return{diagnostic:{layer:e,directory:t,manifest_path:r,name:null,version:null,entry:null,priority:null,entry_path:null,enabled:null,status:"warn"},warnings:[n],candidate:null}}function ab(e,t,r,n,o,i,s,a){let c=Md(e,t,r);Array.isArray(t.legacy_capability_aliases)&&t.legacy_capability_aliases.length>0&&c.push(Pd(e,t.name,t.legacy_capability_aliases));for(let d of xd(t.capabilities))c.push(Dd(e,t.name,d));return n?o||c.push(`extension_entry_missing:${e}:${t.name}`):c.push(`extension_entry_outside_extension:${e}:${t.name}`),i.warning&&c.push(a?i.warning:i.warning.replace("extension_pm_","extension_disabled_pm_")),s.warning&&c.push(a?s.warning:s.warning.replace("extension_pm_","extension_disabled_pm_")),c}async function cb(e,t,r,n,o,i,s){let a=bt.join(t,r),c=bt.join(a,"manifest.json");if(!await ft(c))return Vl(e,r,c,`extension_manifest_missing:${e}:${r}`);let d,l;try{let ae=JSON.parse(await wt.readFile(c,"utf8"));l=ze(ae),d=As(ae)}catch{l=null,d=null}if(!d||!l)return Vl(e,r,c,`extension_manifest_invalid:${e}:${r}`);let u=bt.resolve(a,d.entry),f=ws(a,u),m=f?await ft(u):!1,_=f&&m?await eb(a,u):f,y=Qg(d.name,n,o),w=await ub(e,d),v=await fb(e,d,s),I=ab(e,d,l,_,m,w,v,y),z=_&&m&&w.allowed&&v.allowed,X=i.get(`directory:${r}`)??i.get(`name:${d.name}`);return{diagnostic:{layer:e,directory:r,manifest_path:c,name:d.name,version:d.version,entry:d.entry,priority:d.priority,entry_path:u,enabled:y,status:z?"ok":"warn"},warnings:I,candidate:rl({layer:e,directory:r,manifestPath:c,entryPath:u,manifest:d,sourceIdentity:X,extensionReady:z,enabledForLoad:y})}}async function db(e){let t=tb(e.pmRoot,e.cwd??process.cwd()),r=Fr(e.settings.extensions.enabled),n=Fr(e.settings.extensions.disabled),o=al(e.settings),i=cl(o);if(e.noExtensions)return{disabled_by_flag:!0,roots:t,configured_enabled:r,configured_disabled:n,discovered:[],effective:[],warnings:[...o.warnings],policy:i};let s=new Set(r),a=new Set(n),c=e.ignoreGlobalExtensions===!0?sb():await ql("global",t.global,s,a,o.pmMaxVersionExceededMode.global),d=await ql("project",t.project,s,a,o.pmMaxVersionExceededMode.project),l=[...o.warnings],u=ib(c.candidates,d.candidates),f=[];for(let m of u){let _={layer:m.layer,name:m.manifest.name,trusted:m.manifest.trusted===!0,provenanceVerified:m.manifest.provenance?.verified===!0,sandboxProfile:m.manifest.sandbox_profile,permissions:m.manifest.permissions&&typeof m.manifest.permissions=="object"?{fs_read:m.manifest.permissions.fs_read,fs_write:m.manifest.permissions.fs_write,network:m.manifest.permissions.network,env_read:m.manifest.permissions.env_read,env_write:m.manifest.permissions.env_write,process_spawn:m.manifest.permissions.process_spawn}:void 0},y=ul(o,_);if(y.warning&&l.push(y.warning),!!y.allowed){for(let w of m.manifest.capabilities){let v=fl(o,_,w);v.warning&&l.push(v.warning)}f.push(nb(m))}}return{disabled_by_flag:!1,roots:t,configured_enabled:r,configured_disabled:n,discovered:[...c.diagnostics,...d.diagnostics],effective:f,warnings:[...new Set([...c.warnings,...d.warnings,...l])],policy:i}}function yo(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}async function lb(){try{let e=Bn(import.meta.url,["../../.."]),t=await wt.readFile(bt.join(e,"package.json"),"utf8"),r=JSON.parse(t);return typeof r.version=="string"&&r.version.trim().length>0?r.version.trim():null}catch{return null}}function Gl(){return Fl??=lb(),Fl}function Kl(e,t,r){let n=r.current??"unknown";if(r.kind==="pm_min_version")switch(r.status){case"invalid":return`extension_pm_min_version_invalid:${e}:${t.name}:required=${r.required}`;case"unchecked":return`extension_pm_min_version_unchecked:${e}:${t.name}:required=${r.required}:current=${n}`;case"unmet":return`extension_pm_min_version_unmet:${e}:${t.name}:required=${r.required}:current=${n}`;default:return}switch(r.status){case"invalid":return`extension_pm_max_version_invalid:${e}:${t.name}:allowed=${r.required}`;case"unchecked":return`extension_pm_max_version_unchecked:${e}:${t.name}:allowed=${r.required}:current=${n}`;case"exceeded_warn":return`extension_pm_max_version_exceeded_warn:${e}:${t.name}:allowed=${r.required}:current=${n}`;case"exceeded":return`extension_pm_max_version_exceeded:${e}:${t.name}:allowed=${r.required}:current=${n}`;default:return}}async function ub(e,t){if(t.pm_min_version===void 0)return{allowed:!0};let r=jl(t.pm_min_version,await Gl()),n=Kl(e,t,r);return n?{allowed:r.allowed,warning:n}:{allowed:r.allowed}}async function fb(e,t,r){if(t.pm_max_version===void 0)return{allowed:!0};let n=Ll(t.pm_max_version,await Gl(),r),o=Kl(e,t,n);return o?{allowed:n.allowed,warning:o}:{allowed:n.allowed}}async function Bl(e){try{let t=await wt.stat(e);return`${Math.trunc(t.mtimeMs)}-${t.size}`}catch{return"missing"}}async function mb(e,t){let r=e.entry_path;t.module_graph_snapshot_root&&(r=await hl(t.module_graph_snapshot_root,e));let n=new URL(Xg(r).href);if(!(t.cache_bust===!0||typeof t.reload_token=="string"))return n.href;let[o,i]=await Promise.all([Bl(e.entry_path),Bl(e.manifest_path)]),s=t.reload_token??Zg();return n.searchParams.set("pm_ext_reload",s),n.searchParams.set("pm_ext_entry",o),n.searchParams.set("pm_ext_manifest",i),n.href}async function Kx(e){let t=await db(e),r=[],n=[],o=[...t.warnings];if(t.disabled_by_flag)return{...t,warnings:o,loaded:r,failed:n};let i=typeof e.extensionFilter=="function"?t.effective.filter(e.extensionFilter):t.effective;for(let s of i)try{let a=await import(await mb(s,e));r.push({...s,module:a})}catch(a){o.push(`extension_load_failed:${s.layer}:${s.name}`),n.push({layer:s.layer,name:s.name,entry_path:s.entry_path,error:yo(a)})}return{...t,warnings:o,loaded:r,failed:n}}var Wl=5e3,pb=2147483647;function _b(e){let t={activate:e.activate.bind(e)};if(typeof e.deactivate=="function"){let r=e.deactivate;t.deactivate=r.bind(e)}return t}function Yl(e){let t=ad(e);return t?_b(t):null}async function Yx(e,t,r={}){let n=yb(r?.deactivate_timeout_ms),o=new Set((t?.failed??[]).map(l=>`${l.layer}:${l.name}`)),i=[];for(let l of e.loaded){if(o.has(`${l.layer}:${l.name}`))continue;let u=Yl(l.module);!u||typeof u.deactivate!="function"||i.push({extension:l,deactivate:u.deactivate})}let s=await Promise.all(i.map(async({extension:l,deactivate:u})=>{try{return await hb(u,n),{ok:!0}}catch(f){return{ok:!1,layer:l.layer,name:l.name,error:yo(f)}}})),a=[],c=[],d=0;for(let l of s){if(l.ok){d+=1;continue}a.push(`extension_deactivate_failed:${l.layer}:${l.name}`),c.push({layer:l.layer,name:l.name,error:l.error})}return{deactivated:d,warnings:a,failed:c}}function yb(e){return typeof e!="number"||e<0?Wl:e===0||e===1/0?0:Number.isFinite(e)?Math.min(pb,Math.max(1,Math.floor(e))):Wl}async function hb(e,t){if(t===0){await e();return}let r;try{let n=Promise.resolve().then(()=>e());n.catch(()=>{}),await Promise.race([n,new Promise((o,i)=>{r=setTimeout(()=>{i(new Error(`extension deactivate timed out after ${t}ms`))},t),r.unref?.()})])}finally{clearTimeout(r)}}function gb(e){if(!Array.isArray(e.capabilities))return null;let t=new Set;for(let r of e.capabilities){let n=r.trim().toLowerCase();He(n)&&t.add(n)}return t}function U(e,t,r){let n=gb(e);if(n!==null&&!n.has(t))throw Pe(`${r} requires capability '${t}' in extension manifest capabilities`,{method:r,registration_index:-1,capability:t,missing_capability:t,expected_schema:`"capabilities": [..., "${t}"]`,received:e.capabilities,hint:`Add "${t}" to ${e.name} manifest capabilities, or remove the ${r} registration call.`})}function bb(e){return Object.freeze({name:e.name,layer:e.layer,version:e.version,capabilities:Object.freeze((e.capabilities??[]).filter(t=>xe.includes(t))),pm_min_version:e.pm_min_version,pm_max_version:e.pm_max_version,source_package:e.source_package})}function wb(e){return{layer:e.layer,name:e.name,trusted:e.trusted===!0,provenanceVerified:e.provenance?.verified===!0,sandboxProfile:e.sandbox_profile,permissions:e.permissions&&typeof e.permissions=="object"?{fs_read:e.permissions.fs_read,fs_write:e.permissions.fs_write,network:e.permissions.network,env_read:e.permissions.env_read,env_write:e.permissions.env_write,process_spawn:e.permissions.process_spawn}:void 0}}var Ns=class{extension;hooks;#e;#r;#o;#n;#s;#a;#i;#c;#t;#d;#l;#u;constructor(t,r,n,o,i,s,a,c,d,l,u){this.#e=t,this.extension=bb(t),this.#r=wb(t),this.#o=r,this.#n=n,this.#s=o,this.#a=i,this.#i=s,this.#c=a,this.#t=c,this.#d=d,this.#l=l,this.#u=u,this.registerCommand=this.registerCommand.bind(this),this.registerParser=this.registerParser.bind(this),this.registerPreflight=this.registerPreflight.bind(this),this.registerService=this.registerService.bind(this),this.registerFlags=this.registerFlags.bind(this),this.registerItemFields=this.registerItemFields.bind(this),this.registerItemTypes=this.registerItemTypes.bind(this),this.registerRelationshipKinds=this.registerRelationshipKinds.bind(this),this.registerMigration=this.registerMigration.bind(this),this.registerProfile=this.registerProfile.bind(this),this.registerRenderer=this.registerRenderer.bind(this),this.registerImporter=this.registerImporter.bind(this),this.registerExporter=this.registerExporter.bind(this),this.registerSearchProvider=this.registerSearchProvider.bind(this),this.registerVectorStoreAdapter=this.registerVectorStoreAdapter.bind(this),this.registerAssuranceMeasurementProvider=this.registerAssuranceMeasurementProvider.bind(this),this.hooks={beforeCommand:f=>this.registerBeforeCommand(f),beforeMutation:f=>this.registerBeforeMutation(f),afterCommand:f=>this.registerAfterCommand(f),onWrite:f=>this.registerOnWrite(f),onRead:f=>this.registerOnRead(f),onIndex:f=>this.registerOnIndex(f)}}allowRegistration(t,r,n,o){let i=ml(this.#u,this.#r,t,r,n,o);return i.warning&&this.#d.push(i.warning),i.allowed}registerCommandTrace(t,r,n,o,i){return{method:"registerCommand",registration_index:t==="override"?this.#n.overrides.length:this.#n.handlers.length,command:r,expected_schema:n,received:Br(o),hint:i}}registerCommandOverride(t,r){let n=F(t);if(n.length===0)throw Pe("registerCommand requires a non-empty command name",this.registerCommandTrace("override",t,'registerCommand("<command>", (context) => unknown)',t,"Provide a non-empty command path as the first argument."));if(typeof r!="function"){let o=this.registerCommandTrace("override",n,'registerCommand("<command>", (context) => unknown)',r,"Provide a function as the second registerCommand argument.");throw Pe(`registerCommand requires an override function when command name is provided (command="${n}", registration_index=${o.registration_index})`,o)}this.allowRegistration("commands.override","registerCommand","commands",{command:n})&&this.#n.overrides.push({layer:this.#e.layer,name:this.#e.name,command:n,run:r})}resolveCommandDefinitionRunHandler(t,r){let n=typeof t.run=="function"?t.run:void 0,o=typeof t.handler=="function"?t.handler:void 0;return!n&&o&&this.#d.push(`extension_command_definition_legacy_handler_alias:${this.#e.layer}:${this.#e.name}:${r}`),n??o}registerCommandDefinition(t){if(typeof t!="object"||t===null)throw Pe("registerCommand requires a command definition object",this.registerCommandTrace("definition",void 0,"{ name: string; run: (context) => unknown; }",t,'Use registerCommand({ name: "command path", run: (context) => ... }).'));if(typeof t.name!="string")throw Pe("registerCommand requires a command definition name",this.registerCommandTrace("definition",void 0,"{ name: string; run: (context) => unknown; }",t,"Set command definition.name to a non-empty string command path."));let r=F(t.name);if(r.length===0)throw Pe("registerCommand requires a non-empty command definition name",this.registerCommandTrace("definition",t.name,"{ name: string; run: (context) => unknown; }",t,"Ensure command definition.name contains a non-empty command path."));let n=this.resolveCommandDefinitionRunHandler(t,r);if(typeof n!="function"){let o=this.registerCommandTrace("definition",r,"{ name: string; run: (context) => unknown; }",n,"Define command definition.run as a function.");throw Pe(`registerCommand requires a command definition run handler (command="${r}", registration_index=${o.registration_index})`,o)}try{Qd(t);let o=Cs(r,t.action),i=el(t.read_output,r,o);if(!this.allowRegistration("commands.handler","registerCommand","commands",{command:r,action:o}))return;let s=t.description?.trim(),a=t.intent?.trim(),c=Hr("registerCommand definition.examples",t.examples),d=Hr("registerCommand definition.failure_hints",t.failure_hints),l=Rs(t.arguments);t.flags!==void 0&&(U(this.#e,"schema","registerCommand flags"),this.allowRegistration("schema.flags","registerCommand flags","schema")&&(_o(t.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:r,flags:po("registerCommand definition.flags",t.flags)})));let u={read_output:i,layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:r,action:o,examples:c,failure_hints:d,arguments:l,tier:t.tier??"standard",family:t.family??"extensions"};s&&(u.description=s),a&&(u.intent=a),this.#t.commands.push(u)}catch(o){let i=yo(o),s=this.registerCommandTrace("definition",r,"{ name: string; run: (context) => unknown; action?: string; arguments?: object[]; flags?: object[]; }",t,i),a=Pe(`registerCommand definition metadata invalid (command="${r}", registration_index=${s.registration_index}): ${i}`,s);this.#d.push(`extension_command_quarantined:${this.#e.layer}:${this.#e.name}:${r}`),this.#l.push({layer:this.#e.layer,name:this.#e.name,entry_path:this.#e.entry_path,error:a.message,trace:s});return}this.#n.handlers.push({layer:this.#e.layer,name:this.#e.name,command:r,run:n})}registerCommand(t,r){if(U(this.#e,"commands","registerCommand"),typeof t=="string"){this.registerCommandOverride(t,r);return}this.registerCommandDefinition(t)}registerParser(t,r){if(U(this.#e,"parser","registerParser"),!this.allowRegistration("parser.override","registerParser","parser"))return;let n=F(te("registerParser command",t));Yr("registerParser override",r),this.#s.overrides.push({layer:this.#e.layer,name:this.#e.name,command:n,run:r})}registerPreflight(t){if(U(this.#e,"preflight","registerPreflight"),!this.allowRegistration("preflight.override","registerPreflight","preflight"))return;let r=gl(t);this.#a.overrides.push({layer:this.#e.layer,name:this.#e.name,...r})}registerService(t,r,n={}){U(this.#e,"services","registerService");let o=String(t).trim().toLowerCase();if(!kl(o))throw new TypeError(`registerService service must be one of: ${Bt.join(", ")}`);this.allowRegistration("services.override","registerService","services",{service:o})&&(Yr("registerService override",r),this.#i.overrides.push({layer:this.#e.layer,name:this.#e.name,service:o,run:r,...Ml(n)?{passThrough:!0}:{}}))}registerRenderer(t,r,n={}){if(U(this.#e,"renderers","registerRenderer"),!this.allowRegistration("renderers.override","registerRenderer","renderers"))return;if(typeof r!="function")throw new TypeError("registerRenderer requires a renderer function");let o=String(t).trim().toLowerCase();if(!El(o))throw new Error(`registerRenderer format must be toon|json, received: ${String(t)}`);if(n.resultDiscriminator!==void 0&&typeof n.resultDiscriminator!="function")throw new TypeError("registerRenderer ownership.resultDiscriminator must be a function when provided");let i=[...new Set((n.commands??[]).map(s=>{if(typeof s!="string"||s.trim().length===0)throw new TypeError("registerRenderer ownership.commands must contain non-empty command paths");return F(s)}))];this.#c.overrides.push({layer:this.#e.layer,name:this.#e.name,format:o,run:r,commands:i,...n.resultDiscriminator?{resultDiscriminator:n.resultDiscriminator}:{}})}registerFlags(t,r){if(U(this.#e,"schema","registerFlags"),!this.allowRegistration("schema.flags","registerFlags","schema"))return;let n=F(te("registerFlags targetCommand",t));_o(r);let o=po("registerFlags flags",r);if(o.length===0)throw new TypeError("registerFlags requires at least one flag definition");this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:o})}registerItemFields(t){if(U(this.#e,"schema","registerItemFields"),!this.allowRegistration("schema.itemfields","registerItemFields","schema"))return;Cl(t);let r=Kr("registerItemFields fields",t);if(r.length===0)throw new TypeError("registerItemFields requires at least one field definition");this.#t.item_fields.push({layer:this.#e.layer,name:this.#e.name,fields:r})}registerItemTypes(t){if(U(this.#e,"schema","registerItemTypes"),!this.allowRegistration("schema.itemtypes","registerItemTypes","schema"))return;Rl(t);let r=Kr("registerItemTypes types",t);if(r.length===0)throw new TypeError("registerItemTypes requires at least one type definition");this.#t.item_types.push({layer:this.#e.layer,name:this.#e.name,types:r})}registerRelationshipKinds(t){if(U(this.#e,"schema","registerRelationshipKinds"),!this.allowRegistration("schema.relationshipkinds","registerRelationshipKinds","schema"))return;if(!Array.isArray(t))throw new TypeError("registerRelationshipKinds definitions requires an array of object definitions");if(t.length===0)throw new TypeError("registerRelationshipKinds requires at least one definition");let r=Vi();for(let o of this.#t.relationship_kinds)for(let i of o.definitions)r.register(i);let n=t.map(o=>(r.register(o),r.require(o.kind)));this.#t.relationship_kinds.push({layer:this.#e.layer,name:this.#e.name,definitions:n})}registerMigration(t){if(U(this.#e,"schema","registerMigration"),!this.allowRegistration("schema.migrations","registerMigration","schema"))return;xl(t);let r=Gr("registerMigration definition",t);this.#t.migrations.push(Xr({layer:this.#e.layer,name:this.#e.name,definition:er("registerMigration definition",t)},r))}registerProfile(t){if(U(this.#e,"schema","registerProfile"),!this.allowRegistration("schema.profiles","registerProfile","schema"))return;let r=Wr(t);Dl(r),this.#t.profiles.push({layer:this.#e.layer,name:this.#e.name,profile:Pl(r)})}registerImportExportCommandFlags(t,r,n){n.flags!==void 0&&(U(this.#e,"schema",`${t} options.flags`),this.allowRegistration("schema.flags",`${t} options.flags`,"schema")&&(_o(n.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:r,flags:po(`${t} options.flags`,n.flags)})))}applyImportExportCommandMetadata(t,r,n){if(n!==void 0&&(typeof n!="object"||n===null||Array.isArray(n)))throw new TypeError(`${t} options must be an object when provided`);let o=`${t==="registerImporter"?"Import":"Export"} items with the registered extension adapter.`,i=[{name:"file",required:!1,description:"Optional input or output file path."}],s={...n,description:n?.description??o,arguments:n?.arguments??i},a=tl(t,s,n?.description!==void 0);V(`${t} options.action`,s.action),V(`${t} options.description`,s.description),V(`${t} options.intent`,s.intent);let c=Cs(r,s.action),d=Hr(`${t} options.examples`,s.examples),l=Hr(`${t} options.failure_hints`,s.failure_hints),u=Rs(s.arguments);this.registerImportExportCommandFlags(t,r,s);let f={layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:r,action:c,examples:d,failure_hints:l,arguments:u},m=s.description?.trim();m&&(f.description=m);let _=s.intent?.trim();return _&&(f.intent=_),this.#t.commands.push(f),a}registerImporter(t,r,n){if(U(this.#e,"importers","registerImporter"),!this.allowRegistration("importers.importer","registerImporter","importers"))return;let o=Is(te("registerImporter name",t));Yr("registerImporter importer",r);let i=Ts(o,"import");this.applyImportExportCommandMetadata("registerImporter",i,n),this.#t.importers.push({layer:this.#e.layer,name:this.#e.name,importer:o}),this.#n.handlers.push({layer:this.#e.layer,name:this.#e.name,command:i,run:async s=>r(Es(s,o,"import"))})}registerExporter(t,r,n){if(U(this.#e,"importers","registerExporter"),!this.allowRegistration("importers.exporter","registerExporter","importers"))return;let o=Is(te("registerExporter name",t));Yr("registerExporter exporter",r);let i=Ts(o,"export"),s=this.applyImportExportCommandMetadata("registerExporter",i,n);this.#t.exporters.push({layer:this.#e.layer,name:this.#e.name,exporter:o,...s===void 0?{}:{output:s}}),this.#n.handlers.push({layer:this.#e.layer,name:this.#e.name,command:i,run:async a=>{let c=await r(Es(a,o,"export"));return s?.receipt==="suppress"&&!Vn(c)?od(c):c}})}registerSearchProvider(t){if(U(this.#e,"search","registerSearchProvider"),!this.allowRegistration("search.provider","registerSearchProvider","search"))return;let r=Gr("registerSearchProvider provider",t);this.#t.search_providers.push(Xr({layer:this.#e.layer,name:this.#e.name,definition:er("registerSearchProvider provider",t)},r))}registerVectorStoreAdapter(t){if(U(this.#e,"search","registerVectorStoreAdapter"),!this.allowRegistration("search.vectorstore","registerVectorStoreAdapter","search"))return;let r=Gr("registerVectorStoreAdapter adapter",t);this.#t.vector_store_adapters.push(Xr({layer:this.#e.layer,name:this.#e.name,definition:er("registerVectorStoreAdapter adapter",t)},r))}registerAssuranceMeasurementProvider(t){if(U(this.#e,"services","registerAssuranceMeasurementProvider"),!this.allowRegistration("services.assuranceprovider","registerAssuranceMeasurementProvider","services"))return;if(Il(t),t.network&&this.#e.permissions?.network!==!0)throw new TypeError("registerAssuranceMeasurementProvider network provider requires permissions.network=true");let r=Gr("registerAssuranceMeasurementProvider provider",t);this.#t.assurance_providers.push(Xr({layer:this.#e.layer,name:this.#e.name,network_permission:this.#e.permissions?.network===!0,definition:er("registerAssuranceMeasurementProvider provider",t)},r))}registerBeforeCommand(t){U(this.#e,"hooks","api.hooks.beforeCommand"),this.allowRegistration("hooks.beforecommand","api.hooks.beforeCommand","hooks")&&(gt("beforeCommand",t),this.#o.beforeCommand.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerBeforeMutation(t){U(this.#e,"hooks","api.hooks.beforeMutation"),this.allowRegistration("hooks.beforemutation","api.hooks.beforeMutation","hooks")&&(gt("beforeMutation",t),this.#o.beforeMutation.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerAfterCommand(t){U(this.#e,"hooks","api.hooks.afterCommand"),this.allowRegistration("hooks.aftercommand","api.hooks.afterCommand","hooks")&&(gt("afterCommand",t),this.#o.afterCommand.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnWrite(t){U(this.#e,"hooks","api.hooks.onWrite"),this.allowRegistration("hooks.onwrite","api.hooks.onWrite","hooks")&&(gt("onWrite",t),this.#o.onWrite.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnRead(t){U(this.#e,"hooks","api.hooks.onRead"),this.allowRegistration("hooks.onread","api.hooks.onRead","hooks")&&(gt("onRead",t),this.#o.onRead.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnIndex(t){U(this.#e,"hooks","api.hooks.onIndex"),this.allowRegistration("hooks.onindex","api.hooks.onIndex","hooks")&&(gt("onIndex",t),this.#o.onIndex.push({layer:this.#e.layer,name:this.#e.name,run:t}))}};function vb(e,t,r,n,o,i,s,a,c,d,l){return new Ns(e,t,r,n,o,i,s,a,c,d,l)}function Eb(e){let t=e.commands.length,r=e.flags.reduce((s,a)=>s+a.flags.length,0),n=e.item_fields.reduce((s,a)=>s+a.fields.length,0),o=e.item_types.reduce((s,a)=>s+a.types.length,0),i=(e.relationship_kinds??[]).reduce((s,a)=>s+a.definitions.length,0);return{commands:t,flags:r,item_fields:n,item_types:o,...i>0?{relationship_kinds:i}:{},migrations:e.migrations.length,profiles:e.profiles.length,importers:e.importers.length,exporters:e.exporters.length,search_providers:e.search_providers.length,vector_store_adapters:e.vector_store_adapters.length,...(e.assurance_providers?.length??0)>0?{assurance_providers:e.assurance_providers.length}:{}}}function kb(e){let t=[],r=(i,s)=>{let a=new Map;for(let c of i){let d=a.get(c.command)??[];d.push(c),a.set(c.command,d)}for(let c of[...a.keys()].sort((d,l)=>d.localeCompare(l))){let d=a.get(c);if(d.length<=1)continue;let l=d[d.length-1];for(let u of d.slice(0,-1))t.push(`${s}:${c}:${l.layer}:${l.name}:${u.layer}:${u.name}`)}};r(e.handlers,"extension_command_handler_collision"),r(e.overrides,"extension_command_override_collision");let n=new Set(e.handlers.map(i=>i.command)),o=[...new Set(e.overrides.map(i=>i.command))].filter(i=>n.has(i));o.sort((i,s)=>i.localeCompare(s));for(let i of o){let s=e.handlers.filter(c=>c.command===i),a=e.overrides.filter(c=>c.command===i);for(let c of a)for(let d of s)t.push(`extension_command_override_handler_overlap:${i}:${c.layer}:${c.name}:${d.layer}:${d.name}`)}return t}function Sb(e){let t=new Map;for(let n of e.overrides){let o=t.get(n.format)??[];o.push(n),t.set(n.format,o)}let r=[];for(let n of[...t.keys()].sort((o,i)=>o.localeCompare(i))){let o=t.get(n);if(o.length<=1)continue;let i=o[o.length-1];for(let s of o.slice(0,-1))i.commands?.length&&s.commands?.length&&!s.commands.some(a=>i.commands?.includes(a))||r.push(`extension_renderer_collision:${n}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return r}function Ob(e){let t=[],r=new Map;for(let n of e.overrides){let o=r.get(n.command)??[];o.push(n),r.set(n.command,o)}for(let n of[...r.keys()].sort((o,i)=>o.localeCompare(i))){let o=r.get(n);if(o.length<=1)continue;let i=o[o.length-1];for(let s of o.slice(0,-1))t.push(`extension_parser_override_collision:${n}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return t}var Ab=new Set(["output_format"]);function Ib(e){let t=[],r=new Map;for(let n of e.overrides){let o=r.get(n.service)??[];o.push(n),r.set(n.service,o)}for(let n of[...r.keys()].sort((o,i)=>o.localeCompare(i))){let o=r.get(n);if(o.length<=1||Ab.has(n))continue;let i=o[o.length-1];for(let s of o.slice(0,-1))t.push(`extension_service_override_collision:${n}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return t}async function Xx(e){let t=dl(e.policy??Jg),r=zr(),n=ts(),o=rs(),i=ns(),s=os(),a=is(),c=ss(),d=[],l=[];for(let m of e.loaded){let _=Yl(m.module);if(!_)continue;let y=d.length,w=Jd({hooks:r,commands:n,parsers:o,preflight:i,services:s,renderers:a,registrations:c});try{await _.activate(vb(m,r,n,o,i,s,a,c,l,d,t)),d.length>y&&(w(),l.push(`extension_activation_rolled_back:${m.layer}:${m.name}`))}catch(v){w(),l.push(`extension_activate_failed:${m.layer}:${m.name}`);let I=Ol(v);d.push({layer:m.layer,name:m.name,entry_path:m.entry_path,error:yo(v),trace:I})}}let u=[...kb(n),...Ob(o),...bl(i),...Ib(s),...Sb(a)],f=[...new Set([...l,...u])];return{hooks:r,commands:n,parsers:o,preflight:i,services:s,renderers:a,registrations:c,failed:d,warnings:f,hook_counts:{before_command:r.beforeCommand.length,before_mutation:r.beforeMutation.length,after_command:r.afterCommand.length,on_write:r.onWrite.length,on_read:r.onRead.length,on_index:r.onIndex.length},command_override_count:n.overrides.length,command_handler_count:n.handlers.length,parser_override_count:o.overrides.length,preflight_override_count:i.overrides.length,service_override_count:s.overrides.length,renderer_override_count:a.overrides.length,registration_counts:Eb(c)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b1a38f8c-8f65-59e2-bddf-ed0606a0f0b5")}catch{}})();function eN(e){return{...e,hooks:zr(),profileEnabled:!!e.globalOptions.profile,migrationBlockers:[]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4da25248-2914-5bc5-aa42-87f677ef4ea8")}catch{}})();function rN(){let e=Promise.resolve(),t=new Set;return{async read(r){let n=e,o,i=new Promise(s=>{o=s});t.add(i),await n;try{return await r()}finally{t.delete(i),o()}},write(r){let n=Promise.all([e,...t]).then(()=>r());return e=n.then(()=>{},()=>{}),n}}}function Tb(){let e=Promise.resolve(),t=0,r=[],n=()=>{if(t!==0)return;let o=r.splice(0);for(let i of o)i()};return{enqueue(o){t++;let i=e.then(()=>o());return e=i.then(()=>{},()=>{}).finally(()=>{t--,n()}),i},idle(){return t===0?Promise.resolve():new Promise(o=>r.push(o))}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d8844150-afb4-5f2e-a005-4cfb8482660c")}catch{}})();var Cb={commands:["registerCommand","command override","command handler"],renderers:["registerRenderer"],hooks:["hooks.beforeCommand","hooks.beforeMutation","hooks.afterCommand","hooks.onWrite","hooks.onRead","hooks.onIndex"],schema:["registerFlags","registerItemFields","registerItemTypes","registerRelationshipKinds","registerMigration","registerProfile"],importers:["registerImporter","registerExporter"],search:["registerSearchProvider","registerVectorStoreAdapter"],parser:["registerParser"],preflight:["registerPreflight"],services:["registerService","registerAssuranceMeasurementProvider"]},Xl=":";function Jl(e,t){return`${e}${Xl}${Ds(t)}`}function Rb(e){return e.slice(e.indexOf(Xl)+1)}function Ds(e){return e.trim().toLowerCase()}function xb(e){if(!Array.isArray(e))return[];let t=new Set;for(let r of e){let n=Rd(r);n!==null&&t.add(n)}return[...t].sort((r,n)=>r.localeCompare(n))}function Zl(e){let t=new Map,r=(l,u)=>{for(let f of l){let m=Jl(f.layer,f.name),_=t.get(m);_===void 0&&(_=new Set,t.set(m,_)),_.add(u)}},{registrations:n,commands:o,parsers:i,preflight:s,services:a,renderers:c,hooks:d}=e;return r(n.commands,"commands"),r(o.overrides,"commands"),r(o.handlers,"commands"),r(n.flags,"schema"),r(n.item_fields,"schema"),r(n.item_types,"schema"),r(n.relationship_kinds??[],"schema"),r(n.migrations,"schema"),r(n.profiles,"schema"),r(n.importers,"importers"),r(n.exporters,"importers"),r(n.search_providers,"search"),r(n.vector_store_adapters,"search"),r(i.overrides,"parser"),r(s.overrides,"preflight"),r(a.overrides,"services"),r(n.assurance_providers??[],"services"),r(c.overrides,"renderers"),r(d.beforeCommand,"hooks"),r(d.beforeMutation,"hooks"),r(d.afterCommand,"hooks"),r(d.onWrite,"hooks"),r(d.onRead,"hooks"),r(d.onIndex,"hooks"),t}function Nb(e,t={}){let r=Zl(e),n=new Set;t.extensionName!==void 0&&n.add(Ds(t.extensionName));for(let i of t.extensionNames??[])n.add(Ds(i));let o=new Set;for(let[i,s]of r)if(!(n.size>0&&!n.has(Rb(i))))for(let a of s)o.add(a);return[...o].sort((i,s)=>i.localeCompare(s))}function Db(e,t){let r=Zl(t),n=[];for(let o of e){let i=xb(o.capabilities);if(i.length===0)continue;let s=r.get(Jl(o.layer,o.name))??new Set,a=[...s].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>!s.has(d));n.push({layer:o.layer,name:o.name,declared:i,used:a,unused:c})}return n}import{existsSync as Pb}from"node:fs";import{AsyncLocalStorage as Mb}from"node:async_hooks";import Me from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7c2e7a35-cbf9-5bb6-abfd-f1ae75c6afc2")}catch{}})();var $e=null,tr=null,Zr=null,Qr=null,rr=null,en=null,tn=null,Be=null,go,ho=[],eu=new Mb;function M(){return eu.getStore()}function lN(e){return eu.run({hooks:null,commands:null,parsers:null,preflight:null,services:null,renderers:null,registrations:null,commandContext:null,commandResult:void 0,affectedItems:[]},e)}var $b=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function Ql(e){let t=Me.resolve(e);for(;;){if(Pb(Me.join(t,".git")))return t;let r=Me.dirname(t);if(r===t)return;t=r}}function bo(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||process.cwd(),r=Ql(t)??Me.resolve(t),n=Ql(r);if(!e)return{source_workspace_root:r,...n?{repo_root:n}:{}};let o=Me.relative(r,Me.resolve(e)),i=o.length>0&&!o.startsWith(`..${Me.sep}`)&&o!==".."&&!Me.isAbsolute(o);return{source_workspace_root:r,...n?{repo_root:n}:{},...i?{pm_root_rel:o.split(Me.sep).join("/")}:{}}}function uN(e){let t=M();if(t){t.hooks=e;return}$e=e}function fN(e){let t=M();if(t){t.commands=e;return}tr=e}function mN(e){let t=M();if(t){t.parsers=e;return}Zr=e}function pN(e){let t=M();if(t){t.preflight=e;return}Qr=e}function _N(e){let t=M();if(t){t.services=e;return}rr=e}function yN(e){let t=M();if(t){t.renderers=e;return}en=e}function hN(e){let t=M();if(t){t.registrations=e;return}tn=e}function tu(){let e=M();return e?e.registrations:tn}function gN(){let e=M();if(e){e.hooks=null,e.commands=null,e.parsers=null,e.preflight=null,e.services=null,e.renderers=null,e.registrations=null,e.commandContext=null,e.commandResult=null,e.affectedItems=[];return}$e=null,tr=null,Zr=null,Qr=null,rr=null,en=null,tn=null,Be=null,go=null}function bN(e){let t=e?{...e,...bo(e.pm_root)}:null,r=M();if(r){r.commandContext=t;return}Be=t}function ru(){let e=M(),t=e?e.commandContext:Be;return t?{...t,args:[...t.args],options:t.options?{...t.options}:{},global:t.global?{...t.global}:void 0}:null}function wN(e){let t=M()??{commandContext:Be,hooks:$e,commands:tr,parsers:Zr,preflight:Qr,services:rr,renderers:en,registrations:tn};return t.commandContext?.command!==e||[t.hooks,t.preflight,t.services,t.renderers].some(r=>Object.values(r??{}).some(n=>n.length>0))||[t.commands,t.parsers].some(r=>Object.values(r??{}).some(n=>n.some(o=>o.command===e)))?!1:!Object.entries(t.registrations??{}).some(([r,n])=>["migrations","search_providers","vector_store_adapters","assurance_providers"].includes(r)&&n.length>0)}function wo(e){let t=M();if(t){t.commandResult=e;return}go=e}function vN(){let e=M();return e?e.commandResult:go}function EN(e){if(!e)return;let t=M();t?t.affectedItems.push(e):ho.push(e)}function kN(e,t){if(!e||!e.id)return{};let r={id:e.id,type:e.type,status:e.status};if(!Array.isArray(t))return r;let n=e;for(let o of t){if(typeof o!="string")continue;let i=o.startsWith("unset:")?o.slice(6):o;i==="id"||i==="type"||i==="status"||$b.has(i)||Object.hasOwn(n,i)&&n[i]!==void 0&&(r[i]=n[i])}return r}function SN(){let e=M(),t=e?.affectedItems??ho;if(t.length===0)return;let r=t;return e?e.affectedItems=[]:ho=[],r}function ON(){let e=M();if(e){e.hooks=null,e.commands=null,e.parsers=null,e.preflight=null,e.services=null,e.renderers=null,e.registrations=null,e.commandContext=null,e.commandResult=void 0,e.affectedItems=[];return}$e=null,tr=null,Zr=null,Qr=null,rr=null,en=null,tn=null,Be=null,go=void 0,ho=[]}async function vo(e){let t=M(),r=t?t.hooks:$e;return r?ls(r,e):[]}async function AN(e){let t=M(),r=t?t.hooks:$e;r&&await ds(r,e)}async function nr(e){let t=M(),r=t?t.hooks:$e;return r?us(r,e):[]}function IN(){let e=M();return((e?e.hooks:$e)?.onRead?.length??0)>0}async function TN(e){let t=M(),r=t?t.hooks:$e;return r?fs(r,e):[]}function nu(e){let t=M(),r=t?t.commands:tr,n=t?t.commandContext:Be;return!r||!n?{overridden:!1,result:e,warnings:[]}:gs(r,{command:n.command,args:[...n.args],options:n.options?{...n.options}:{},global:n.global?{...n.global}:void 0,pm_root:n.pm_root,source_workspace_root:n.source_workspace_root,repo_root:n.repo_root,pm_root_rel:n.pm_root_rel,result:e})}async function CN(e){let t=M(),r=t?t.commands:tr;return r?ms(r,{...e,...bo(e.pm_root)}):{handled:!1,result:null,warnings:[]}}async function RN(e){let t=M(),r=t?t.parsers:Zr;return r?ps(r,{...e,...bo(e.pm_root)}):{overridden:!1,context:{command:e.command,args:[...e.args],options:{...e.options},global:{...e.global},pm_root:e.pm_root},warnings:[]}}async function xN(e){let t=M(),r=t?t.preflight:Qr;return r?_s(r,{...e,...bo(e.pm_root)}):{overridden:!1,context:{command:e.command,args:[...e.args],options:{...e.options},global:{...e.global},pm_root:e.pm_root},decision:{...e.decision},warnings:[]}}function ou(e,t){let r=M(),n=r?r.renderers:en,o=r?r.commandContext:Be;return n?bs(n,{format:e,command:o?.command,args:o?[...o.args]:[],options:o?.options?{...o.options}:{},global:o?.global?{...o.global}:void 0,pm_root:o?.pm_root,source_workspace_root:o?.source_workspace_root,repo_root:o?.repo_root,pm_root_rel:o?.pm_root_rel,result:t}):{overridden:!1,rendered:null,warnings:[]}}function iu(e,t){let r=M(),n=r?r.commandContext:Be;return{service:e,command:n?.command,args:n?[...n.args]:[],options:n?.options?{...n.options}:{},global:n?.global?{...n.global}:void 0,pm_root:n?.pm_root,source_workspace_root:n?.source_workspace_root,repo_root:n?.repo_root,pm_root_rel:n?.pm_root_rel,payload:t}}async function or(e,t){let r=M(),n=r?r.services:rr;return n?hs(n,iu(e,t)):{handled:!1,result:t,warnings:[]}}function Ps(e,t){let r=M(),n=r?r.services:rr;return n?ys(n,iu(e,t)):{handled:!1,result:t,warnings:[]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4a7b042c-7fb8-57a5-8f94-de44f82d7589")}catch{}})();function jb(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function We(e,t){let r=e.slice(0,t),n=r.charCodeAt(r.length-1),o=e.charCodeAt(r.length);return n>=55296&&n<=56319&&o>=56320&&o<=57343?r.slice(0,-1):r}function jN(e){return jb(e).split(/[^a-z0-9]+/).filter(t=>t.length>0)}function LN(e,t){if(e.length===0&&t.length===0)return 1;if(e.length===0||t.length===0)return 0;let r=new Set(e),n=new Set(t),o=0;for(let s of r)n.has(s)&&(o+=1);let i=new Set([...r,...n]).size;return o/i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3a66ccfd-51fb-5d4a-b9cd-257c49997d52")}catch{}})();var cu=new WeakMap;function HN(e,t){cu.set(e,new Set(t))}var Eo='.row_contract.row_keys[] as $key | getpath($key | split(".")) | if type == "array" then .[] else if type == "object" then to_entries[] else empty end end',Lb={context:{row_keys:["high_level","low_level"],fields:"supported"},get:{row_keys:["children"],fields:"supported"},list:{row_keys:["items"],fields:"supported"},next:{row_keys:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],fields:"unsupported"},search:{row_keys:["items"],fields:"supported"},activity:{row_keys:["activity_digest","compact_activity","provenance_activity","activity"],fields:"unsupported"},history:{row_keys:["compact_history","provenance_history","history","diff"],fields:"unsupported"},deps:{row_keys:["graph.nodes","graph.edges","context.nodes","context.edges"],fields:"unsupported"},health:{row_keys:["checks"],fields:"unsupported"},aggregate:{row_keys:["groups"],fields:"unsupported"},duplicates:{row_keys:["clusters"],fields:"unsupported"},stats:{row_keys:["by_type","by_status"],fields:"unsupported"},comments:{row_keys:["comments"],fields:"unsupported"},notes:{row_keys:["notes"],fields:"unsupported"},learnings:{row_keys:["learnings"],fields:"unsupported"},files:{row_keys:["files"],fields:"unsupported"},docs:{row_keys:["docs"],fields:"unsupported"},validate:{row_keys:["checks","warnings"],fields:"unsupported"},contracts:{row_keys:["command_summaries","commands"],fields:"unsupported"}},Fb=[{command:"activity",complete_mode:"full",omissions_by_mode:{digest:[{name:"event_rows",restore_with:"--raw"}],compact:[{name:"provenance",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}},{command:"history",complete_mode:"full",omissions_by_mode:{compact:[{name:"raw_history",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}}];function qN(e,t,r){if(e&&t)throw new g(`${r} cannot be combined with --full`,h.USAGE)}function Ae(e,t=new Set){let r=e.filter(n=>!t.has(n.name)).map(n=>({...n}));return{has_omissions:r.length>0,omitted_field_group_count:r.length,omitted_field_groups:r}}function VN(e,t){let r=Fb.find(o=>o.command===e);if(r===void 0)throw new TypeError(`Unknown mode-paired output command: ${e}`);if(t===r.complete_mode)return Ae([]);let n=r.omissions_by_mode[t];if(n===void 0)throw new TypeError(`Unknown ${e} output mode: ${t}`);return Ae(n)}var zb=[{name:"hierarchy",restore_with:"--section hierarchy"},{name:"activity",restore_with:"--section activity"},{name:"progress",restore_with:"--section progress"},{name:"blockers",restore_with:"--section blockers"},{name:"recently_created",restore_with:"--section recently_created"},{name:"unparented",restore_with:"--section unparented"},{name:"files",restore_with:"--section files"},{name:"workload",restore_with:"--section workload"},{name:"staleness",restore_with:"--section staleness"},{name:"tests",restore_with:"--section tests"}];function re(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Ub=new Set([void 0,"tabular_when_uniform"]),Hb=new Set(["collection","none"]),qb=new Set(["supported","unsupported"]);function su(e,t){return Array.isArray(e)&&(t||e.length>0)&&e.every(r=>typeof r=="string"&&r.length>0)&&new Set(e).size===e.length}function Vb(e){return re(e)&&typeof e.command=="string"&&e.command.trim().length>0&&Hb.has(e.row_kind)&&su(e.row_keys,!0)&&(e.continuation_row_keys===void 0||su(e.continuation_row_keys,!1))&&qb.has(e.fields)&&Ub.has(e.toon_encoding)&&(e.row_kind==="collection"?e.row_keys.length>0&&typeof e.jq_selector=="string"&&e.jq_selector.trim().length>0:e.row_keys.length===0&&e.jq_selector===void 0)}var Bb={ancestors:["ids"],descendants:["ids"],predecessors:["ids"],successors:["ids"],paths:["paths"],impact:["affected"],audit:["findings"],communities:["communities"],redundancy:["redundant"],dominators:["bottlenecks"],slack:["rows"],centrality:["rows"],articulation:["articulation_points","bridges"],plan:["steps"]},Wb={context:["sections_included","high_level","low_level"],get:["item"],list:["items","projection"],next:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items","projection"],activity:["activity_digest","compact_activity","provenance_activity","activity"],history:["compact_history","provenance_history","history","diff"],deps:["tree","graph","projection"],health:["checks"],aggregate:["groups"],duplicates:["clusters"],stats:["totals","by_type","by_status"],comments:["comments"],notes:["notes"],learnings:["learnings"],files:["files"],docs:["docs"],validate:["checks","warnings"],contracts:["command_summaries","commands","selected"]};function Gb(e,t){let r=e.trim().toLowerCase().split(/\s+/u,1)[0],n=r?.startsWith("list-")?"list":r;if(n==="graph"){let s=typeof t.subcommand=="string"?t.subcommand:"";if(s.length===0)return;let a=Bb[s];if(a===void 0)return;let c=a.filter(d=>Array.isArray(t[d])||re(t[d]));return{command:"graph",row_kind:c.length>0?"collection":"none",row_keys:c,fields:"unsupported",...c.length>0?{jq_selector:Eo}:{},toon_encoding:"tabular_when_uniform"}}let o=Lb[n],i=Wb[n];return o===void 0||i===void 0||!i.some(s=>Object.hasOwn(t,s))?void 0:(()=>{let s=o.row_keys.filter(a=>{let c=a.split(".").reduce((d,l)=>re(d)?d[l]:void 0,t);return Array.isArray(c)||re(c)});return{command:n,row_kind:s.length>0?"collection":"none",row_keys:s,fields:o.fields,...s.length>0?{jq_selector:Eo}:{},toon_encoding:"tabular_when_uniform"}})()}function Kb(e){if(!re(e.projection)||typeof e.projection.mode!="string"||e.projection.mode.trim().length===0)return;let t=e.projection.declared_field_groups,r=e.projection.included_field_groups;if(!Array.isArray(t)||!Array.isArray(r))return;let n=t.filter(s=>re(s)&&typeof s.name=="string"&&s.name.trim().length>0&&typeof s.restore_with=="string"&&s.restore_with.trim().length>0),o=r.filter(s=>typeof s=="string");if(n.length!==t.length||o.length!==r.length)return;let i=new Set(n.map(s=>s.name));if(!(i.size!==n.length||new Set(o).size!==o.length||o.some(s=>!i.has(s))))return Ae(n,new Set(o))}function Yb(e){if(!Array.isArray(e.sections_included))return;let t=Ae(zb,new Set(e.sections_included.filter(r=>typeof r=="string")));return re(e.summary)&&e.summary.scope==="matching_items"&&(t.summary_scope="matching_items"),t}function Xb(e,t,r){return e==="dependency_provenance"?!1:Object.hasOwn(t,e)||(e==="reminders"||e==="events")&&re(r.schedule)&&Object.hasOwn(r.schedule,e)||["files","tests","docs"].includes(e)&&re(r.linked)&&Array.isArray(r.linked[e])&&r.linked[e].length>0}function Jb(e){if(!re(e.item))return;let t=e.item,r=["comments","notes","learnings","files","tests","docs","reminders","events"],n=["body","children","claim_state","linked","schedule"],o=cu.get(e),i=a=>r.includes(a)||a==="body"||a==="dependency_provenance"?t:e,s=["body",...r,...n.slice(1),...o?.has("dependency_provenance")?["dependency_provenance"]:[],...o?.has("blockers")||Object.hasOwn(e,"blockers")?["blockers"]:[]].filter(a=>o===void 0||o.has(a)||Object.hasOwn(i(a),a)).map(a=>({name:a,restore_with:a==="blockers"?"--full":a==="dependency_provenance"?"--fields dependencies":`--fields ${a}`}));return Ae(s,new Set(s.flatMap(({name:a})=>Xb(a,i(a),e)?[a]:[])))}function au(e){if(re(e.projection))return Ae([{name:"full_item_fields",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_item_fields"]:[]))}function Zb(e){if(!re(e.projection))return Ae([]);if(typeof e.projection.mode=="string")return Ae([{name:"full_check_details",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_check_details"]:[]))}function Qb(e){if(!(!re(e.selected)||typeof e.selected.summary!="boolean"))return Ae([{name:"full_contract_catalog",restore_with:"--full"}],new Set(e.selected.summary?[]:["full_contract_catalog"]))}function ew(e,t){let r=Kb(t);if(r!==void 0)return r;let[n]=e.split(/\s+/u,1);if(n==="context")return Yb(t);if(n==="get")return Jb(t);if(n==="list"||n.startsWith("list-"))return au(t);if(n==="search")return au(t)??Ae([{name:"projection_metadata",restore_with:"--full"}]);if(n==="health")return Zb(t);if(n==="contracts")return Qb(t)}function du(e,t){if(e===void 0||!re(t))return t;let r=ew(e,t),n=t.row_contract,o=Vb(n)?n:Gb(e,t),i=o!==void 0?{...t,row_contract:o}:Object.hasOwn(t,"row_contract")?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="row_contract")):t;return re(i.omission_receipt)||r===void 0?i:{...i,omission_receipt:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="86412887-5659-5892-beaa-bdd15a02ff4c")}catch{}})();var lu=e=>{let t='"',r=0;for(let n of e){if(n==="\\"){r+=1;continue}t+="\\".repeat(n==='"'?r*2+1:r),t+=n,r=0}return`${t}${"\\".repeat(r*2)}"`},uu=(e,t=process.platform)=>(t==="win32"?/^[A-Za-z0-9._:/\\@=-]+$/:/^[A-Za-z0-9._:/@=-]+$/).test(e)?e:t==="win32"?lu(e):`"${e.replace(/(["\\$`])/g,"\\$1")}"`,ir=(e,t=process.platform)=>{let r=e.map(n=>uu(n,t)).join(" ");return r.length>0?`pm ${r}`:"pm"};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7607f0d2-6e95-5b85-9bc2-18f643a64171")}catch{}})();var fu=new Set(["--pm-path","--path","--author","--output-include","--output-limit","--output-budget","--output-format","--format","--output-session","--output-cursor"]),tw=new Set(["--no-extensions","--no-pager","--json","--quiet","--lean","--token-accounting","--output-row-contract","--all"]);function rw(e){let t=e.indexOf("=");return t>0&&fu.has(e.slice(0,t))}function nw(e,t){return typeof t!="string"?!1:e==="--path"||e==="--pm-path"||!t.startsWith("-")}function ko(e){for(let t=0;t<e.length;t+=1){let r=e[t];if(r==="--")return;if(fu.has(r)){t+=nw(r,e[t+1])?1:0;continue}if(!(rw(r)||tw.has(r)||r==="--profile"||r==="--id-only"||r==="--explain")&&!r.startsWith("-"))return t}}function GN(e){let t=ko(e);return t===void 0?void 0:e[t].trim().toLowerCase()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="98cde1d6-d5dd-56b9-89f9-51f5d08221d1")}catch{}})();var ow=new Set(["--literal","--regex","--replacement"]);function iw(e){let t=ko(e);if(t===void 0)return!1;if(e[t]==="history-redact")return!0;if(e[t]!=="history")return!1;let r=e.slice(t+1),n=ko(r);return n!==void 0&&r[n]==="redact"}function JN(e){if(!iw(e))return[...e];let t=[],r=!1;for(let n of e){if(r){t.push("[redacted]"),r=!1;continue}r=!1;let o=n.indexOf("="),i=o>=0?n.slice(0,o):n;if(!ow.has(i)){t.push(n);continue}if(o>=0){t.push(`${i}=[redacted]`);continue}t.push(i),r=!0}return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b6db58d1-5d89-56b2-adee-13e985ebc675")}catch{}})();var sw=new Set(["applied_bound","completeness","budget_retention_policy","continuation_contract","continuation_kind","continuation_path","filters","omission_receipt","output_budget_truncation","projection","read_output","read_session","row_contract","sorting"]);function J(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function mu(e,t){let r=e;for(let n of t.split("."))if(Array.isArray(r)){if(!/^\d+$/u.test(n))return;r=r[Number(n)]}else{if(!J(r))return;r=r[n]}return r}function Ms(e,t,r){let n=t.split("."),o=(i,s)=>{if(s===n.length)return r;let a=n[s];if(Array.isArray(i)){let d=Number(a),l=[...i];return l[d]=o(i[d],s+1),l}let c=i;return{...c,[a]:o(c[a],s+1)}};return o(e,0)}function pu(e,t,r){let n=sr(e).find(s=>s.path===t);if(!n)return e;let o=Array.isArray(n.value)?n.value.slice(r):Object.fromEntries(Object.entries(n.value).slice(r)),i=Ms(e,t,o);return J(i.summary)&&J(i.summary.focus_row_states)&&typeof i.summary.focus_row_states[t]=="string"&&(i.summary={...i.summary,focus_row_states:{...i.summary.focus_row_states,[t]:i.summary.focus_row_states[t].slice(r)}}),on(i),i}function Oo(e){let t=e.row_contract;return J(t)&&Array.isArray(t.row_keys)?t.row_keys.filter(r=>typeof r=="string"&&r.trim().length>0):Object.entries(e).filter(([,r])=>Array.isArray(r)).map(([r])=>r)}function aw(e){let t=e.row_contract;return J(t)&&Array.isArray(t.continuation_row_keys)?t.continuation_row_keys.filter(r=>typeof r=="string"&&r.trim().length>0):Oo(e)}function Ge(e){return Oo(e).flatMap(t=>{let r=mu(e,t);return Array.isArray(r)||J(r)?[{path:t,value:r}]:[]})}function sr(e){return aw(e).flatMap(t=>{let r=mu(e,t);return Array.isArray(r)||J(r)?[{path:t,value:r}]:[]})}function rn(e){let t=Ge(e),r=new Set(t.map(o=>o.path)),n=(o,i)=>{if(Array.isArray(o)){r.has(i)||t.push({path:i,value:o}),o.forEach((s,a)=>n(s,`${i}.${a}`));return}if(J(o))for(let[s,a]of Object.entries(o))i.length===0&&sw.has(s)||n(a,i.length===0?s:`${i}.${s}`)};return n(e,""),t}function Ao(e){return Ge(e).reduce((t,r)=>t+(Array.isArray(r.value)?r.value.length:Object.keys(r.value).length),0)}function nn(e,t){let r=e;for(let n of Ge(r)){let o=Array.isArray(n.value)?n.value.map((i,s)=>t(i,n.path,s)):Object.fromEntries(Object.entries(n.value).map(([i,s],a)=>[i,t(s,n.path,a)]));r=Ms(r,n.path,o)}return r}function _u(e,t){let r=e,n=!1;for(let o of Ge(r)){let i=Array.isArray(o.value)?o.value:Object.entries(o.value);if(i.length<=t)continue;n=!0;let s=Array.isArray(o.value)?i.slice(0,t):Object.fromEntries(i.slice(0,t));r=Ms(r,o.path,s)}return{result:r,truncated:n}}var yu=["high_level","low_level","blocked_fallback"];function So(e){let t=e.status==="in_progress"?"i":"o";return e.blocked===!0?t.toUpperCase():t}function QN(e,t){if(!J(e.summary)||!J(e.summary.returned_focus))return;let r=new Map(t.map(n=>[n.id,n]));e.summary={...e.summary,focus_row_states:Object.fromEntries(yu.map(n=>[n,Array.isArray(e[n])?e[n].filter(J).map(o=>So(r.get(o.id)??o)).join(""):""]))}}function cw(e,t){if(e!==void 0){if(typeof e!="string"||e.length!==t||!/^[iIoO]*$/u.test(e))throw new TypeError("Context focus classification receipt must contain one i/I/o/O code per delivered record");return e}}function dw(e,t,r,n){let o=Array.isArray(t[r])?t[r].filter(J):[],i=cw(n[r],o.length)??o.map(So).join(""),s=new Map(o.flatMap((d,l)=>d.id===void 0?[]:[[d.id,i[l]]])),a=Array.isArray(e[r])?e[r].filter(J):[],c=!1;return{states:a.map((d,l)=>{let u=s.get(d.id)??(d.id===void 0?i[l]:void 0)??So(d);return u!==So(d)&&(c=!0),u}).join(""),needsStates:c}}function lw(e,t){typeof e.count=="number"&&(e.count_only===!0||t.count_only===!0?typeof t.count=="number"&&(e.count=t.count):Array.isArray(e.items)&&(e.count=e.items.length))}function on(e,t=e){if(lw(e,t),!J(e.summary)||!J(e.summary.returned_focus))return;let r={...e.summary},n=J(t.summary)&&J(t.summary.focus_row_states)?t.summary.focus_row_states:{},o=yu.map(c=>({key:c,...dw(e,t,c,n)})),i=Object.fromEntries(o.map(({key:c,states:d})=>[c,d])),s=o.some(c=>c.needsStates),a=Object.values(i).join("");typeof r.high_level=="number"&&(r.high_level=Array.isArray(e.high_level)?e.high_level.length:0),typeof r.low_level=="number"&&(r.low_level=Array.isArray(e.low_level)?e.low_level.length:0),r.returned_focus={active_items:a.length,in_progress:[...a].filter(c=>c.toLowerCase()==="i").length,open:[...a].filter(c=>c.toLowerCase()==="o").length,blocked:[...a].filter(c=>c===c.toUpperCase()).length},s?r.focus_row_states=i:delete r.focus_row_states,e.summary=r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="439cf503-a832-58a3-ba19-db44de57b573")}catch{}})();var Io="changed_fields",uw="changed_field_count",$s="rows",fw=new Set(["apply","rollback"]),wu=new Set(["deleted","would_delete"]),hu=256,gu={start_task:["claim","update"],pause_task:["update","release"],close_task:["close","release"]};function mw(e,t){if(!ne(e)||typeof e.action!="string"||typeof e.id!="string"||e.id.length===0)return null;let r=Object.hasOwn(gu,e.action)?gu[e.action]:void 0;if(!r||!r.every(i=>{let s=e[i];return ne(s)&&ne(s.item)&&s.item.id===e.id&&Array.isArray(s.changed_fields)&&s.changed_fields.every(a=>typeof a=="string")}))return null;let n=e[r.at(-1)],o=Eu(n);return t.idOnly?o:!t.compactEnvelope&&t.changedFields!=="compact"?null:{...e,...t.compactEnvelope?{...o,changed_field_count:new Set(r.flatMap(i=>e[i].changed_fields)).size}:{},...Object.fromEntries(r.map(i=>[i,sn(e[i],t)]))}}function bu(e){return typeof e!="string"||e.length<=hu?e:`${We(e,hu-1)}\u2026`}function pw(e){if(!ne(e))return null;let t={...e};return t.reason=bu(t.reason),ne(t.previous_terminal)&&(t.previous_terminal=Object.fromEntries(Object.entries(t.previous_terminal).map(([r,n])=>[r,bu(n)]))),t}function ne(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function vu(e){let t=e[Io];if(!Array.isArray(t))return null;let r=Object.getPrototypeOf(e)===null?Object.create(null):{};for(let[n,o]of Object.entries(e))n!==Io&&(r[n]=o);return r[uw]=t.length,r}function _w(e){return"item"in e&&Array.isArray(e[Io])}function yw(e){return typeof e.mode=="string"&&fw.has(e.mode)&&Array.isArray(e[$s])}function hw(e,t){let r=Object.getPrototypeOf(e)===null?Object.create(null):{};return Object.assign(r,e),r[$s]=t,r}function Eu(e){if(!ne(e))return null;let t=ne(e.item)?e.item:ne(e.plan)?e.plan:null;if(t===null)return null;let r=typeof t.id=="string"?t.id:void 0,n=typeof e.outcome=="string"&&wu.has(e.outcome)?e.outcome:typeof t.status=="string"?t.status:void 0;return r?n?{id:r,status:n,...typeof e.deleted=="boolean"?{deleted:e.deleted}:{}}:{id:r}:null}function gw(e,t){if(!ne(e))return null;if(ne(e.plan)&&ne(e.mutation_receipt)&&e.mutation_receipt.kind==="plan_mutation"&&e.mutation_receipt.id===e.plan.id&&e.mutation_receipt.action===e.action)return e.mutation_receipt;if(!t||!ne(e.item)||typeof e.item.id!="string")return null;let r=e[Io];if(!Array.isArray(r))return null;let n={id:e.item.id,...typeof e.outcome=="string"&&wu.has(e.outcome)?{status:e.outcome}:typeof e.item.status=="string"?{status:e.item.status}:{},...typeof e.deleted=="boolean"?{deleted:e.deleted}:{},...typeof e.previous_status=="string"?{previous_status:e.previous_status}:{},changed_field_count:r.length};return bw(e,e.item,n),n}function bw(e,t,r){let n=typeof e.close_reason=="string"?e.close_reason:typeof t.close_reason=="string"?t.close_reason:void 0;n!==void 0&&(r.close_reason=n);let o=pw(e.recurrence);o!==null&&(r.recurrence=o),Array.isArray(e.warnings)&&e.warnings.length>0&&(r.warnings=e.warnings);for(let i of["recovery","follow_up","handoff","completion"])ne(e[i])&&(r[i]=e[i]);if(typeof e.claimed_by=="string"||typeof e.released_by=="string")for(let i of["claimed_by","released_by","previous_assignee","forced","skipped","available","attempts","suggestions"])Object.hasOwn(e,i)&&(r[i]=e[i])}function ww(e){let t=yw(e)?e[$s]:void 0;if(!Array.isArray(t))return{projected:e,changed:!1};let r=!1,n=t.map(o=>{if(!ne(o))return o;let i=vu(o);return i?(r=!0,i):o});return r?{projected:hw(e,n),changed:!0}:{projected:e,changed:!1}}function sn(e,t={}){let r=mw(e,t);if(r!==null)return r;if(t.idOnly===!0){let a=Eu(e);if(a!==null)return a}if(t.compactEnvelope===!0||t.changedFields==="compact"){let a=gw(e,t.compactEnvelope===!0);if(a!==null)return a}if((t.changedFields??"full")==="full"||!ne(e))return e;let n=!1,o=e,i=_w(e)?vu(e):null;i!==null&&(o=i,n=!0);let s=ww(o);return s.changed&&(o=s.projected,n=!0),n?o:e}import{AsyncLocalStorage as BE}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1b67272d-8924-5b1b-97cd-74a6a10493be")}catch{}})();function js(e){let t=e.trim().toLowerCase().startsWith("extension:"),r=e.trim().toLowerCase().replace(/^extension:/u,"");if(Jt(r))return;let n=tu()?.commands??[],o=[...n].reverse().find(s=>s.command===r)?.command??(t?void 0:n.find(s=>s.action===r)?.command),i=[...n].reverse().find(s=>s.command===o);return i===void 0||Jt(i.command)||Jt(i.action)?void 0:i}function vw(e){let t=js(e);return t?.read_output===void 0?void 0:t}function ku(e,t){let r=vw(e),n=r?.read_output;if(n===void 0)return t;if(typeof t!="object"||t===null||Array.isArray(t))throw new g("Read-only extension commands must return a structured object.",h.USAGE,{code:"extension_read_output_invalid"});for(let o of n.row_keys){let i=t;for(let s of o.split("."))i=typeof i=="object"&&i!==null&&Object.hasOwn(i,s)?Reflect.get(i,s):void 0;if(i===null||typeof i!="object")throw new g(`Read-only extension result is missing declared row collection ${o}.`,h.USAGE,{code:"extension_read_output_invalid"})}return{...t,row_contract:{command:`extension:${r.command}`,row_kind:n.row_keys.length>0?"collection":"none",row_keys:[...n.row_keys],fields:"supported",...n.row_keys.length>0?{jq_selector:Eo}:{},toon_encoding:"tabular_when_uniform"}}}import{createHash as Rv}from"node:crypto";import{createHash as Ov}from"node:crypto";import{stripVTControlCharacters as Ew}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1a14ce9e-1074-5434-9646-dd5e25e34814")}catch{}})();var kw=["full","compact","brief","summary","counts"],mD=["mutation","read","discovery","governance"],Ou=["error","warning","validation_summary","recovery_bundle"],Sw=["full","omit_explanation","limit_collections","compact_recovery","action_only"],Ow=new Set(["append","claim","close","close-many","close-task","comments","config","copy","create","delete","docs","event","files","focus","history-author-acknowledge","history-compact","history-redact","history-repair","init","item","learnings","meet","notes","pause-task","release","remind","restore","schema","start-task","update","update-many"]),Aw=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),Iw=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),Tw={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},Cw=3,Rw=2,xw=192,Nw={error:{text:768,json:2e3},warning:{text:768,json:2e3},validation_summary:{text:1500,json:3e3},recovery_bundle:{text:768,json:2e3}},Dw=Ou.map(e=>({diagnostic_class:e,default_max_estimated_tokens_by_format:Nw[e],minimum_max_estimated_tokens:xw,degradation_ladder:Sw,corrective_action_paths:["required","recovery.suggested_retry","recovery.suggested_retry_args","recovery.next_best_command","next_steps[0]"],token_estimate:"ceil(utf8_bytes / 4)"})),Pw=new Map(Dw.map(e=>[e.diagnostic_class,e]));function Mw(e){let[t=""]=Dr(e).split(/\s+/u);return Ow.has(t)?"mutation":Aw.has(t)?"discovery":Iw.has(t)?"governance":"read"}function Au(e,t=Mw(e)){let r=e.trim().replace(/\s+/gu," ");if(r.length===0)throw new TypeError("command must be a non-empty command path");let n=Tw[t];return $w({command:r,budget_class:t,default_max_estimated_tokens:n,default_max_estimated_tokens_by_format:{toon:n,json:Math.ceil(n*Cw/Rw)},degradation_ladder:kw,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function $w(e){if(!Number.isSafeInteger(e.default_max_estimated_tokens)||e.default_max_estimated_tokens<=0)throw new RangeError("default_max_estimated_tokens must be a positive safe integer");for(let[t,r]of Object.entries(e.default_max_estimated_tokens_by_format))if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`default_max_estimated_tokens_by_format.${t} must be a positive safe integer`);return e}var jw=oo.map(e=>Au(e)),Lw=new Map(jw.map(e=>[e.command,e]));function Iu(e,t={}){let r=e.trim().replace(/\s+/gu," "),[n]=Dr(r).split(" "),o=Lw.get(n);return o?{...o,command:r}:t.generateFallback?Au(r):null}function Et(e){return Math.ceil(Math.max(0,e)/4)}function Tu(e){let t=Pw.get(e);if(t===void 0)throw new TypeError(`diagnosticClass must be one of: ${Ou.join(", ")}`);return t}function Ke(e){return Et(Buffer.byteLength(JSON.stringify(e,null,2),"utf8"))}function Fw(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ls(e){if(!Fw(e))return;let t={};for(let r of["suggested_retry","suggested_retry_args","next_best_command","allowed_values","candidate_commands","missing","missing_required_fields","option_scope","retry_after_ms","waited_ms","owner_handoffs"]){let n=e[r];Array.isArray(n)?t[r]=r==="suggested_retry_args"?n:n.slice(0,3):n!==void 0&&(t[r]=n)}return Object.keys(t).length>0?t:void 0}function zw(e,t){return typeof e!="string"||e.length<=t?e:`${We(e,Math.max(1,t-3))}...`}function vt(e,t){if(Buffer.byteLength(e,"utf8")<=t)return e;let r="...",n=Array.from(e),o=0,i=n.length;for(;o<i;){let s=Math.ceil((o+i)/2),a=`${n.slice(0,s).join("")}${r}`;Buffer.byteLength(a,"utf8")<=t?o=s:i=s-1}return`${n.slice(0,o).join("")}${r}`}function Cu(e){let t={};for(let r of["code","required","recovery","next_steps","exit_code","type","title","detail","why","examples"])Object.hasOwn(e,r)&&e[r]!==void 0&&(t[r]=e[r]);for(let[r,n]of Object.entries(e))r!=="__proto__"&&!Object.hasOwn(t,r)&&(t[r]=n);return t}var Uw=new Set(["limit_collections","compact_recovery","action_only"]),Hw=new Set(["compact_recovery","action_only"]);function qw(e){let t={code:typeof e.code=="string"?e.code:"diagnostic",required:zw(e.required,160)??"Inspect the diagnostic code and retry with corrected input."},r=Ls(e.recovery);return r!==void 0?t.recovery=r:Array.isArray(e.next_steps)&&(t.next_steps=e.next_steps.slice(0,1)),e.exit_code!==void 0&&(t.exit_code=e.exit_code),e.type!==void 0&&(t.type=e.type),t}function Vw(e,t){let r=structuredClone(e);if(t!=="full"&&(delete r.why,delete r.examples),Uw.has(t))for(let[n,o]of Object.entries(r))Array.isArray(o)&&(r[n]=o.slice(0,3));if(Hw.has(t)){let n=Ls(r.recovery);n?r.recovery=n:delete r.recovery}return t!=="action_only"?Cu(r):qw(r)}function ar(e,t){let r={...e,diagnostic_output:{...t,estimated_tokens:0}};for(let n=0;n<4;n+=1){let o=Ke(r),i=r.diagnostic_output;if(i.estimated_tokens===o)break;i.estimated_tokens=o}return r}function Bw(e,t,r){let n=ar(e,t);for(let i of["recovery","exit_code"])Ke(n)<=r||e[i]===void 0||(delete e[i],n=ar(e,t));let o=40;for(;Ke(n)>r&&o>4;)o-=4,e.code=vt(String(e.code),o),e.required=vt(String(e.required),o),n=ar(e,t);return n}function Ww(e,t){let r=e.diagnostic_output,{estimated_tokens:n,...o}=r,i=o.omitted_fields.slice(0,8).map(u=>vt(u,32)),s={...o,omitted_fields:i,...o.omitted_fields.length>i.length?{omitted_fields_overflow_count:o.omitted_fields.length-i.length}:{}},a=Ls(e.recovery),c=a&&Ke(a)<=48?a:void 0,d={code:vt(String(e.code),320),required:vt(String(e.required),320),...c?{recovery:c}:{},...e.exit_code!==void 0?{exit_code:e.exit_code}:{}},l=ar(d,s);for(;Ke(l)>t&&s.omitted_fields.length>0;)s.omitted_fields.pop(),s.omitted_fields_overflow_count=o.omitted_fields.length-s.omitted_fields.length,l=ar(d,s);return l=Bw(d,s,t),l}function pD(e,t={}){let r=e,n=t.diagnosticClass??"error",o=Tu(n),i=t.maxEstimatedTokens;if(i!==void 0&&(!Number.isSafeInteger(i)||i<o.minimum_max_estimated_tokens))throw new RangeError(`maxEstimatedTokens must be a safe integer >= ${o.minimum_max_estimated_tokens}`);let s=i??o.default_max_estimated_tokens_by_format.json,a=Ke(r),c=Object.keys(r);if(a<=s)return Cu(structuredClone(r));let d;for(let[l,u]of o.degradation_ladder.entries()){let f=Vw(r,u),m=c.filter(y=>!Object.hasOwn(f,y)),_=ar(f,{diagnostic_class:n,format:"json",budget:s,budget_source:i===void 0?"default":"explicit",original_estimated_tokens:a,truncated:l>0,degradation_steps:o.degradation_ladder.slice(0,l+1),omitted_fields:m});if(d=_,Ke(_)<=s)break}return Ke(d)>s&&(d=Ww(d,s)),d}function Su(e){return Ew(e).replace(/\r\n/gu,`
|
|
2
|
-
`).replace(/[^\P{Cc}\n]/gu," ")}function _D(e,t,r={}){let n=r.diagnosticClass??"error",o=Tu(n),i=r.maxEstimatedTokens;if(i!==void 0&&(!Number.isSafeInteger(i)||i<o.minimum_max_estimated_tokens))throw new RangeError(`maxEstimatedTokens must be a safe integer >= ${o.minimum_max_estimated_tokens}`);let s=i??o.default_max_estimated_tokens_by_format.text,a=Su(e),c=Et(Buffer.byteLength(a,"utf8")),d=c>s,l=`What is required:
|
|
3
|
-
`,u=`
|
|
4
|
-
|
|
5
|
-
${vt(a.trimStart().split(/\r?\n/u,1)[0].trim(),320)}
|
|
6
|
-
|
|
7
|
-
Diagnostic output exceeded its declared ${s}-token ceiling; rerun with structured JSON for the bounded recovery envelope.`,f=Su(t).trim()||"Inspect the diagnostic code and retry with corrected input.",m=Math.max(1,s*4-Buffer.byteLength(`${l}${u}`,"utf8")),_=d?`${l}${vt(f,m)}${u}`:a;return{output:_,diagnostic_output:{diagnostic_class:n,format:"text",budget:s,budget_source:i===void 0?"default":"explicit",original_estimated_tokens:c,estimated_tokens:Et(Buffer.byteLength(_,"utf8")),truncated:d,degradation_steps:d?[...o.degradation_ladder]:["full"],omitted_fields:d?["explanation","collections"]:[]}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="24a8de41-54f9-5b59-8e58-7ac924ba6e08")}catch{}})();function vD(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"&&"context_ref"in e&&typeof e.context_ref=="string"&&e.context_ref.startsWith("session:")&&e.context_ref.endsWith(`:${e.id}`)}var Fs=256,zs=1e4,Gw=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u,Ru=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,Kw=new Set(["version","id","token_budget","spent_tokens","seen_item_ids"]),Yw=[{valid:e=>e.version===1,reason:"version must equal 1."},{valid:e=>typeof e.id=="string"&&Gw.test(e.id),reason:"id must be 1-64 portable identifier characters."},{valid:e=>Number.isSafeInteger(e.token_budget)&&e.token_budget>=Fs,reason:`token_budget must be a safe integer of at least ${Fs}.`},{valid:e=>Number.isSafeInteger(e.spent_tokens)&&e.spent_tokens>=0&&e.spent_tokens<=e.token_budget,reason:"spent_tokens must be a non-negative safe integer no larger than token_budget."},{valid:e=>Array.isArray(e.seen_item_ids)&&e.seen_item_ids.length<=zs&&e.seen_item_ids.every(t=>typeof t=="string"&&Ru.test(t)),reason:`seen_item_ids must contain at most ${zs} portable item identifiers.`}];function Co(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function To(e){throw new g(`--output-session ${e}`,h.USAGE,{code:"invalid_read_output_session",field:"outputSession"})}function Ro(e){if(e===void 0)return;let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{To("must be a valid JSON object.")}Co(t)||To("must be a JSON object.");let r=Object.keys(t).filter(i=>!Kw.has(i));r.length>0&&To(`contains unknown field "${r.sort()[0]}".`);let n=Yw.find(i=>!i.valid(t));n!==void 0&&To(n.reason);let o=[...new Set(t.seen_item_ids)].sort();return{version:1,id:t.id,token_budget:t.token_budget,spent_tokens:t.spent_tokens,seen_item_ids:o}}function xu(e){if(Co(e))return typeof e.id=="string"?e.id:typeof e.item_id=="string"?e.item_id:Co(e.item)&&typeof e.item.id=="string"?e.item.id:void 0}function Xw(e){let t=new Set,r=0,n=Ge(e),o=new Set(n.map(({path:s})=>s)),i=Object.entries(e).flatMap(([s,a])=>Array.isArray(a)&&!o.has(s)?[{path:s,value:a}]:[]);for(let s of[...n,...i]){let a=Array.isArray(s.value)?s.value:Object.values(s.value);for(let c of a){if(!Co(c))continue;if(typeof c.context_ref=="string"){r+=1;continue}let d=xu(c);d!==void 0&&Ru.test(d)&&t.add(d)}}return{deliveredIds:t,suppressedRepeatCount:r}}function Nu(e,t){let r=new Set(t.seen_item_ids);return nn(e,n=>{let o=xu(n);return o!==void 0&&r.has(o)?{id:o,context_ref:`session:${t.id}:${o}`}:n})}function Us(e,t,r){let{deliveredIds:n,suppressedRepeatCount:o}=Xw(e),i=new Set(t.seen_item_ids),s=[...n].filter(y=>!i.has(y)).sort(),a=s.slice(0,zs-t.seen_item_ids.length),c=[...t.seen_item_ids,...a].sort(),d=s.length-a.length,l={contract_version:1,id:t.id,measurement_scope:"complete_read_envelope",estimator:"ceil(utf8_bytes / 4)",token_budget:t.token_budget,spent_before_tokens:t.spent_tokens,spent_this_call_tokens:0,charged_this_call_tokens:0,spent_total_tokens:t.spent_tokens,remaining_tokens:t.token_budget-t.spent_tokens,exhausted:!1,seen_before_count:t.seen_item_ids.length,new_item_count:n.size,...d===0?{}:{seen_item_overflow_count:d},suppressed_repeat_count:o,reference_format:"session:<session-id>:<item-id>",restore_reference_with:"pm get <item-id> --depth brief",next_state:{version:1,id:t.id,token_budget:t.token_budget,spent_tokens:t.spent_tokens,seen_item_ids:c}},u={...e,read_session:l},f=y=>{l.spent_this_call_tokens=y,l.charged_this_call_tokens=Math.min(t.token_budget-t.spent_tokens,y),l.spent_total_tokens=Math.min(t.token_budget,t.spent_tokens+l.charged_this_call_tokens),l.remaining_tokens=Math.max(0,t.token_budget-l.spent_total_tokens),l.exhausted=l.remaining_tokens<Fs,l.next_state.spent_tokens=l.spent_total_tokens},m=0,_=0;for(let y=0;y<8;y+=1){f(m);let w=an(u,r);if(w===m)return u;_=Math.max(_,w),m=w}return f(_),u}function Du(e){return Math.max(0,e.token_budget-e.spent_tokens)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1cc0fcb7-2aaa-5233-bdfd-4b4d0fb3e9c1")}catch{}})();var cn=Symbol.for("pm.readOutputInvocationProvenance");function kD(e,t){return Reflect.set(e,cn,{canonical_include_modes:[...t],explicit_legacy_aliases:[],sdk_invocation_observed:!0}),e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a829643f-ca94-51b0-a6ae-27583cd95b3d")}catch{}})();var kt=["include","amount","cost","encoding"],Uu=["canonical","legacy","intent","default"],ln=io,zD=Object.freeze(kt.map(e=>ln[e])),UD=so,Hu={list:{include:["--brief","--compact","--fields","--full"],amount:["--after","--limit","--no-truncate"],cost:["--token-budget"],encoding:["--format","--stream"]},context:{include:["--fields","--section"],amount:["--after","--depth","--limit"],cost:["--token-budget"],encoding:["--format"]},search:{include:["--compact","--fields","--full"],amount:["--after","--limit"],cost:["--token-budget"],encoding:["--format"]},get:{include:["--fields","--full"],amount:["--depth"],cost:["--token-budget"],encoding:["--format"]},next:{amount:["--blocked-limit","--limit"],cost:["--token-budget"],encoding:["--format"]},health:{include:["--brief","--check-only","--full","--summary"]},deps:{include:["--collapse","--full","--summary"],amount:["--edge-limit","--max-depth","--node-limit"],cost:["--token-budget"],encoding:["--format"]},graph:{include:["--full","--summary"],amount:["--after","--limit","--max-depth","--max-paths"]},history:{include:["--compact","--full"],amount:["--limit"],encoding:["--format"]},activity:{include:["--compact","--full"],amount:["--limit","--unbounded","--after"],encoding:["--stream"]},validate:{include:["--counts","--full"]},events:{include:["--full"],amount:["--limit"],encoding:["--follow"]},contracts:{include:["--full","--summary"]},comments:{amount:["--limit"]},notes:{amount:["--limit"]},files:{amount:["--limit","--no-truncate","--offset"]},docs:{},stats:{},aggregate:{},duplicates:{amount:["--limit"]},"package-catalog":{},"package-manage":{},"comments-audit":{},assurance:{}},qu=new Set(["--collapse","--fields","--section"]),qs=Object.freeze({"--after":"--after retains cursor-position semantics; use --output-limit <n> separately to bound returned rows.","--check-only":"--check-only retains health side-effect semantics; --output-include does not suppress vector refresh.","--collapse":"--collapse retains dependency grouping semantics; --output-include does not replace it.","--depth":"--depth retains traversal or detail-depth semantics; --output-limit does not replace it.","--follow":"--follow retains event-tail semantics; --output-format does not enable following.","--max-depth":"--max-depth retains graph traversal-depth semantics; --output-limit does not replace it.","--max-paths":"--max-paths retains graph path-search semantics; use --output-limit separately to bound returned rows.","--no-truncate":"--no-truncate is a compatibility alias; prefer --output-limit unbounded --output-budget unbounded.","--offset":"--offset retains positional pagination semantics; use --output-limit separately to bound returned rows.","--stream":"--stream retains command streaming semantics; --output-format selects only static result encoding.","--unbounded":"--unbounded is a compatibility alias; prefer --output-limit unbounded."});function Vs(e){return e.slice(2).replaceAll("-","_")}function Jw(e,t){let r=qs[e];if(r!==void 0)return r;let n=t==="include"?qu.has(e)?"<csv>":Vs(e):t==="amount"?"<n>":t==="cost"?"<tokens>":"<toon|json>";return`${e} is a compatibility alias; prefer ${ln[t]} ${n}.`}function Vu(e){let t=Hu[e]??{},r=Object.freeze(Object.fromEntries(kt.map(n=>[n,Object.freeze({dimension:n,canonical_option:ln[n],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((t[n]??[]).map(o=>Object.freeze({flag:o,semantics:qs[o]===void 0?"replacement":"behavior_preserving",migration_hint:Jw(o,n),visibility:"hidden_alias"})))})])));return Object.freeze({command:e,dimensions:r,precedence:Uu,budget_retention_policy:e==="assurance"?"verdict_priority":"ordered_prefix",projection_modes:Object.freeze([...Wu(e).keys()])})}var Zw=Object.freeze(Xt.map(Vu)),Qw=new Map(Zw.map(e=>[e.command,e]));function lr(e,t={}){let r=Dr(e.trim().toLowerCase()),n=js(r);return n!==void 0?n.read_output===void 0?void 0:`extension:${n.command}`:ev(r,t)}function ev(e,t){let r=e==="package catalog"||e==="packages catalog"||e==="package-catalog"||(e==="package"||e==="packages"||e==="extension")&&(t.catalog===!0||t.target==="catalog"||t.action==="catalog")?"package-catalog":e==="package manage"||e==="package-manage"?"package-manage":e.split(" ")[0],n=r.startsWith("list-")?"list":r==="ctx"?"context":r;return Xt.includes(n)?n:void 0}var tv=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"],rv={comments:["add","body","stdin","file","edit","delete"],notes:["add","addJson","stdin","file","edit","delete"],files:["add","addGlob","remove","migrate","apply","note"],docs:["add","addGlob","remove","migrate","note"],"package-catalog":["activate","adopt","adoptAll","deactivate","doctor","init","install","manage","migrate","reload","scaffold","uninstall"]};function nv(e){return tv.some(t=>t!=="outputFormat"&&t!=="output_format"&&e[t]!==void 0)}var ov=[{keys:["outputInclude","output_include"],valid:e=>dn(e)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:e=>e==="unbounded"||dr(e)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:e=>e==="unbounded"||dr(e)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputSession","output_session"],valid:e=>(Ro(e),!0),message:"--output-session must be a valid session-state object."},{keys:["outputCursor","output_cursor"],valid:e=>typeof e=="string"&&e.trim().length>0,message:"--output-cursor requires a non-empty continuation cursor."}];function HD(e,t){let r=t.outputFormat??t.output_format;if(r!==void 0&&r!=="json"&&r!=="toon")throw new g("--output-format must be toon or json.",h.USAGE);if(!nv(t))return;let n=lr(e,t);if(!n)throw new g(`Universal output controls apply only to read commands; ${e||"this command"} is not a read surface.`,h.USAGE);if((rv[n]??[]).some(o=>t[o]!==void 0&&t[o]!==!1))throw new g(`Universal output controls cannot be combined with a ${n} mutation.`,h.USAGE);for(let o of ov){let i=o.keys.map(s=>t[s]).find(s=>s!==void 0);if(i!==void 0&&!o.valid(i))throw new g(o.message,h.USAGE)}}function Bu(e){let t=lr(e);return t?Wu(t):new Map}function Wu(e){return new Map((Hu[e]?.include??[]).filter(t=>!qu.has(t)&&qs[t]===void 0).map(t=>[Vs(t),Gu(t)]))}function iv(e,t,r){let n=dn(t)??[],o=Bu(e),i=[],s=[],a=r,c=a[cn],d=new Set(c?.canonical_include_modes??[]),l=new Set(c?.explicit_legacy_aliases??[]);for(let m of n){let _=o.get(m);if(_===void 0){i.push(m);continue}let y=`--${m.replaceAll("_","-")}`;Ws(Bs(r,y))&&l.add(y),r[_]=!0,s.push(m),d.add(m)}let u=lr(e)==="get"?i.filter(m=>m!=="item"):[],f=u.length>0;return f&&(r.fields=[...new Set([...dn(r.fields)??[],...u])].join(","),d.add("fields")),(s.length>0||f)&&(a[cn]={canonical_include_modes:[...d],explicit_legacy_aliases:[...l],...c?.cli_invocation_observed===!0?{cli_invocation_observed:!0}:{}}),{selectors:i,modes:s}}function qD(e,t){let r=t.outputInclude??t.output_include;if(r===void 0)return;let{selectors:n,modes:o}=iv(e,r,t);if(o.length===0)return;let i=n.length>0?n.join(","):void 0;t.outputInclude=i,Object.hasOwn(t,"output_include")&&(t.output_include=i)}function Gu(e){return e.slice(2).replace(/-([a-z])/gu,(t,r)=>r.toUpperCase())}function Bs(e,t){let r=Gu(t);if(Object.hasOwn(e,r))return e[r];let n=t.slice(2).replaceAll("-","_");if(Object.hasOwn(e,n))return e[n];if(t==="--no-truncate"&&e.truncate===!1)return!0}function Ws(e){return e!==void 0&&e!==!1&&e!==null}function dn(e){let t=(Array.isArray(e)?e:[e]).flatMap(r=>typeof r=="string"?r.split(","):[]).map(r=>r.trim()).filter(Boolean);return t.length>0?[...new Set(t)]:void 0}function dr(e){let t=typeof e=="number"?e:typeof e=="string"&&/^\d+$/u.test(e.trim())?Number(e):Number.NaN;return Number.isSafeInteger(t)&&t>0?t:void 0}function sv(e,t,r,n){for(let o of e.legacy_aliases){if(n(o.flag))continue;let i=Bs(t,o.flag),s={value:i,flag:o.flag};if(Ws(i)&&r(s))return s}}function Pu(e,t){let r=dn(e);if(r)return{source:"canonical",value:r};if(t)return{source:"legacy",value:dn(t.value)??[Vs(t.flag)]}}function Mu(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let r=dr(e);if(r!==void 0)return{source:"canonical",value:r};if(!t)return;if(t.flag==="--no-truncate"||t.flag==="--unbounded")return{source:"legacy",value:"unbounded"};let n=dr(t.value);return n===void 0?void 0:{source:"legacy",value:n}}function $u(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let r=dr(e);if(r!==void 0)return{source:"canonical",value:r};if(!t)return;let n=dr(t.value);return n===void 0?void 0:{source:"legacy",value:n}}function ju(e,t){if(e==="json"||e==="toon")return{source:"canonical",value:e};if(t)return t.flag==="--stream"||t.flag==="--follow"?{source:"legacy",value:"stream"}:t.value==="json"||t.value==="toon"?{source:"legacy",value:t.value}:void 0}function Ku(e,t,r){if(!e)return!1;let n=new Set(e.explicit_legacy_aliases);if(e.cli_invocation_observed===!0||e.sdk_invocation_observed===!0)return!n.has(r);let o=new Set(e.canonical_include_modes.map(i=>`--${i.replaceAll("_","-")}`));return t==="include"&&o.has(r)&&!n.has(r)}function av(e,t,r,n){return e.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0]==="list-all"||Ws(Bs(n,"--no-truncate"))&&!Ku(r,"amount","--no-truncate")||t.amount?.flag==="--no-truncate"||t.include?.flag==="--full"||r?.canonical_include_modes.includes("full")===!0}function cv(e,t){return kt.flatMap(r=>e[r]?.source==="canonical"||r==="include"&&(t?.canonical_include_modes.length??0)>0?[ln[r]]:[])}function Yu(e,t){let r=lr(e,t);if(!r)return;let n=Qw.get(r)??Vu(r),o=t[cn],i={include:v=>Pu(void 0,v),amount:v=>Mu(void 0,v),cost:v=>$u(void 0,v),encoding:v=>ju(void 0,v)},s=Object.fromEntries(kt.map(v=>[v,sv(n.dimensions[v],t,I=>i[v](I)!==void 0,I=>Ku(o,v,I))])),a=kt.flatMap(v=>{let I=s[v];return I?[I.flag]:[]}),c=kt.flatMap(v=>{let I=s[v];return I?[n.dimensions[v].legacy_aliases.find(z=>z.flag===I.flag).migration_hint]:[]}),d=ju(t.outputFormat??t.output_format,s.encoding),l=Pu(t.outputInclude??t.output_include,s.include),u=Mu(t.outputLimit??t.output_limit,s.amount),f=$u(t.outputBudget??t.output_budget,s.cost),m=av(e,s,o,t),_=Iu(e,{generateFallback:!0}),y=d?.value==="json"||t.resolvedOutputFormat==="json"?"json":"toon",w=f??(m?{source:"intent",value:"unbounded"}:{source:"default",value:_.default_max_estimated_tokens_by_format[y]});return{command:r,include:l,amount:u,cost:w,encoding:d,canonical_options_used:cv({include:l,amount:u,cost:w,encoding:d},o),legacy_aliases_used:a,migration_hints:c,precedence:Uu}}function ee(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Gs=new Set(["applied_bound","applied_limit","completeness","continuation_kind","continuation_path","continuation_contract","count","filters","has_more","next_cursor","now","omission_receipt","projection","budget_retention_policy","row_contract","sorting","total","truncated"]),dv=["collection_counts","notes_count","tests_count"];function Xu(e,t){let r=new Set(t.map(n=>n.split(".")[0]));return Object.fromEntries(Object.entries(e).filter(([n])=>r.has(n)))}function lv(e){let t=ee(e.item)?e.item:{},r=[...new Set([...Object.keys(t),...dv.filter(o=>Object.hasOwn(t,o))])].sort((o,i)=>o.localeCompare(i)),n=Object.keys(e).filter(o=>o!=="item"&&o!=="read_output"&&!Gs.has(o)).sort((o,i)=>o.localeCompare(i));return{item:t,itemFields:r,sections:n,valid:[...r,"item",...r.map(o=>`item.${o}`),...n]}}function uv(e,t){let r=lv(e),n=t.filter(l=>!r.valid.includes(l));if(n.length>0)throw new g(`Unknown --output-include selector(s) for get: ${n.join(", ")}. Valid selectors: ${r.valid.join(", ")}.`,h.USAGE);let o=t.includes("item"),i=t.flatMap(l=>l.startsWith("item.")?[l.slice(5)]:r.itemFields.includes(l)?[l]:[]).filter((l,u,f)=>f.indexOf(l)===u);if(o&&i.length>0)throw new g("--output-include cannot mix a full item with projected item fields; use item or item.<field>, not both.",h.USAGE);let s=new Set(t.filter(l=>r.sections.includes(l))),a=Object.fromEntries(Object.entries(e).filter(([l])=>Gs.has(l)||s.has(l)));o?a.item=r.item:i.length>0&&(a.item=Xu(r.item,i));let c=[...o?[]:i.length>0?r.itemFields.filter(l=>!i.includes(l)).map(l=>({name:`item.${l}`,restore_with:`--output-include item.${l}`})):[{name:"item",restore_with:"--output-include item"}],...r.sections.filter(l=>!s.has(l)).map(l=>({name:l,restore_with:`--output-include ${l}`}))],d=[...ee(a.omission_receipt)&&Array.isArray(a.omission_receipt.omitted_field_groups)?a.omission_receipt.omitted_field_groups:[],...c];return a.omission_receipt={has_omissions:d.length>0,omitted_field_group_count:d.length,omitted_field_groups:d},a}function Lu(e){let t=0;return nn({...e},r=>(ee(r)&&Object.keys(r).length>0&&(t+=1),r)),t}function fv(e,t,r,n){if(Lu(t)===0||Lu(r)>0)return;let o=[...Bu(e).keys()],i=o.length>0?` Declared ${e} projection modes: ${o.join(", ")}.`:` The ${e} surface declares no projection modes; name row fields instead.`;throw new g(`Unknown --output-include selector(s) for ${e}: ${n.join(", ")}. No selector matched any returned row field.${i}`,h.USAGE)}function mv(e,t,r){if(e==="get")return uv(t,r);let n=Oo(t),o=r.flatMap(s=>n.flatMap(a=>s.startsWith(`${a}.`)?[s.slice(a.length+1)]:[])),i=r.some(s=>Object.hasOwn(t,s.split(".")[0])&&!n.some(a=>s.startsWith(`${a}.`)));if(n.length>0&&(!i||o.length>0)){let s={...t},a=o.length>0?o:r,c=nn(s,d=>ee(d)?Xu(d,a):d);return fv(e,t,c,a),c}return Object.fromEntries(Object.entries(t).filter(([s])=>r.some(a=>a.split(".")[0]===s)||Gs.has(s)))}function pv(e,t){if(t==="unbounded")return e;let{result:r,truncated:n}=_u(e,t);if(!n)return r;if(r.has_more=!0,r.truncated=!0,typeof r.count=="number"){let o=ee(r.projection)?r.projection.row_key:void 0;r.count=typeof o=="string"&&Array.isArray(r[o])?r[o].length:Ao(r)}return r.applied_bound={kind:"output_limit",source:"explicit",value:t},r}function _v(e){return kt.filter(t=>e[t]!==void 0&&e[t]?.source!=="default"||e.canonical_options_used.includes(ln[t]))}function Ju(e){let t=e.resolvedOutputFormat??e.outputFormat??e.output_format??e.format;return t==="json"||t==="toon"?t:void 0}function xo(e,t,r,n){let o=Us(e,t,n);cr(e,o);for(let i=0;i<8;i+=1){let s=r.estimated_tokens,a=o.read_session.spent_this_call_tokens;Ye(o,r,n);let c=o;o=Us(o,t,n),cr(c,o);let d=o.read_session.spent_this_call_tokens;if(r.estimated_tokens===s&&d===a)return o}return o}function Ks(e,t){if(!ee(e.read_output))return e;let r=Ju(t),n=e.read_output,o=Ro(t.outputSession??t.output_session);return o===void 0?(Ye(e,n,r),e):xo(e,o,n,r)}function yv(e,t){if(e!=="validate")return t;let r=ee(t.projection)?t.projection:void 0;if(!(Array.isArray(r?.declared_field_groups)?r.declared_field_groups:[]).some(l=>ee(l)&&l.name==="diagnostic_rows"))return t;let n=[...new Set(rn(t).map(({path:l})=>l).filter(l=>/^checks\.\d+\.details\./u.test(l)))],o=n.filter(l=>!n.some(u=>u!==l&&l.startsWith(`${u}.`)));if(o.length===0)return t;let i=ee(t.row_contract)?t.row_contract:{},s=Array.isArray(i.row_keys)?i.row_keys.filter(l=>typeof l=="string"):[],a=Array.isArray(i.continuation_row_keys)?i.continuation_row_keys.filter(l=>typeof l=="string"):[],c=s.length>0?s:o,d=[...new Set(o)];return JSON.stringify(c)===JSON.stringify(s)&&JSON.stringify(d)===JSON.stringify(a)?t:{...t,row_contract:{...i,row_keys:c,continuation_row_keys:d,jq_selector:typeof i.jq_selector=="string"?i.jq_selector:".checks[].details"}}}function hv(e,t,r,n,o){let i={...e};if(t.include?.source==="canonical"&&(i=mv(t.command,i,t.include.value)),t.command==="assurance"&&(i=af(i)),on(i,e),i=cf(i,t.command,n),t.command==="history"&&n){let c=["compact_history","provenance_history","history","diff"];if(i=Object.fromEntries(Object.entries(i).filter(([d])=>!c.includes(d)||d===n.path)),ee(i.projection)&&(i.projection={...i.projection,row_key:n.path}),ee(i.row_contract)){let d=i.row_contract;i.row_contract={...d,row_keys:[n.path],...Array.isArray(d.continuation_row_keys)?{continuation_row_keys:[n.path]}:{}}}i.count=Object.keys(i[n.path]).length}let s=e.count_only===!0?{...i,count_only:!0,count:e.count}:i,a=kv(i,e,t.command,n,o);return t.amount?.source==="canonical"&&(i=pv(i,t.amount.value),a.cursorContinuesExistingPage&&tf(i,a.originalItems,a.cursorSource,!0,a.originalItemOffset)),on(i,s),{projected:r===void 0?i:Nu(i,r),continuationState:a}}function gv(e,t){return[...e.cost!==void 0&&e.cost.value!=="unbounded"&&(e.cost.source==="canonical"||e.cost.source==="default"||e.command==="context"&&e.cost.source==="legacy")?[{source:e.cost.source,tokens:e.cost.value}]:[],...t===void 0?[]:[{source:"session",tokens:Du(t)}]].sort((r,n)=>r.tokens-n.tokens)[0]}function Zu(e){let t=e.canonical_options_used;return t&&t.length>0?{canonical_options_used:t}:{}}function Qu(e,t){return ee(e.context_intent)&&e.context_intent.command==="context"&&e.context_intent.token_budget===t&&e.context_intent.within_budget===!0}function ef(e,t={}){return e?.source==="default"||e?.source==="legacy"&&!Qu(t,e.tokens)?{budget_source:e.source,budget_tokens:e.tokens}:{}}function bv(e,t,r,n,o,i){let s={contract_version:1,command:e.command,requested_dimensions:t,...ef(n),precedence:e.precedence,...Zu(e),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0,...r===void 0?{omitted_result_estimated_tokens:o}:{}},a={output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:s},c=r===void 0?a:xo(a,r,s,i);if(r===void 0&&Ye(c,s,i),r!==void 0&&s.estimated_tokens>n.tokens)throw new g("The remaining output-session budget cannot fit its mandatory receipts; start a new session with a larger token_budget.",h.USAGE);return c}function wv(e,t,r){return e.command==="context"&&e.cost?.source==="legacy"&&!Qu(r,e.cost.value)||t.outputRowContract===!0||t.output_row_contract===!0||e.canonical_options_used.includes("--output-include")||e.command==="list"&&e.canonical_options_used.length>0&&e.include?.value.includes("full")===!0}function vv(e,t,r,n,o){if(t!==void 0||wv(e,o,r))return!1;if(e.amount?.source==="canonical"&&e.amount.value!=="unbounded"){let i=e.amount.value;if(Ge(r).some(({value:s})=>(Array.isArray(s)?s.length:Object.keys(s).length)>i))return!1}return e.cost===void 0||e.cost.value==="unbounded"||e.cost.source==="legacy"&&e.command!=="context"||an(o.outputRowContract===!1?Object.fromEntries(Object.entries(r).filter(([i])=>i!=="row_contract")):r,n)<=e.cost.value}function Ev(e,t,r,n,o,i,s){if(!r.rows_compacted)return;let a=t.amount?.value==="unbounded"?["amount"]:[],c=new Map(sr(e).map(_=>[_.path,Array.isArray(_.value)?_.value.length:Object.keys(_.value).length])),d=[...s.entries()].flatMap(([_,y])=>{let w=c.get(_);if(w>=y.rows)return[];let v=y.baseOffset+w;return[{path:_,cursor:Ys({command:t.command,path:_,offset:v,total_rows:y.totalRows,fingerprint:y.fingerprint}),retained_rows:w,remaining_rows:y.totalRows-v,total_rows:y.totalRows}]}),l=d[0],u=l?"; page --output-cursor":"",f=n.source==="session"?`Truncated by the remaining ${n.tokens}-token session budget; start a new output session with a larger token_budget${u}.`:`${n.tokens}-token: raise --output-budget${u}`;r.migration_hints=[f,...t.migration_hints];let m=Hs({effective_budget_tokens:n.tokens,measured_result_tokens:i});l&&!o&&(typeof e.next_cursor!="string"||e.continuation_kind==="output_cursor")&&(e.next_cursor=l.cursor),e.continuation_kind=o?"producer_cursor":l?"output_cursor":"none",e.output_budget_truncation={reason:"output_budget_reached",budget_source:n.source,budget_tokens:n.tokens,overridden_dimensions:a,compacted_row_paths:r.compacted_row_paths,continuation_cursor_rebased:o,continuation_available:d.length>0,recovery_budget_multiplier:l?1:m.recovery_budget_multiplier,continuations:d,restore_with:l?"recovery":`Retry with --output-budget ${m.output_budget} because no declared row collection can be continued.`,recovery:l?{cursor:l.cursor,cli:"--output-cursor",sdk:"outputCursor",mcp:"outputCursor"}:{cli:`--output-budget ${m.output_budget}`,sdk:{outputBudget:m.output_budget},mcp:{outputBudget:m.output_budget}}}}function tf(e,t,r,n,o){if(typeof r!="string"||!Array.isArray(e.items))return!1;let i=e.items.length,s=t.length;if(i===0||i>=s)return!1;let a;try{a=Xs(r)}catch{return!1}let c=a.after_index;if(c===void 0)return!1;let d=t[i-1];if(Object.prototype.toString.call(d)!=="[object Object]")return!1;let l=Reflect.get(d,"id");if(typeof l!="string"||l.length===0)return!1;let u=n?c-(s-i):c+o+i;return u<0?!1:(e.next_cursor=fn(a.fingerprint,l,u,a.snapshot),!0)}function kv(e,t,r,n,o){let i=new Map(sr(e).map(c=>{let d=Array.isArray(c.value)?c.value.length:Object.keys(c.value).length,l=n?.path===c.path;return[c.path,{rows:d,totalRows:l?n.total_rows:d,baseOffset:l?n.offset:0,fingerprint:l?n.fingerprint:No(c.path,c.value,r)}]})),s=typeof e.next_cursor=="string",a=n?.path==="items"?n.offset:0;return{collectionsBeforeBudget:i,originalItems:Array.isArray(t.items)?a>0?t.items.slice(a):t.items:[],originalItemOffset:a,cursorContinuesExistingPage:s,cursorSource:s?e.next_cursor:o.after}}function Sv(e,t,r,n,o,i,s,a,c,d){let l={...t,count_only:r},u=n.command==="assurance"&&Array.isArray(e.assertions)?e.assertions.filter(m=>ee(m)&&m.verdict!=="pass").length:0,f=new Map;if(u>0&&f.set("assertions",u),n.command==="history"&&Array.isArray(e.diff))for(let m of rn(e))m.path.startsWith("diff.")&&f.set(m.path,Object.keys(m.value).length);return zu(e,o,i.tokens,f,d,m=>{on(m,l);let _=tf(m,a.originalItems,a.cursorSource,a.cursorContinuesExistingPage,a.originalItemOffset);if(Ev(m,n,o,i,_,c,a.collectionsBeforeBudget),n.command==="history"&&ee(m.projection)){m.has_more=typeof m.next_cursor=="string"||m.applied_bound?.kind==="output_limit";let y=m.projection.row_key;typeof y=="string"&&Array.isArray(m[y])&&(m.count=m[y].length)}s!==void 0&&Object.assign(m,xo(m,s,o,d))},n.command==="history"&&Array.isArray(e.diff))}function rf(e,t,r){let n=Yu(e,t);if(!n)return r;let o=Ju(t),i=Ro(t.outputSession??t.output_session),s=t.outputCursor??t.output_cursor,a=typeof s=="string"?un(s):void 0,c=_v(n),d=yv(n.command,r);if(a===void 0&&vv(n,i,d,o,t))return d;let l=gv(n,i),u=hv(d,n,i,a,t),f=u.projected;cr(f,f,t.outputRowContract===!1);let m={contract_version:1,command:n.command,requested_dimensions:c,...ef(l,f),precedence:n.precedence,...Zu(n),legacy_aliases_used:n.legacy_aliases_used,migration_hints:n.migration_hints,estimated_tokens:0,within_budget:!0,strings_compacted:!1,rows_compacted:!1,result_omitted:!1};if(f.read_output=m,f=i===void 0?f:xo(f,i,m,o),Ye(f,m,o),l!==void 0&&m.estimated_tokens>l.tokens){let _=Fu(n.command,t,f);_!==void 0&&(m.applied_depth="brief",m.degradation_reason="output_budget_reached",cr(f,_),f=Ks(_,t)),m.estimated_tokens>l.tokens&&(f=Sv(f,f,d.count_only===!0,n,m,l,i,u.continuationState,m.estimated_tokens,o))}return l!==void 0&&m.estimated_tokens>l.tokens?bv(n,c,i,l,m.estimated_tokens,o):f}function nf(e){return ee(e)&&ee(e.output_budget_exceeded)&&e.output_budget_exceeded.omitted_result===!0&&e.output_budget_exceeded.reason==="requested_budget_infeasible"}function of(e,t){let r=t.outputFormat??t.output_format;if(r==="json"||r==="toon")return r;let n=Yu(e,t)?.encoding;return n?.value==="json"||n?.value==="toon"?n.value:void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f7f59eaa-9d5d-5797-99de-e672fdfba99d")}catch{}})();var Av=4096,Iv=Object.freeze(["queue_draining","queue_entries","queue_exists","queue_high_retry_entries","queue_invalid_rows","queue_max_attempts","queue_rows_total","queue_size_bytes","pending_otel_spans","last_attempted_flush_at","last_failed_flush_at","last_otel_attempt_at","last_otel_failure_at","last_otel_success_at","last_successful_flush_at"]),sf=Object.freeze({health:Object.freeze({version:3,paths:Object.freeze(["checks"]),ignored_detail_field_names_by_row:Object.freeze({telemetry:Iv}),guarantee:"nonvolatile_snapshot_and_stable_configuration"})});function pn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function mn(e){return Array.isArray(e)?e.map(mn):pn(e)?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,mn(r)])):e}function df(e,t){if(!pn(e))return mn(e);let r=typeof e.name=="string"?e.name:void 0,n=r!==void 0&&Object.hasOwn(t.ignored_detail_field_names_by_row,r)?t.ignored_detail_field_names_by_row[r]:void 0;return Object.fromEntries(Object.entries(e).map(([o,i])=>o!=="details"||!n||!pn(i)?[o,mn(i)]:[o,Object.fromEntries(Object.entries(i).filter(([s])=>!n.includes(s)).map(([s,a])=>[s,mn(a)]))]))}function Tv(e,t){return Array.isArray(e)?e.map(r=>df(r,t)):df(e,t)}function No(e,t,r){let n=r?sf[r]:void 0,o=n?.paths.includes(e)===!0;return Ov("sha256").update(R({path:e,value:o?Tv(t,n):t,...o?{fingerprint_policy_version:n.version}:{}})).digest("base64url").slice(0,16)}function Ys(e){return Buffer.from(JSON.stringify({v:1,c:e.command,p:e.path,o:e.offset,n:e.total_rows,f:e.fingerprint}),"utf8").toString("base64url")}function Cv(e){return typeof e=="string"&&(lr(e)===e||/^extension:\S(?:[^\r\n]*\S)?$/u.test(e))}function un(e){if(e.length>Av)throw new g("The read-output continuation cursor is malformed or unsupported.",h.USAGE,{code:"read_output_cursor_invalid"});let t;try{t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{t=null}if(!pn(t)||t.v!==1||!Cv(t.c)||typeof t.p!="string"||t.p.length===0||!Number.isSafeInteger(t.o)||t.o<0||!Number.isSafeInteger(t.n)||t.n<1||typeof t.f!="string"||t.f.length===0)throw new g("The read-output continuation cursor is malformed or unsupported.",h.USAGE,{code:"read_output_cursor_invalid"});return{version:1,command:t.c,path:t.p,offset:t.o,total_rows:t.n,fingerprint:t.f}}function af(e){if(!Array.isArray(e.assertions))return e;let t=r=>!pn(r)||r.verdict==="pass"?4:r.verdict==="retired"?3:r.enforcement==="block"?0:r.enforcement==="warn"?1:2;return{...e,assertions:e.assertions.map((r,n)=>({row:r,index:n})).sort((r,n)=>t(r.row)-t(n.row)||r.index-n.index).map(({row:r})=>r),budget_retention_policy:"verdict_priority"}}function cf(e,t,r){if(!r)return e;if(r.command!==t)throw new g(`The read-output cursor belongs to ${r.command}, not ${t}.`,h.USAGE,{code:"read_output_cursor_command_mismatch"});let n=sr(e).find(i=>i.path===r.path),o=n?Array.isArray(n.value)?n.value.length:Object.keys(n.value).length:0;if(!n||o!==r.total_rows||r.offset>o||No(r.path,n.value,t)!==r.fingerprint)throw new g("The read-output continuation no longer matches the declared row collection; restart the bounded read.",h.USAGE,{code:"read_output_cursor_stale"});return pu(e,r.path,r.offset)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b6a81cf4-3095-5197-8e73-f017d98b1ccf")}catch{}})();var Zs=1,lf=4096,xv=/^[A-Za-z0-9_-]+$/;function Js(e){return e.replace(/^--/u,"").replace(/[-_]([a-z0-9])/gu,(t,r)=>r.toUpperCase())}function oP(e,t){let r=[...Object.values(io),...so],n=new Set(r.flatMap(o=>[Js(o),o.slice(2).replaceAll("-","_")]));for(let o of t)if(o.cursor_semantics==="presentation"){n.add(Js(o.flag));for(let i of o.aliases??[])n.add(Js(i))}return Object.fromEntries(Object.entries(e).filter(([o])=>!n.has(o)))}function iP(e,t){return Rv("sha256").update(e).update("\0").update(R(t)).digest("hex").slice(0,24)}function fn(e,t,r,n){return Buffer.from(JSON.stringify({version:Zs,fingerprint:e,after_id:t,...r===void 0?{}:{after_index:r},...n===void 0?{}:{snapshot:n}})).toString("base64url")}function St(e,t){return new g(e,h.USAGE,{code:"invalid_query_cursor",nextSteps:[`Repeat the original query without ${t} to obtain a fresh cursor.`]})}function Nv(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return t.version===Zs&&typeof t.fingerprint=="string"&&typeof t.after_id=="string"&&t.after_id.length>0&&(t.after_index===void 0||Number.isSafeInteger(t.after_index)&&t.after_index>=0)&&(t.snapshot===void 0||typeof t.snapshot=="string"&&t.snapshot.length>0)}function Xs(e,t="--after"){if(typeof e!="string")throw St("Query cursor is malformed.",t);let r=e.trim();if(r.length===0||r.length>lf||!xv.test(r))throw St("Query cursor is malformed.",t);let n;try{n=JSON.parse(Buffer.from(r,"base64url").toString("utf8"))}catch{throw St("Query cursor is malformed.",t)}if(!Nv(n)){let o=!1;try{un(r),o=!0}catch{}throw o?new g(`An output cursor must be continued with --output-cursor, not ${t}.`,h.USAGE,{code:"invalid_query_cursor",nextSteps:[`Repeat the same query, replacing ${t} with --output-cursor ${r}; retain any producer ${t} cursor from the original page.`]}):St("Query cursor version or payload is unsupported.",t)}return n}function Qs(e,t,r="--after"){let n=Xs(e,r);if(n.fingerprint!==t)throw St(`Query cursor does not match the current filters, sort, or query (${n.fingerprint} != ${t}).`,r);return{after_id:n.after_id,...n.after_index===void 0?{}:{after_index:n.after_index},...n.snapshot===void 0?{}:{snapshot:n.snapshot}}}function sP(e,t){return Qs(e,t).after_id}function Dv(e,t,r,n,o="--after"){if(t===void 0)return 0;let i=Qs(t,r,o),s=e.findIndex(a=>n(a)===i.after_id);if(s<0){if(i.after_index!==void 0)return Math.min(i.after_index,e.length);throw St(`Query cursor item ${i.after_id} is no longer present in this result set.`,o)}return s+1}function aP(e,t){if(t.cursor!==void 0&&Qs(t.cursor,t.fingerprint).snapshot!==t.snapshot)throw St("Query cursor does not match the requested snapshot.","--after");let r=Dv(e,t.cursor,t.fingerprint,t.readId),n=e.slice(r,r+t.limit),o=n.length>0&&r+n.length<e.length,i=n.at(-1);return{rows:n,has_more:o,...o&&i!==void 0?{next_cursor:fn(t.fingerprint,t.readId(i),r+n.length-1,t.snapshot)}:{}}}var cP=Object.freeze({version:Zs,max_length:lf});import{randomUUID as ME}from"node:crypto";import{randomUUID as xE}from"node:crypto";import{constants as mr}from"node:fs";import{lstat as xf,mkdir as NE,open as Df,rename as DE,rm as PE}from"node:fs/promises";import Fo from"node:path";import{constants as oE}from"node:fs";import de from"node:fs/promises";import Je from"node:path";import{randomUUID as $o}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="92573990-a040-526d-a0b1-b91d2ef401f1")}catch{}})();function Do(e){let t=Math.ceil(e.size/2);for(let r of e.keys()){if(t===0)return;e.delete(r),t-=1}}import Pv from"node:crypto";import{AsyncLocalStorage as Mv}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ced47074-06d3-53b9-af75-63586cbd4f6a")}catch{}})();var ea=new Mv,uf=1024;function $v(e){let t=Date.parse(e.clock);if(!Number.isFinite(t))throw new Error(`Invalid reproducible workspace clock: ${e.clock}`);if(!Number.isSafeInteger(e.tickMs)||e.tickMs<0)throw new Error("Reproducible workspace tickMs must be a non-negative integer");if(e.seed.trim().length===0)throw new Error("Reproducible workspace seed must not be empty");return{...e,clock:new Date(t).toISOString()}}function jv(e){let t={...$v(e),clockReads:0,tokenReads:0};return r=>ea.run(t,r)}async function mP(e,t){return jv(e)(t)}function ff(){let e=ea.getStore();if(e===void 0)return;let t=new Date(Date.parse(e.clock)+e.clockReads*e.tickMs).toISOString();return e.clockReads+=1,t}function pP(e){let t=ea.getStore();if(t===void 0)return;if(!Number.isSafeInteger(e)||e<0||e>uf)throw new Error(`Reproducible token length must be an integer between 0 and ${uf}`);let r="";for(;r.length<e;){let n=Pv.createHash("sha256").update(`${t.seed}\0${t.tokenReads}`).digest();t.tokenReads+=1;for(let o of n)if(r+=(o%36).toString(36),r.length===e)break}return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0bf155fc-c690-5318-ba1e-275f1787858b")}catch{}})();var Lv=/^([+-]?)(\d+)([hdwm])$/i,Fv=/^[+-]?\d+[hdwm](?:[+-]\d+[hdwm])+$/i,zv=/^(\d{4})(\d{2})(\d{2})$/,Uv=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,Hv=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})-(\d{2})(?:-(\d{2}))?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,qv=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,Vv=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/i;function Ie(){return ff()??new Date().toISOString()}function je(e){return Number.isFinite(Date.parse(e))}function _n(e){let t=Vv.exec(e);if(!t||!Number.isFinite(Date.parse(e)))return!1;let[,r,n,o,i,s,a,c,d]=t,[l,u,f,m,_,y]=[r,n,o,i,s,a].map(Number);return u>=1&&u<=12&&f>=1&&f<=na(l,u-1)&&m<=23&&_<=59&&y<=59&&(c===void 0||Number(c)<=23)&&(d===void 0||Number(d)<=59)}function ur(e){let t=/\.(\d+)(?:Z|[+-]\d{2}:\d{2})$/iu.exec(e)?.[1];return _n(e)&&(t===void 0||/^\d{0,3}0*$/u.test(t))}var Bv=1e4,Po=new Map;function mf(e){let t=Po.get(e);if(t!==void 0)return t;let r=Date.parse(e);return Po.size>=Bv&&Do(Po),Po.set(e,r),r}function oe(e,t){let r=mf(e),n=mf(t);return Number.isFinite(r)&&Number.isFinite(n)&&r!==n?r-n:e.localeCompare(t)}function wP(e,t){return!(t.deadlineBefore&&(!e.deadline||oe(e.deadline,t.deadlineBefore)>0)||t.deadlineAfter&&(!e.deadline||oe(e.deadline,t.deadlineAfter)<0)||t.updatedAfter&&oe(e.updated_at,t.updatedAfter)<0||t.updatedBefore&&oe(e.updated_at,t.updatedBefore)>0||t.createdAfter&&oe(e.created_at,t.createdAfter)<0||t.createdBefore&&oe(e.created_at,t.createdBefore)>0)}function ta(e){return e?`.${e.slice(1).padEnd(3,"0").slice(0,3)}`:""}function ra(e){if(!e)return"";if(e.toUpperCase()==="Z")return"Z";let t=/^([+-]\d{2})(\d{2})$/.exec(e);return t?`${t[1]}:${t[2]}`:e}function Wv(e,t,r){r&&r!==t&&(e.includes(r)||e.push(r))}function Gv(e){let t=[],r=d=>Wv(t,e,d),n=zv.exec(e);if(n){let[,d,l,u]=n;r(`${d}-${l}-${u}`)}let o=Uv.exec(e);if(o){let[,d,l,u,f,m,_,y,w]=o,v=_?`:${_}`:"";r(`${d}-${l}-${u}T${f}:${m}${v}${ta(y)}${ra(w)}`)}let i=Hv.exec(e);if(i){let[,d,l,u,f,m,_]=i,y=f?`:${f}`:"";r(`${d}T${l}:${u}${y}${ta(m)}${ra(_)}`)}let s=qv.exec(e);if(s){let[,d,l,u,f,m,_]=s,y=f?`:${f}`:"";r(`${d}T${l}:${u}${y}${ta(m)}${ra(_)}`)}let a=10,c=e.slice(0,a);if(Yv(c)){let d=a;for(;d<e.length&&Xv(e[d]);)d+=1;d<e.length&&r(`${c}T${e.slice(d)}`)}return t}function Kv(e){let t=Date.parse(e);if(Number.isFinite(t))return t;for(let r of Gv(e)){let n=Date.parse(r);if(Number.isFinite(n))return n}return Number.NaN}function Yv(e){if(e.length!==10)return!1;for(let t=0;t<e.length;t+=1){let r=e[t];if(t===4||t===7){if(r!=="-")return!1;continue}let n=r.charCodeAt(0);if(n<48||n>57)return!1}return!0}function Xv(e){return e?e===" "||e===" "||e===`
|
|
8
|
-
`||e==="\r"||e==="\f"||e==="\v":!1}function na(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}var Jv=["January","February","March","April","May","June","July","August","September","October","November","December"],Zv=/^(\d{4})-(\d{2})-(\d{2})/,Qv=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/;function eE(e,t,r){let n=Zv.exec(t)??Qv.exec(t);if(!n)return;let o=Number.parseInt(n[1],10),i=Number.parseInt(n[2],10),s=Number.parseInt(n[3],10),a=r?.trim()||"deadline";if(i<1||i>12)throw new g(`Invalid ${a} value "${e}". Month "${n[2]}" is out of range \u2014 use a month between 01 and 12.`,h.USAGE,{field:a,value:e});let c=na(o,i-1);if(s<1||s>c)throw new g(`Invalid ${a} value "${e}". ${Jv[i-1]} ${o} has ${c} days, so day "${n[3]}" does not exist. Use a real YYYY-MM-DD calendar date.`,h.USAGE,{field:a,value:e})}function tE(e,t){let r=new Date(e.getTime()),n=r.getUTCDate(),o=r.getUTCMonth()+t,i=r.getUTCFullYear()+Math.floor(o/12),s=(o%12+12)%12,a=Math.min(n,na(i,s));return r.setUTCFullYear(i,s,a),r}function vP(e,t=new Date,r="deadline"){let n=e.trim();if(n.toLowerCase()==="now")return t.toISOString();let o=Lv.exec(n);if(o){let s=o[1]==="-"?-1:1,a=Number.parseInt(o[2],10)*s,c=o[3].toLowerCase();if(c==="m")return tE(t,a).toISOString();let d=c==="h"?3600*1e3:c==="d"?1440*60*1e3:10080*60*1e3;return new Date(t.getTime()+a*d).toISOString()}eE(e,n,r);let i=Kv(n);if(!Number.isFinite(i)){let s=r.trim().length>0?r.trim():"deadline",a=Fv.test(n)?"Compound relative expressions like +3d+1h are not supported; use a single relative token (for example +3d) or an ISO/date string.":'Use ISO/date string input, "now", or relative +6h/-6h/+1d/-1d/+2w/-2w/+6m/-6m.';throw new g(`Invalid ${s} value "${e}". ${a}`,h.USAGE,{field:s,value:e})}return new Date(i).toISOString()}import oa from"node:fs/promises";import{createHash as rE}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d1f829a5-70d6-5096-86f7-717440dd67d5")}catch{}})();function pf(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function nE(e){if(!Number.isSafeInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return!pf(t,"ESRCH")}}function _f(e){let t=e.lastIndexOf(")");if(t<0)return null;let r=e.slice(t+2).trim().split(/\s+/u)[19];return r!==void 0&&/^\d+$/u.test(r)?r:null}async function fr(e){try{return _f(await oa.readFile(`/proc/${e}/stat`,"utf8"))}catch{return null}}async function yn(e=process.pid){let t=await fr(e);return{pid:e,...t===null?{}:{process_start_identity:t}}}async function hn(e,t,r){if(!nE(e.pid))return!1;let n=await fr(e.pid);return e.process_start_identity!==void 0&&n!==null?n===e.process_start_identity:t<=r}async function yf(){try{let[e,t]=await Promise.all([oa.readFile("/proc/sys/kernel/random/boot_id","utf8"),oa.readlink("/proc/self/ns/pid")]);return!/^[a-f0-9-]{36}\s*$/u.test(e)||!/^pid:\[\d+\]$/u.test(t)?null:rE("sha256").update(`${e.trim()}:${t}`).digest("hex")}catch{return null}}async function hf(){let[e,t]=await Promise.all([yf(),fr(process.pid)]);return e!==null&&t!==null?{host_identity:e,process_start_identity:t}:{}}async function ia(e){if(!e||typeof e.pid!="number"||!Number.isSafeInteger(e.pid)||e.pid<=0||typeof e.host_identity!="string"||typeof e.process_start_identity!="string"||!/^\d+$/u.test(e.process_start_identity))return"unknown";let t=await yf();if(t===null||t!==e.host_identity)return"unknown";try{process.kill(e.pid,0)}catch(n){return pf(n,"ESRCH")?"dead":"unknown"}let r=await fr(e.pid);return r===null?"unknown":r===e.process_start_identity?"alive":"dead"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c1ee0cca-ae03-50eb-8158-46510be6f43d")}catch{}})();function iE(e){let t;try{t=JSON.parse(e)}catch{return{info:null,warnings:["lock_info_invalid_json"]}}if(typeof t!="object"||t===null||Array.isArray(t))return{info:null,warnings:["lock_info_invalid_shape"]};let r=t,n=r.id,o=r.pid,i=r.owner,s=r.token,a=r.created_at,c=r.ttl_seconds;return typeof n!="string"||typeof o!="number"||!Number.isFinite(o)||typeof i!="string"||s!==void 0&&(typeof s!="string"||s.trim().length===0)||typeof a!="string"||typeof c!="number"||!Number.isFinite(c)?{info:null,warnings:["lock_info_invalid_shape"]}:{info:{id:n,pid:o,owner:i,...typeof s=="string"?{token:s}:{},created_at:a,ttl_seconds:c,host_identity:r.host_identity,process_start_identity:r.process_start_identity},warnings:[]}}async function Ot(e,t=!0){try{let r=await de.readFile(e,"utf8");return t&&await nr({path:e,scope:"project"}),iE(r)}catch(r){return me(r)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function Xe(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function sE(e,t,r=process.platform){if(Xe(e,"EEXIST"))return!0;if(!Xe(e,"EPERM")&&!Xe(e,"EACCES")&&!Xe(e,"EBUSY"))return!1;try{return await de.lstat(t),!0}catch(n){if(r!=="win32"||!me(n)&&!Xe(n,"EPERM")&&!Xe(n,"EACCES")&&!Xe(n,"EBUSY"))return!1}try{return await de.access(Je.dirname(t),oE.W_OK),!0}catch{return!1}}async function vf(e,t){await vo({path:e,scope:"project",op:t})}async function aE(e,t,r,n=$o()){return{...await hf(),id:e,pid:process.pid,owner:t,token:n,created_at:Ie(),ttl_seconds:r}}async function cE(e,t,r,n,o,i){i&&await de.mkdir(Je.dirname(e),{recursive:!0});let s=await Lo(e,t);if(s===null)throw await de.access(Je.dirname(e)),Object.assign(new Error("Lock initialization is contended"),{code:"EEXIST"});let a;try{let c=await de.open(e,"wx");try{try{let d=await aE(t,r,n,o);a=d.created_at,await c.writeFile(`${JSON.stringify(d,null,2)}
|
|
9
|
-
`,"utf8")}finally{await c.close()}}catch(d){throw await ca(e,"lock:release"),d}}finally{await s()}return await vf(e,"lock:create"),a}async function ca(e,t){try{return await de.unlink(e),await vf(e,t),!0}catch{return!1}}async function dE(e,t,r,n){let o=Date.now(),i=da;for(;;){let s=await Lo(e,t);if(s!==null){try{let d=await Ot(e,!1);sa(d.info,t,r,n)&&await ca(e,"lock:release")}finally{await s()}return}let a=await Ot(e,!1);if(!sa(a.info,t,r,n))return;let c=Date.now()-o;if(c>=Mo)return;await la(Math.min(i,Mo-c)),i=Math.min(i*2,jo)}}function sa(e,t,r,n){return e?.id===t&&e.pid===process.pid&&e.owner===r&&e.token===n}function Ef(e,t){let r=e?.created_at?Date.parse(e.created_at):Number.NaN;return(Number.isFinite(r)?Date.now()-r:Number.POSITIVE_INFINITY)>t*1e3}async function kf(e){return e!==null&&Number.isFinite(Date.parse(e.created_at))&&await ia(e)==="dead"}async function Sf(e,t){return Ef(e,t)||await kf(e)}async function Of(e,t,r){let{info:n}=await Ot(Ji(e,t),!1);return n!==null&&n.owner.startsWith(r)&&!await Sf(n,n.ttl_seconds)}function lE(e){return e?.owner?` (owner ${e.owner})`:""}var da=25,jo=200,Af=250,uE=12e4,fE=3,mE=".stale-cleanup",If="owner.json",Tf=1e4,Mo=Tf+jo,pE=60*6e4;function aa(e){if(typeof e=="string"){let t=e.trim();if(!/^\d+$/.test(t))return;let r=Number(t);return Number.isSafeInteger(r)?r:void 0}if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return Math.trunc(e)}function _E(e){let t=process.env.PM_LOCK_WAIT_MS,r=aa(t);if(r!==void 0)return r;let n=aa(e);return n!==void 0?n:0}function yE(e,t){return Math.min(_E(e),t??1/0)}function la(e){let t=Math.max(1,Math.round(e*(.5+Math.random())));return new Promise(r=>setTimeout(r,t))}async function Cf(e,t,r,n=0){let o=await ia(t),i=n>0?` across ${n} owner handoff(s)`:"",s=r>0?` after waiting ${r}ms${i}`:"";return new g(`Item ${e} is locked${lE(t)} (owner process ${o})${s}`,h.CONFLICT,{code:"lock_conflict",item_id:e,reason:`lock_owner_${o}`,required:"Wait for the owner to release the lock, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget when contention is expected. Inspect stale receipts with pm gc --scope locks --dry-run.",recovery:{retry_after_ms:Af,...r>0?{waited_ms:r,owner_handoffs:n}:{}}})}function hE(e,t){let r=Date.now(),n=r,o,i=0;return{startedAtMs:r,observe(s){let a=Date.now(),c=bE(s);o!==void 0&&c!==o&&(i+=1,n=a),o=c;let d=a-r,l=a-n;return{exhausted:e===0||l>=e||d>=t,elapsedMs:d,remainingMs:Math.min(e-l,t-d),ownerHandoffs:i}}}}function gE(e,t,r){return r!=="progress"||t!==void 0?e:Math.max(e,uE)}function bE(e){return e===null?"released":e.token??`${e.pid}:${e.owner}:${e.created_at}`}function wE(e){let t=Date.parse(e.acquiredAt)+e.ttlSeconds*1e3;return{owner:e.owner,acquired_at:e.acquiredAt,ttl_seconds:e.ttlSeconds,expires_at:new Date(t).toISOString()}}function vE(e,t,r,n){let o=`the lease acquired at ${t.acquiredAt} (ttl ${t.ttlSeconds}s)`;if(n==="fence_gate_unavailable")return{summary:`Lock for ${e} could not be verified before commit: ${o} could not enter its commit fence because the stale-cleanup gate stayed held.`,required:"Retry the same operation; this writer's change was not committed. Inspect pm gc --scope locks --dry-run if the stale-cleanup gate stays held."};let i=r===null?"the lock no longer exists":`it is now held by ${r.owner} since ${r.created_at}`;return{summary:`Lock for ${e} was lost before commit: ${o} is no longer owned by this writer, and ${i}.`,required:"Re-read the item and apply the mutation again; this writer's change was not committed and the newer value was kept. Keep mutation work shorter than locks.ttl_seconds, or raise locks.ttl_seconds for long-running callbacks."}}function gf(e,t,r,n){let{summary:o,required:i}=vE(e,t,r,n);return new g(`${o} Nothing was written.`,h.CONFLICT,{code:"lock_lost",item_id:e,reason:n,lease:wE(t),current_owner:r===null?null:{owner:r.owner,pid:r.pid,created_at:r.created_at,ttl_seconds:r.ttl_seconds},required:i,recovery:{retry_after_ms:Af}})}async function EE(e,t){let r=Date.now(),n=da;for(;;){let o=await Lo(e,t);if(o!==null)return o;let i=Date.now()-r;if(i>=Mo)return null;await la(Math.min(n,Mo-i)),n=Math.min(n*2,jo)}}async function kE(e,t,r,n){let o=await EE(e,t);if(o===null){let i=await Ot(e,!1);throw gf(t,r,i.info,"fence_gate_unavailable")}try{let i=await Ot(e,!1);if(!sa(i.info,t,r.owner,r.token))throw gf(t,r,i.info,i.info===null?"lease_released":"lease_taken_over");return await n()}finally{await o()}}function SE(e){if(typeof e=="function")return e;if(typeof e=="object"&&e!==null&&"release"in e){let t=e.release;return typeof t=="function"?t:null}return null}function OE(e,t,r,n){if(!r&&n){let o=t.warnings.length>0?` (${t.warnings.join(",")})`:"";throw new g(`Item ${e} lock is stale${o}; rerun with --force when supported for this command`,h.CONFLICT)}}function AE(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let r=t,n=r.pid,o=r.token,i=r.process_start_identity;return typeof n!="number"||!Number.isInteger(n)||n<=0||typeof o!="string"||o.length===0||i!==void 0&&(typeof i!="string"||!/^\d+$/u.test(i))?null:{pid:n,token:o,...typeof i=="string"?{process_start_identity:i}:{}}}async function Rf(e){try{return AE(await de.readFile(Je.join(e,If),"utf8"))}catch{return null}}async function ua(e){try{return await de.rm(e,{recursive:!0,force:!0}),!0}catch{return!1}}async function bf(e,t){let r=await Rf(e);r===null||r.token!==t||await ua(e)}async function wf(e){try{await de.mkdir(e)}catch(r){return Xe(r,"EEXIST"),null}let t={...await yn(),token:$o()};try{await de.writeFile(Je.join(e,If),`${JSON.stringify(t)}
|
|
10
|
-
`,"utf8")}catch{return await ua(e),null}return t}async function IE(e){let t;try{let n=await de.stat(e);if(t=Date.now()-n.mtimeMs,t<=Tf)return!1}catch(n){return me(n)}let r=await Rf(e);return r!==null&&await hn(r,t,pE)?!1:ua(e)}async function Lo(e,t){let r=`${e}${mE}`,n=await wf(r);if(n!==null)return async()=>bf(r,n.token);if(!await IE(r))return null;let o=await wf(r);return o===null?null:async()=>bf(r,o.token)}async function TE(e,t){let r=Je.join(Je.dirname(e),"recoveries");await de.mkdir(r,{recursive:!0}),await de.writeFile(Je.join(r,`${$o()}.json`),`${JSON.stringify({event:"owner_dead_recovery_attempt",recorded_at:Ie(),lock:JSON.parse(t)})}
|
|
11
|
-
`,{encoding:"utf8",flag:"wx",mode:384})}async function CE(e){let t=await Lo(e.lockPath,e.id);if(t===null)return{lockInfo:e.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{let r=await Ot(e.lockPath);if(r.info===null&&r.warnings.length===0)return{lockInfo:r,shouldRetryCreate:!0,staleRemovalCounted:!1};let n=await kf(r.info);if(!Ef(r.info,e.ttlSeconds)&&!n)return{lockInfo:r,shouldRetryCreate:!1,staleRemovalCounted:!1};if(OE(e.id,r,e.force||n,e.forceRequiredForStaleLock),e.staleRemovals>=fE)throw await Cf(e.id,r.info,Date.now()-e.startedAtMs);return n&&await TE(e.lockPath,JSON.stringify(r.info)),{lockInfo:r,shouldRetryCreate:await ca(e.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await t()}}async function le(e,t,r,n,o=!1,i=!0,s,a={}){return(await RE(e,t,r,n,o,i,s,a)).release}async function RE(e,t,r,n,o=!1,i=!0,s,a={}){let c=aa(a.maxWaitMs),d=await or("lock_acquire",{pm_root:e,id:t,ttl_seconds:r,owner:n,force:o,force_required_for_stale_lock:i,...c===void 0?{}:{max_wait_ms:c}});if(d.handled){let I=SE(d.result);if(I)return{release:async()=>{await Promise.resolve(I()),await or("lock_release",{pm_root:e,id:t,owner:n})},fence:z=>z()}}let l=Ji(e,t),u=yE(s,c),f=gE(u,c,a.waitPolicy),m=hE(u,f),_=m.startedAtMs,y=0,w=da,v=$o();for(;;)try{let I=await cE(l,t,n,r,v,a.createParentDirectories!==!1),z={owner:n,token:v,acquiredAt:I,ttlSeconds:r};return{release:async()=>{await dE(l,t,n,v),await or("lock_release",{pm_root:e,id:t,owner:n})},fence:X=>kE(l,t,z,X)}}catch(I){if(!await sE(I,l))throw new g(`Failed to acquire lock for ${t}: ${sd(I)}`,h.GENERIC_FAILURE);let z=await Ot(l);if(await Sf(z.info,r)){let ae=await CE({lockPath:l,id:t,ttlSeconds:r,force:o,forceRequiredForStaleLock:i,staleRemovals:y,waitBudgetMs:u,startedAtMs:_,fallbackLockInfo:z});if(z=ae.lockInfo,ae.staleRemovalCounted&&(y+=1),ae.shouldRetryCreate)continue}let X=m.observe(z.info);if(X.exhausted)throw await Cf(t,z.info,u===0?0:X.elapsedMs,X.ownerHandoffs);await la(Math.min(w,X.remainingMs)),w=Math.min(w*2,jo)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="71b65888-baa5-5c5f-a02c-4a0fd818fadb")}catch{}})();var Le={max_serving_rows:256,max_bytes:262144,max_event_bytes:32768,retained_byte_fraction:.5,max_events:2048,retention_days:30},Y=class extends TypeError{code="context_usage_validation_failed";constructor(t){super(t),this.name="ContextUsageValidationError"}};function At(e){let t=Date.parse(e.now??new Date().toISOString());if(!Number.isFinite(t))throw new Y("Context usage now must be a valid timestamp");return{iso:new Date(t).toISOString(),ms:t}}function Pf(e){let t=e.maxBytes??Le.max_bytes,r=e.maxEvents??Le.max_events,n=e.retentionDays??Le.retention_days;if(!Number.isSafeInteger(t)||t<1024||t>Le.max_bytes||!Number.isSafeInteger(r)||r<1||!Number.isFinite(n)||n<=0)throw new Y("Context usage retention requires positive maxEvents and retentionDays, and maxBytes from 1024 through 262144");return{maxBytes:t,maxEvents:r,cutoff:At(e).ms-n*864e5}}async function Mf(e,t){if(!(await xf(Fo.dirname(e))).isDirectory())throw new Y("Context usage runtime must be a real directory");try{if((await xf(e)).isSymbolicLink())throw new Y("Context usage ledger must not be a symbolic link")}catch(n){if(!me(n))throw n}let r=await Df(e,t|mr.O_NOFOLLOW|mr.O_NONBLOCK,384);try{let n=await r.stat();if(!n.isFile()||n.nlink!==1)throw new Y("Context usage ledger must be an unshared regular file");return r}catch(n){throw await r.close(),n}}async function zo(e){let t=Pf(e);try{let r=await Mf(Fo.join(e.pmRoot,"runtime","context-usage.jsonl"),mr.O_RDONLY);try{let n=(await r.stat()).size,o=Math.max(0,n-t.maxBytes),i=Buffer.alloc(Math.min(n,t.maxBytes)),{bytesRead:s}=await r.read(i,0,i.length,o),a=i.subarray(0,s).toString("utf8");return(o>0?a.includes(`
|
|
12
|
-
`)?a.slice(a.indexOf(`
|
|
13
|
-
`)+1):"":a).split(`
|
|
14
|
-
`).flatMap(c=>{try{let d=JSON.parse(c);return d&&Date.parse(d.at)>=t.cutoff?[d]:[]}catch{return[]}}).slice(-t.maxEvents)}finally{await r.close()}}catch{return[]}}function Nf(e,t,r){let n=[],o=0;for(let i=e.length-1;i>=0&&n.length<r;i-=1){let s=`${JSON.stringify(e[i])}
|
|
15
|
-
`;if(o+=Buffer.byteLength(s),o>t)break;n.push(s)}return n.reverse().join("")}async function gn(e,t,r){let n=Pf(e),o=Fo.join(e.pmRoot,"runtime","context-usage.jsonl"),i=Math.floor(n.maxBytes*Le.retained_byte_fraction),s=Math.min(Le.max_event_bytes,i);if(t.some(f=>Buffer.byteLength(`${JSON.stringify(f)}
|
|
16
|
-
`)>s))throw new Y("Context usage event exceeds the declared byte ceiling");let a=t.filter(f=>Date.parse(f.at)>=n.cutoff),c=Nf(a,i,n.maxEvents),d=performance.now(),l=await le(e.pmRoot,"context-usage-ledger",30,`context-usage:${process.pid}`,!1,!1,3e3),u=performance.now()-d;try{await NE(Fo.dirname(o),{recursive:!0});let f=await Mf(o,mr.O_WRONLY|mr.O_CREAT|mr.O_APPEND);try{let m=(await f.stat()).size,_=r===void 0?void 0:await zo(e);if(_?.some(I=>I.kind==="delivery"&&I.serve_id===r))return{written_bytes:0,ledger_bytes:m,compacted:!1,lock_wait_ms:u};if(!(e.maxEvents!==void 0||e.retentionDays!==void 0)&&m+Buffer.byteLength(c)<=n.maxBytes)return await f.writeFile(c,"utf8"),{written_bytes:Buffer.byteLength(c),ledger_bytes:m+Buffer.byteLength(c),compacted:!1,lock_wait_ms:u};let y=Nf([..._??await zo(e),...a],i,n.maxEvents),w=`${o}.${process.pid}.${xE()}.tmp`,v=await Df(w,"wx",384);try{try{await v.writeFile(y,"utf8")}finally{await v.close()}return await f.close(),f=void 0,await DE(w,o),{written_bytes:Buffer.byteLength(y),ledger_bytes:Buffer.byteLength(y),compacted:!0,lock_wait_ms:u}}finally{await PE(w,{force:!0})}}finally{await f?.close()}}finally{await l()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e76b38ce-b2aa-589b-9d17-0952eca9e7a2")}catch{}})();var $E=864e5,Uo=Symbol.for("@unbrained/pm-cli/context-usage-serving-receipt");function Z(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function XP(e,t){let r=Z(e);r!==null&&t!==null&&(r[Uo]=t)}function pr(e,t){let r=Z(e),n=Z(t),o=r?.[Uo];n!==null&&o!==void 0&&(n[Uo]=o)}function jE(e){return Z(e)?.[Uo]??null}function jf(e){let t=Z(e);for(let r of["read_output","context_intent"])if(Z(t?.[r])?.result_omitted===!0)return!0;return!1}function Ze(e,t){typeof t=="string"&&t.trim().length>0&&e.add(t.trim())}function Lf(e,t){if(Array.isArray(t))for(let r of t)Ze(e,Z(r)?.id)}function $f(e,t){if(Array.isArray(t))for(let r of t)Ze(e,r)}function LE(e,t){let r=Z(e.recommended)===null?[]:[e.recommended];for(let n of["ready","decision_needed","gate_needed","containers","blocked","held_by_others"])Array.isArray(e[n])&&r.push(...e[n]);for(let n of r){let o=Z(n);Ze(t,o?.id);for(let i of Array.isArray(o?.blockers)?o.blockers:[])Ze(t,Z(i)?.id);for(let i of Array.isArray(o?.unblocks)?o.unblocks:[])Ze(t,i)}}function FE(e,t){for(let r of["high_level","low_level","blocked_fallback","recently_created","unparented","activity","progress","blockers","staleness"])Lf(t,e[r]);for(let r of Array.isArray(e.blockers)?e.blockers:[])Ze(t,Z(r)?.blocked_by);zE(e,t)}function zE(e,t){for(let o of Array.isArray(e.hierarchy)?e.hierarchy:[]){let i=Z(o);Ze(t,i?.id),Lf(t,i?.children)}for(let o of["files","workload"])for(let i of Array.isArray(e[o])?e[o]:[])$f(t,Z(i)?.items);let r=Z(e.agenda);for(let o of Array.isArray(r?.events)?r.events:[])Ze(t,Z(o)?.item_id);let n=Z(e.tests);$f(t,n?.items_failing)}function UE(e,t){let r=Z(e);if(r===null||jf(e))return[];let n=new Set;return t==="next"?LE(r,n):FE(r,n),[...n]}async function JP(e){let t=jE(e.result);if(t===null)return!1;let r=jf(e.result);return await HE({pmRoot:e.pmRoot,receipt:t,deliveredItemIds:UE(e.result,t.surface),resultOmitted:r}),!0}async function ZP(e){if([process.env.PM_CONTEXT_USAGE_DISABLED==="1",e.enabled===!1].includes(!0))return null;if(!e.author.trim()||e.rows.some(o=>!o.id.trim()||!Number.isInteger(o.rank)||o.rank<1))throw new Y("Context usage serving requires an author and valid ranked rows");let t=e.rows.map(o=>({id:o.id.trim(),rank:o.rank,included:o.included}));if(new Set(t.map(o=>o.id)).size!==t.length)throw new Y("Context usage serving requires unique normalized row ids");let r=t.slice(0,Le.max_serving_rows),n={serve_id:ME(),author:e.author.trim(),surface:e.surface,rows:t,recorded_item_ids:r.map(o=>o.id)};return n.storage=await gn(e,[{kind:"serve",schema_version:2,serve_id:n.serve_id,at:At(e).iso,author:e.author.trim(),surface:e.surface,profile:e.profile.trim()||"balanced",rows:r,candidate_count:t.length,omitted_row_count:t.length-r.length,result_omitted:!1,packed_item_ids:r.filter(o=>o.included).map(o=>o.id)}]),n}async function HE(e){if(e.receipt===null||process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1)return;let t=new Set(e.receipt.rows.map(i=>i.id)),r=[...new Set(e.deliveredItemIds.map(i=>i.trim()))];if(r.some(i=>i.length===0||!t.has(i))||e.resultOmitted&&r.length>0)throw new Y("Context usage delivery requires emitted ranked ids and zero ids for an omitted result");let n=new Set(e.receipt.recorded_item_ids??e.receipt.rows.map(i=>i.id)),o={kind:"delivery",schema_version:2,serve_id:e.receipt.serve_id,at:At(e).iso,author:e.receipt.author,surface:e.receipt.surface,result_omitted:e.resultOmitted,delivered_item_ids:r.filter(i=>n.has(i))};await gn(e,[o],o.serve_id)}async function QP(e){if(!(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1)){if(!e.author.trim()||!e.itemId.trim()||!e.intent.trim())throw new Y("Context usage touch requires author, itemId, and intent");await gn(e,[{kind:"touch",at:At(e).iso,author:e.author.trim(),item_id:e.itemId.trim(),intent:e.intent.trim()}])}}async function e1(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1||e.itemIds.length===0)return;let t=e.author.trim(),r=e.intent.trim();if(!t||!r)throw new Y("Context usage touch requires author and intent");let n=new Set;for(let s of e.itemIds){if(typeof s!="string")throw new Y("Context usage touch requires string itemIds");let a=s.trim();if(!a)throw new Y("Context usage touch requires non-empty itemId");n.add(a)}let o=At(e).iso,i=[...n].map(s=>({kind:"touch",at:o,author:t,item_id:s,intent:r}));await gn(e,i)}function qE(e,t,r,n){return e.find(({entry:o,time:i})=>o.item_id===t&&i>=r&&i-r<=n)?.time}function VE(e,t){let r=new Map;for(let n of e)n.kind==="delivery"&&n.schema_version===2&&n.author===t&&!r.has(n.serve_id)&&r.set(n.serve_id,n);return r}async function t1(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1)return{affinity:{},positive_judgments:0,serving_events:0,untrusted_serving_events:0};let t=await zo(e),r=At(e).ms,n=(e.horizonHours??24)*36e5;if(![Number.isFinite(n),n>0].every(Boolean))throw new Y("Context usage horizonHours must be positive");let o=e.author.trim(),i=t.filter(f=>f.kind==="touch").filter(f=>f.author===o).map(f=>({entry:f,time:Date.parse(f.at)})),s=new Map,a=0,c=0,d=0,l=VE(t,o);t.filter(f=>f.kind==="serve").filter(f=>f.author===o).forEach(f=>{if(![f.schema_version===2,!!f.serve_id].every(Boolean)){c+=1;return}a+=1;let m=Date.parse(f.at),_=l.get(f.serve_id),y=new Set(_?.delivered_item_ids??[]);for(let w of f.rows){if(!y.has(w.id))continue;let v=qE(i,w.id,m,n);if(v===void 0)continue;d+=1;let I=Math.max(0,(r-v)/$E);s.set(w.id,(s.get(w.id)??0)+Math.exp(-I/14))}});let u=Math.max(0,...s.values());return{affinity:Object.fromEntries([...s.entries()].map(([f,m])=>[f,u===0?.05:.05+.95*m/u])),positive_judgments:d,serving_events:a,untrusted_serving_events:c}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="417afa3c-d34b-53d9-b273-86903e17576f")}catch{}})();var zf=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]),Uf=new BE;function WE(){return Uf.getStore()??zf}function m1(e,t){return Uf.run(KE(e.workspaceContracts,e.packageContracts),t)}function GE(e,t){let r=e.command.trim().toLowerCase(),n=e.intent.trim().toLowerCase(),o=`${r}:${n}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(r)||!/^[a-z0-9][a-z0-9-]*$/.test(n))throw new TypeError(`Invalid context intent command or name: ${o}`);if(e.description.trim().length===0)throw new TypeError(`Context intent ${o} requires a non-empty description`);if(!Number.isSafeInteger(e.token_budget)||e.token_budget<=0)throw new TypeError(`Context intent ${o} requires a positive integer token_budget`);let i=[...new Set(e.included_field_groups.map(s=>s.trim()).filter(Boolean))];if(i.length===0)throw new TypeError(`Context intent ${o} requires included_field_groups`);return{command:r,intent:n,description:e.description.trim(),included_field_groups:i,token_budget:e.token_budget,source:t}}function KE(e=[],t=[]){let r=[{source:"core",contracts:zf,allowOverride:!1},{source:"package",contracts:t,allowOverride:!1},{source:"workspace",contracts:e,allowOverride:!0}],n=new Map,o=new Set;for(let i of r){o.clear();for(let s of i.contracts){let a=GE(s,i.source),c=`${a.command}:${a.intent}`;if(o.has(c))throw new TypeError(`Duplicate context intent declaration: ${c}`);if(o.add(c),!i.allowOverride&&n.has(c))throw new TypeError(`Duplicate context intent declaration: ${c}`);n.set(c,a)}}return[...n.values()].sort((i,s)=>i.command.localeCompare(s.command)||i.intent.localeCompare(s.intent))}function Hf(e,t,r=WE(),n=[]){let o=e.trim().toLowerCase(),i=t.trim().toLowerCase(),s=r.find(f=>f.command===o&&f.intent===i);if(s)return{...s,source:s.source??"core"};let a=r.filter(f=>f.command===o).map(f=>f.intent);if(a.length===0)return;let c=a.map(f=>{let m=Array.from({length:i.length+1},(_,y)=>y);for(let _=1;_<=f.length;_+=1){let y=m[0];m[0]=_;for(let w=1;w<=i.length;w+=1){let v=m[w];m[w]=Math.min(m[w]+1,m[w-1]+1,y+(f[_-1]===i[w-1]?0:1)),y=v}}return{candidate:f,distance:m[i.length]}}).sort((f,m)=>f.distance-m.distance||f.candidate.localeCompare(m.candidate))[0].candidate,d=[o,...n,"--for",i],l=[o,...n,"--for",c],u=ir(l);throw new g(`Unknown context intent "${i}" for ${o}. Did you mean "${c}"?`,h.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",flag:"--for",value:i,required:`Use a declared ${o} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[u],recovery:{recovery_mode:"compact",attempted_command:ir(d),allowed_values:[...a].sort(),suggested_retry:u,suggested_retry_args:l}})}var qf={context:(e,t,r)=>{e.section===void 0&&e.depth===void 0&&(e.section=t.intent==="handoff"?["activity","progress","blockers"]:["hierarchy","blockers","activity"]),e.depth===void 0&&(e.depth=t.intent==="handoff"?"deep":"standard");let n=qo(e.tokenBudget,t.token_budget),o=Vo("context",t.intent,n,r),i=It(e.limit),s=String(i===void 0?o:Math.min(i,o));(e.limit===void 0||i!==void 0)&&(e.limit=s),e.activityLimit===void 0&&(e.activityLimit=s)},get:e=>{e.depth===void 0&&e.fields===void 0&&(e.depth="standard")},list:(e,t,r)=>{e.brief===void 0&&e.compact===void 0&&e.full===void 0&&e.fields===void 0&&(e.fields="id,title,status,type,priority,parent,assignee,risk,blocked_by");let n=qo(e.tokenBudget,t.token_budget),o=Vo("list",t.intent,n,r),i=It(e.limit);(e.limit===void 0||i!==void 0)&&(e.limit=String(i===void 0?o:Math.min(i,o)))},next:e=>{e.readyOnly===void 0&&(e.readyOnly=!0)},search:(e,t,r)=>{e.compact===void 0&&e.full===void 0&&e.fields===void 0&&(e.compact=!0);let n=qo(e.tokenBudget,t.token_budget),o=Vo("search",t.intent,n,r),i=It(e.limit);(e.limit===void 0||i!==void 0)&&(e.limit=String(i===void 0?o:Math.min(i,o)))}};function p1(e,t,r=[]){let n=t.tokenBudget??t.token_budget;if(typeof t.for!="string"){if(n!==void 0&&(e==="get"||e==="list"||e==="search"))throw new g("--token-budget requires a declared context intent selected with --for",h.USAGE,{code:"missing_required_option",field:"for",required:"Select a context intent with --for when setting --token-budget.",why:"A token-budget override has no projection contract to constrain without a selected intent.",nextSteps:["Retry with --for <intent> --token-budget <n>, or omit --token-budget."]});if(t.tokenBudget!==void 0||t.token_budget===void 0)return t;let a={...t,tokenBudget:n};return delete a.token_budget,a}let o=Hf(e,t.for,void 0,r),i=It(n)!==void 0,s={...t};return s.tokenBudget===void 0&&n!==void 0&&(s.tokenBudget=n),delete s.token_budget,s.tokenBudget===void 0&&(s.tokenBudget=String(o.token_budget)),qf[e](s,o,i),s}var YE={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},Ho=256;function fa(e){return Array.isArray(e)?e.map(fa):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,fa(r)])):typeof e=="string"&&e.length>240?`${We(e,240)}\u2026`:e}function It(e){let t=typeof e=="number"?e:typeof e=="string"&&/^\d+$/u.test(e.trim())?Number(e):Number.NaN;return Number.isSafeInteger(t)&&t>0?t:void 0}function qo(e,t){let r=It(e);if(r===void 0)return t;if(r<Ho)throw new g(`Context intent token budget must be at least ${Ho}`,h.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",value:String(e),required:`Use an integer token budget of at least ${Ho}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${Ho} or omit the override.`]});return r}function Vo(e,t,r,n){if(e==="get"||e==="next")return;let o=e==="context"&&t==="orient",i=e==="context"?o?1200:800:e==="list"?520:480,s=e==="context"?o?600:500:16,a=Math.max(e==="context"?1:2,Math.floor((r-i)/s));return n?a:Math.min(e==="context"?20:100,a)}function Qe(e,t){let r=t.estimated_tokens;for(;;){t.estimated_tokens=r;let n=Math.ceil(Buffer.byteLength(JSON.stringify(e),"utf8")/4);if(n===r)return;r=n}}var Ff={context:["high_level","low_level","blocked_fallback","recently_created","unparented","hierarchy","activity","blockers"],get:["children"],list:["items"],next:["ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items"]};function Vf(e){try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof t.fingerprint!="string"||!Number.isSafeInteger(t.after_index)?void 0:{fingerprint:t.fingerprint,after_index:t.after_index,...typeof t.snapshot=="string"?{snapshot:t.snapshot}:{}}}catch{return}}function XE(e){if(e===null||typeof e!="object")return;if(typeof e.id=="string")return e.id;let t=e.item?.id;return typeof t=="string"?t:void 0}function JE(e,t,r){let n=!1;for(;;){if(Qe(e,t),t.estimated_tokens<=t.token_budget||r.length<=1)return n;let o=Buffer.byteLength(JSON.stringify(r),"utf8"),i=(t.estimated_tokens-t.token_budget)*4;r.splice(-Math.min(r.length-1,Math.max(1,Math.ceil(i/Math.max(1,Math.ceil(o/r.length)))))),n=!0}}function ZE(e,t,r){let n=e.items,o=typeof e.next_cursor=="string",i=o?e.next_cursor:r.after;if(!Array.isArray(n)||typeof i!="string")return!1;let s=Vf(i);if(s===void 0)return!1;let a=n.length,c=[...n],d=!1;for(;;){if(d=JE(e,t,n)||d,!d)return!1;let l=XE(n.at(-1));if(l===void 0)return n.splice(0,n.length,...c),Qe(e,t),!1;if(e.next_cursor=fn(s.fingerprint,l,o?s.after_index-(a-n.length):s.after_index+n.length,s.snapshot),Qe(e,t),t.estimated_tokens<=t.token_budget||n.length<=1)break}return typeof e.count=="number"&&(e.count=n.length),typeof e.applied_limit=="number"&&(e.applied_limit=n.length),!0}function QE(e,t,r,n){if(e==="list"||e==="search")return ZE(t,r,n);if(e!=="next"||typeof t.next_cursor=="string")return!1;let o=!1;for(;;){if(Qe(t,r),r.estimated_tokens<=r.token_budget)return o;let i=Ff[e].map(f=>({key:f,rows:Array.isArray(t[f])?t[f]:[]})).filter(({rows:f})=>f.length>0).sort((f,m)=>m.rows.length-f.rows.length||f.key.localeCompare(m.key))[0];if(i===void 0)return o;let s=Ff[e].reduce((f,m)=>f+(Array.isArray(t[m])?t[m].length:0),0);if(s<=1)return o;let a=Math.min(i.rows.length,s-1),c=Buffer.byteLength(JSON.stringify(i.rows),"utf8"),d=Math.max(1,Math.ceil(c/i.rows.length)),l=(r.estimated_tokens-r.token_budget)*4,u=Math.min(a,Math.max(1,Math.ceil(l/d)));i.rows.splice(-u,u),o=!0}}function e0(e,t,r){if(typeof t.for!="string")return r;let n=e.startsWith("list-")?"list":e;if(!(n in qf))return r;let o=n,i=Hf(o,t.for),s=qo(t.tokenBudget??t.token_budget,i.token_budget),a={command:o,intent:i.intent,source:i.source,included_field_groups:[...i.included_field_groups],token_budget:s,declared_token_budget:i.token_budget,token_budget_override:s-i.token_budget,estimated_tokens:0,within_budget:!0,degradation:YE[o],declaration_feasible:!0,result_omitted:!1},c={...r},d=Vo(o,i.intent,a.token_budget,It(t.tokenBudget??t.token_budget)!==void 0);if(d!==void 0){let u=It(t.limit),f=u!==void 0&&u<d;a.budget_derived_limit=d,a.binding_constraint=f?"explicit_limit":"token_budget",a.limit_reason=f?"The caller supplied a smaller row limit than the budget-derived ceiling.":"The selected intent token budget constrains the effective row ceiling.",c.budget_derived_limit=d}let l={...c,context_intent:a};return Qe(l,a),a.estimated_tokens>a.token_budget&&(a.degradation="recursive_budget_compaction",l={...fa(c),context_intent:a},Qe(l,a)),a.estimated_tokens>a.token_budget&&QE(o,l,a,t)&&(a.degradation="budget_row_compaction",Qe(l,a)),a.declaration_feasible=a.estimated_tokens<=a.declared_token_budget,a.estimated_tokens>a.token_budget&&(a.degradation="budget_receipt_only",a.result_omitted=!0,a.within_budget=!1,l={budget_exceeded:{omitted_result:!0,reason:a.token_budget_override===0?"declared_budget_infeasible":"effective_budget_infeasible",restore_with:n0(e,o,i.intent,a,c)},context_intent:a}),l}var t0=["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"];function r0(e,t){if(typeof e.after!="string"||e.after.length===0)return t;let r=Vf(e.after)?.fingerprint??"opaque_cursor",n={...t};for(let o of t0)delete n[o];return n.continuation_contract={fingerprint:r,metadata:"reference",restore_with:"omit --after"},n}function ma(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function n0(e,t,r,n,o){let i=t==="get"&&ma(o.item)&&typeof o.item.id=="string"?o.item.id:t==="search"&&typeof o.query=="string"?o.query:void 0,s=i===void 0?"":` '${i.replaceAll("'",`'"'"'`)}'`,a=t==="get"?"":` --limit ${n.budget_derived_limit??1}`;return`pm ${e}${s} --for ${r} --token-budget ${Math.ceil(n.estimated_tokens/100)*100}${a}`}function _r(e,t){if(ma(e))return typeof e[t]=="number"?e[t]:void 0}function o0(e,t){let r=e;for(let n=0;n<8;n+=1){let o=_r(r.context_intent,"estimated_tokens"),i=_r(r.read_output,"estimated_tokens"),s=_r(r.read_session,"spent_this_call_tokens");if(ma(r.context_intent)&&Qe(r,r.context_intent),r=Ks(r,t),_r(r.context_intent,"estimated_tokens")===o&&_r(r.read_output,"estimated_tokens")===i&&_r(r.read_session,"spent_this_call_tokens")===s)break}return r}function Bf(e,t,r){let n=du(e,ku(e??"",r)),o=typeof n=="object"&&n!==null&&!Array.isArray(n)?rf(e??"",{...t,outputRowContract:t.outputRowContract===!0||t.output_row_contract===!0},r0(t,e0(e??"",t,n))):n;if(pr(r,o),t.outputRowContract===!0||t.output_row_contract===!0||typeof o!="object"||o===null||Array.isArray(o)||!Object.hasOwn(o,"row_contract"))return o;let i=Object.fromEntries(Object.entries(o).filter(([a])=>a!=="row_contract"));Object.defineProperty(i,"row_contract",{value:o.row_contract,enumerable:!1,configurable:!0});let s=o0(i,t);return delete s.row_contract,pr(o,s),s}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cb1266f3-8375-586f-87c6-356cf7843969")}catch{}})();var yr=["result_rows","envelope","diagnostics","hints"],i0=/^(?:items|results|rows|ready|blocked|recommended|decision_needed|children|dependencies|events|matches|commands|tools)$/u,s0=/^(?:diagnostics|errors?|warnings?|findings|violations|failures?)$/u,a0=/^(?:hints?|suggestions?|next_steps?|recovery|remediation|examples?)$/u,c0=8;function pa(e){return Buffer.byteLength(e,"utf8")}function Wf(e){return pa(JSON.stringify(e)??"null")}function d0(e,t){return s0.test(e)?"diagnostics":a0.test(e)?"hints":i0.test(e)||Array.isArray(t)?"result_rows":"envelope"}function l0(e){let t={result_rows:0,envelope:0,diagnostics:0,hints:0};if(typeof e!="object"||e===null||Array.isArray(e))return t[Array.isArray(e)?"result_rows":"envelope"]=Wf(e),t;for(let[r,n]of Object.entries(e))t[d0(r,n)]+=Wf({[r]:n});return Object.values(t).every(r=>r===0)&&(t.envelope=1),t}function u0(e,t){let r=yr.reduce((s,a)=>s+t[a],0),n=yr.map(s=>({section:s,value:e*t[s]/r})),o={result_rows:0,envelope:0,diagnostics:0,hints:0};for(let s of n)o[s.section]=Math.floor(s.value);let i=e-yr.reduce((s,a)=>s+o[a],0);for(let s of[...n].sort((a,c)=>c.value-Math.floor(c.value)-(a.value-Math.floor(a.value))||yr.indexOf(a.section)-yr.indexOf(c.section))){if(i===0)break;o[s.section]+=1,i-=1}return o}function Gf(e,t){return typeof e=="object"&&e!==null&&!Array.isArray(e)?{...e,token_accounting:t}:{result:e,token_accounting:t}}function Kf(e,t){let r=pa(t(e)),n=u0(r,l0(e)),o=Object.fromEntries(yr.map(a=>[a,{bytes:n[a],estimated_tokens:Et(n[a])}])),i={version:1,measurement_scope:"output_before_token_accounting",estimator:"ceil(utf8_bytes / 4)",total_bytes:r,total_estimated_tokens:Et(r),sections:o,accounting_receipt_bytes:0,accounting_receipt_estimated_tokens:0,excluded_fields:["token_accounting"],section_allocation:"proportional_canonical_json"},s=Gf(e,i);for(let a=0;a<c0;a+=1){let c=pa(t(s))-r;if(c===i.accounting_receipt_bytes)return s;i={...i,accounting_receipt_bytes:c,accounting_receipt_estimated_tokens:Et(c)},s=Gf(e,i)}return s}import{encode as _a}from"@toon-format/toon";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8936e93f-25bf-58cc-ba91-37cc2677c5d2")}catch{}})();function Yf(e){let t=[...new Set(e.flatMap(i=>Object.keys(i)))],r=t.filter(i=>e.some(s=>{let a=s[i];return a!==null&&typeof a=="object"})),n=new Set(r),o=[];return{rows:e.map((i,s)=>Object.fromEntries(t.map(a=>{if(!Object.hasOwn(i,a))return o.push([s,a]),[a,null];let c=i[a];return[a,n.has(a)?JSON.stringify(c):c]}))),encoding:{json_columns:r,absent:o}}}function g1(e){let t=new Set(e.encoding.json_columns),r=new Set(e.encoding.absent.map(([n,o])=>JSON.stringify([n,o])));return e.rows.map((n,o)=>Object.fromEntries(Object.entries(n).flatMap(([i,s])=>r.has(JSON.stringify([o,i]))?[]:[[i,t.has(i)?JSON.parse(String(s)):s]])))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dc76b081-02dc-5b09-ab40-cd57c733b3ad")}catch{}})();var v1=["id","title","status","type","priority","parent","updated_at"],Bo=["id","status","type","title"],E1={list:"brief","list-all":"full","list-draft":"full","list-open":"brief","list-in-progress":"brief","list-blocked":"brief","list-closed":"brief","list-canceled":"full"},f0=["tree_depth","tree_parent","tree_children","tree_title"];function k1(e=[]){return[...new Set([...Ee,"body",...f0,...e])].flatMap(t=>[t,`item.${t}`]).sort()}var S1=["brief","standard","deep"],m0=["body","linked","claim_state","children","schedule","blockers"],p0=["linked.files","linked.tests","linked.docs"],_0=["claim_state.claimed","claim_state.assignee","claim_state.last_claim","claim_state.last_release"],y0=["schedule.deadline","schedule.start_at","schedule.end_at","schedule.location","schedule.reminders","schedule.events"];function O1(e=[]){return[...[...new Set([...Ee,...e,"notes_count","tests_count","collection_counts"])].flatMap(t=>[t,`item.${t}`]),...m0,...p0,..._0,...y0].sort()}var A1=["id","title","status","type","priority","updated_at","score","matched_fields"],h0=["score","matched_fields","highlights"],Xf=["id","title","description","type","status","priority","tags","created_at","updated_at","deadline","assignee","author","estimated_minutes","acceptance_criteria","dependencies","comments","notes","learnings","reminders","events","files","tests","docs","close_reason","parent","reviewer","risk","confidence","sprint","release","blocked_by","blocked_reason","reporter","severity","environment","repro_steps","resolution","expected_result","actual_result","affected_version","fixed_version","component","regression","customer_impact","definition_of_ready","order","rank","goal","objective","value","impact","outcome","why_now","plan"];function I1(e=[]){let t=[...new Set(e)];return[...h0,...Xf,...Xf.map(r=>`item.${r}`),...t,...t.map(r=>`item.${r}`)].sort()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="95103919-d686-5c3b-bd51-928f5b2314ef")}catch{}})();function hr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function g0(e){if(!hr(e))return!1;let t=e.fields;return e.mode==="brief"&&Object.keys(e).length===2&&Array.isArray(t)&&(t.length===Bo.length||t.length===Bo.length+1&&t.at(-1)==="priority")&&Bo.every((r,n)=>t[n]===r)}function b0(e,t){return typeof e.has_more=="boolean"&&e.truncated===e.has_more&&e.count===t&&typeof e.total=="number"&&Number.isSafeInteger(e.total)&&(e.has_more?e.total>t&&typeof e.next_cursor=="string"&&e.next_cursor.length>0:e.total===t&&e.next_cursor==null)}function w0(e){return hr(e)&&(e.status==="complete"||e.status==="unchecked")&&e.unreadable_item_count===0&&e.unreadable_directory_count===0}function v0(e){if(!hr(e)||!Array.isArray(e.omitted_field_groups))return!1;let t=e.omitted_field_groups,r=t[0];return e.has_omissions===!0&&e.omitted_field_group_count===1&&Object.keys(e).length===3&&t.length===1&&hr(r)&&Object.keys(r).length===2&&r.name==="full_item_fields"&&r.restore_with==="--full"}function Jf(e){if(!hr(e)||!Array.isArray(e.items)||Object.hasOwn(e,"details")||!g0(e.projection)||!w0(e.completeness)||!b0(e,e.items.length)||!v0(e.omission_receipt))return e;let{total:t,has_more:r,truncated:n,next_cursor:o,completeness:i,projection:s,now:a,omission_receipt:c,sorting:d,...l}=e,u=i.status==="complete"&&!r&&Object.keys(i).length===3,{unreadable_item_count:f,unreadable_directory_count:m,..._}=i;return{...l,...u?{}:{total:t,has_more:r,completeness:_},...r?{next_cursor:o}:{},...hr(d)&&d.sort==="default"&&d.order==="asc"&&Object.keys(d).length===2?{}:{sorting:d},details:"--full"}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dd3b19cb-eda3-5ee9-a838-f0abaa5cc8ea")}catch{}})();var E0=new Set(Object.values(h)),k0=new Map([["notes_count","notes"],["tests_count","tests"]]),ya="__pm_native_output",Zf=!1;function H(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wa(e){let t={read_output:{result_omitted:!0}};pr(e,t),wo(t)}function S0(e,t,r){if(r){wo(e);return}wa(t)}function O0(e){if(!H(e)||e[ya]!==!0)return e;let{[ya]:t,...r}=e;return r}function ha(e){return typeof e=="object"&&e!==null&&e.code==="EPIPE"}function A0(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.SUCCESS)}function I0(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.GENERIC_FAILURE)}function ga(e){if(e==="stdout"){A0();return}I0()}function Qf(e){let t=e instanceof Error?e:new Error(String(e));setImmediate(()=>{throw t})}function T0(){Zf||(Zf=!0,process.stdout.on("error",e=>{if(ha(e)){ga("stdout");return}Qf(e)}),process.stderr.on("error",e=>{if(ha(e)){ga("stderr");return}Qf(e)}))}function em(e,t){T0();try{return e==="stdout"?process.stdout.write(t):process.stderr.write(t),!0}catch(r){if(ha(r))return ga(e),!1;throw r}}function C0(e){return em("stdout",e)}function bn(e){return em("stderr",e)}function tm(e){return typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"?String(e):e===null?"null":JSON.stringify(e)}function R0(e){let t=Object.keys(e[0]);return t.length>0&&e.every(r=>Object.keys(r).length===t.length&&t.every(n=>{if(!Object.hasOwn(r,n))return!1;let o=r[n];return o===null||typeof o=="string"||typeof o=="number"||typeof o=="boolean"}))}function ba(e,t){let r=" ".repeat(t);return e.split(`
|
|
17
|
-
`).map(n=>`${r}${n}`).join(`
|
|
18
|
-
`)}function x0(e){let t=new Set,r=0;for(let n of e){let o=Object.keys(n);r+=o.length;for(let i of o)t.add(i)}return e.length*t.size<=r*2}function N0(e,t,r,n){let o=" ".repeat(r);if(!H(t)&&!Array.isArray(t))return`${o}${e}: ${tm(t)}`;if(Array.isArray(t)){if(t.length===0)return`${o}${e}: []`;let i=ba(_a({[e]:t}),r);if(n&&t.length>=2&&t.every(H)&&!R0(t)&&x0(t)){let s=Yf(t),a=ba(_a({[e]:s.rows,[`${e}_encoding`]:s.encoding}),r);if(Buffer.byteLength(a)<Buffer.byteLength(i))return a}return i}return H(t)&&Object.keys(t).length===0?`${o}${e}: {}`:`${o}${e}:
|
|
19
|
-
${rm(t,r+1)}`}function D0(e,t,r){let n=e.map(o=>Go(o,t,r||t.preserveRowFacts&&H(o))).filter(o=>o!==void 0);return n.length>0||r?n:void 0}function Go(e,t={omitDuplicateCountAliases:!0,preserveRowFacts:!0},r=!1){if(e===null)return r?null:void 0;if(Array.isArray(e))return D0(e,t,r);if(H(e)){let n=[],o=Object.entries(e).filter(([i,s])=>{let a=k0.get(i);return!t.omitDuplicateCountAliases||a===void 0||!H(e.collection_counts)||s!==e.collection_counts[a]});for(let[i,s]of o){if(i==="omitted_field_groups"&&Array.isArray(s)&&s.length===0){n.push([i,[]]);continue}let a=Go(s,t,r);a!==void 0&&n.push([i,a])}return n.length>0||r?Object.fromEntries(n):void 0}return e}function rm(e,t){let r=" ".repeat(t);if(Array.isArray(e))return e.length===0?"[]":ba(_a(e),t);if(H(e)){let n=Object.entries(e);return n.length===0?"{}":n.map(([o,i])=>N0(o,i,t,!Object.hasOwn(e,`${o}_encoding`)&&!(o==="checks"&&H(e.verdict)&&e.verdict.authority==="ok"))).join(`
|
|
20
|
-
`)}return`${r}${tm(e)}`}function P0(e){if(!H(e)||e.output_default!=="markdown"||typeof e.view!="string"||!Array.isArray(e.events)||!Array.isArray(e.days))return null;let t=[`# pm calendar (${e.view})`,""],r=H(e.summary)?e.summary:{};if(t.push(`- events: ${String(r.events??0)}`),t.push(""),e.events.length===0)return t.push("No calendar events matched the selected filters."),`${t.join(`
|
|
21
|
-
`)}
|
|
22
|
-
`;for(let n of e.events){if(!H(n))continue;let o=typeof n.kind=="string"?n.kind:"event",i=typeof n.item_title=="string"?n.item_title:"",s=typeof n.item_id=="string"?n.item_id:"",a=typeof n.reminder_text=="string"&&n.reminder_text.length>0?` ${n.reminder_text}`:"";t.push(`- [${o}] ${s} ${i}${a}`.trim())}return`${t.join(`
|
|
23
|
-
`)}
|
|
24
|
-
`}var M0=new Set(["filters","now","projection","sorting"]);function $0(e){let t=Go(e,{omitDuplicateCountAliases:!1,preserveRowFacts:!1});if(!H(t)||!Array.isArray(t.items))return t??null;let r=Object.fromEntries(Object.entries(t).filter(([n])=>!M0.has(n)));return r.has_more!==!0&&delete r.next_cursor,r}function j0(e,t){if(!H(e)||!Array.isArray(e.run_results)||!e.run_results.every(H))return e;let r=e.run_results,n=r.map(s=>s.execution_context).filter(s=>s!==void 0),o=n.length===r.length&&n.length>0&&n.every(s=>JSON.stringify(s)===JSON.stringify(n[0]))?n[0]:void 0,i=r.map(s=>{let{execution_context:a,stdout:c,stderr:d,...l}=s;return o===void 0?s:!t||s.status!=="passed"?{...l,stdout:c,stderr:d}:l});return{...e,...o===void 0?{}:{execution_context:o},run_results:i}}function L0(e){return!H(e)||e.ok!==!0||!H(e.verdict)||e.verdict.authority!=="ok"||!Array.isArray(e.checks)?e:{...e,checks:e.checks.map(F0)}}function F0(e){if(!H(e)||e.ok!==!0||!H(e.details)||Object.keys(e.details).length!==0)return e;let{details:t,...r}=e;return r}function Wo(e,t,r=!1){if(t==="json"){let o=r?$0(e):e,i=H(e)&&H(e.projection)&&e.projection.mode==="brief"&&Array.isArray(e.items);return`${JSON.stringify(o,null,i?void 0:2)}
|
|
25
|
-
`}let n=Go(L0(Jf(e)),{omitDuplicateCountAliases:!0,preserveRowFacts:!0});return n===void 0?`{}
|
|
26
|
-
`:`${rm(n,0)}
|
|
27
|
-
`}function z0(e,t,r,n){let o=t?{handled:!1,result:e,warnings:[]}:Ps("output_format",{command:r.command,args:r.commandArgs,command_options:r.commandOptions,global:{...r},pm_root:r.pmRoot,format:n,options:{...r},result:e}),i=o.warnings.find(s=>s.startsWith("extension_output_format_payload_echo_deprecated:"));return i!==void 0&&bn(`Warning: ${i}. Returning context.payload now declines safely for compatibility; migrate the override to declineServiceOverride() or { handled: false }.
|
|
28
|
-
`),o.handled&&typeof o.result=="string"?{result:o.result,rendered:o.result.endsWith(`
|
|
29
|
-
`)?o.result:`${o.result}
|
|
30
|
-
`,structuredDeliveryPreserved:!1}:{result:o.handled?o.result:e,rendered:null,structuredDeliveryPreserved:!o.handled||H(o.result)}}function U0(e,t,r,n){let o=ru(),i=r.command??o?.command,s={...o?.options,...r.commandOptions,...Object.fromEntries([["outputInclude",r.outputInclude],["outputLimit",r.outputLimit],["outputBudget",r.outputBudget],["outputFormat",r.outputFormat],["outputSession",r.outputSession],["outputCursor",r.outputCursor],["outputRowContract",r.outputRowContract]].filter(I=>I[1]!==void 0))},a=of(i??"",s)??n,c={...s,resolvedOutputFormat:a},d={...r,command:i,commandOptions:c},l=z0(e,t,d,a);if(l.rendered!==null)return wa(e),l.rendered;let u=l.result;pr(e,u);let f=i==="test"?j0(u,r.lean===!0):u,m=Bf(i,c,f);nf(m)&&(process.exitCode||=h.USAGE);let{structuredDeliveryPreserved:_}=l,y=I=>{if(a==="toon"){let X=P0(I);if(X!==null)return X}let z=t?{rendered:null}:ou(a,I);return z.rendered!==null?(_=!1,z.rendered.endsWith(`
|
|
31
|
-
`)?z.rendered:`${z.rendered}
|
|
32
|
-
`):a==="json"?Wo(I,"json",r.lean===!0):Wo(I,"toon")},w=r.tokenAccounting===!0?Kf(m,y):m,v=y(w);return S0(w,e,r.quiet!==!0&&_),v}function H0(e,t){let r=nu(e),n=Vn(r.result)?r.result:null,o=r.result,i=H(o)&&o[ya]===!0,s=n?n.result:O0(r.result);if(wo(s),n)return wa(s),"";let a=t.json===!0||t.json===void 0&&t.defaultOutputFormat==="json"?"json":"toon";return U0(s,i,t,a)}function H1(e,t){H(e)&&Number.isInteger(e.exit_code)&&E0.has(Number(e.exit_code))&&(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=Number(e.exit_code));let r=t.idOnly?sn(e,{idOnly:!0}):t.fullChangedFields?e:t.noChangedFields?sn(e,{changedFields:"compact"}):sn(e,{compactEnvelope:!0}),n=H0(r,t);t.quiet||C0(n)}function q1(e){let t=Ps("error_format",{message:e}),r=t.handled&&typeof t.result=="string"?t.result:e;bn(r.endsWith(`
|
|
33
|
-
`)?r:`${r}
|
|
34
|
-
`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="13e57322-501d-5927-8254-f6196854d434")}catch{}})();var q0=8,V0=64,B0=5,W0=4,nm=100;function Fu(e,t,r){if(e!=="get"||!va(r.item)||["fields","outputInclude","output_include","outputCursor","output_cursor"].some(c=>t[c]!==void 0)||t.full===!0||t.tree===!0||t.depth!==void 0&&t.depth!=="standard")return;let n=r.item,o=["linked","claim_state","schedule"],i=o.filter(c=>Object.hasOwn(r,c)),s=Object.fromEntries(Object.entries(r).filter(([c])=>!o.includes(c)));s.item=Object.fromEntries(Object.entries(n).filter(([c])=>c!=="body")),Object.hasOwn(n,"body")&&i.push("body");let a=[...va(r.omission_receipt)&&Array.isArray(r.omission_receipt.omitted_field_groups)?r.omission_receipt.omitted_field_groups:[],...i.map(c=>({name:c,restore_with:`--fields ${c}`}))];return s.omission_receipt={has_omissions:a.length>0,omitted_field_group_count:a.length,omitted_field_groups:a},s}function Hs(e){let t=Math.trunc(e.effective_budget_tokens),r=Math.trunc(e.measured_result_tokens);if(!Number.isSafeInteger(t)||t<=0||!Number.isSafeInteger(r)||r<=0)return{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"};let n=Math.max(t+1,r),o=Math.ceil(n*B0/W0),i=Math.ceil(o/nm)*nm;return Number.isSafeInteger(i)?{output_budget:i,recovery_budget_multiplier:i/t,rule_version:"v1"}:{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"}}function cr(e,t,r=!1){let n=Object.getOwnPropertyDescriptor(e,"row_contract");n&&(r||n.enumerable===!1)&&Object.defineProperty(t,"row_contract",{...n,enumerable:!1})}function an(e,t){let r=t===void 0?JSON.stringify(e):Wo(e,t);return Math.ceil(Buffer.byteLength(r,"utf8")/4)}function va(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ea(e,t,r=!1){return typeof e=="string"?r||e.length<=240?e:(t.compacted=!0,`${We(e,240)}\u2026`):Array.isArray(e)?e.map(n=>Ea(n,t,r)):va(e)?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,Ea(o,t,r||n==="focus_row_states")])):e}function Ye(e,t,r){let n=t.estimated_tokens;for(let o=0;o<q0;o+=1){t.estimated_tokens=n;let i=an(e,r);if(i===n)return;n=i}t.estimated_tokens=n}function G0(e,t){return rn(e).filter(r=>(Array.isArray(r.value)?r.value.length:Object.keys(r.value).length)>Math.max(1,t.get(r.path)??0)).map(r=>({collection:r,length:Array.isArray(r.value)?r.value.length:Object.keys(r.value).length})).sort((r,n)=>n.length-r.length||r.collection.path.localeCompare(n.collection.path))[0]?.collection}function K0(e,t,r,n,o,i){for(let s=0;s<V0;s+=1){if(i?.(e),Ye(e,t,o),t.estimated_tokens<=r)return;let a=G0(e,n);if(!a)return;let c=Math.max(1,n.get(a.path)??0),d=Array.isArray(a.value)?[...a.value]:Object.entries(a.value),l=_=>{if(Array.isArray(a.value)){a.value.length=_;for(let y=0;y<_;y+=1)a.value[y]=d[y]}else{for(let y of Object.keys(a.value))delete a.value[y];Object.defineProperties(a.value,Object.getOwnPropertyDescriptors(Object.fromEntries(d.slice(0,_))))}typeof e.count=="number"&&(e.count=Ao(e)),a.path==="items"&&(e.applied_limit=_),i?.(e),Ye(e,t,o)};t.rows_compacted=!0,t.compacted_row_paths=[...new Set([...t.compacted_row_paths??[],a.path])].sort((_,y)=>_.localeCompare(y)),e.has_more=!0,e.truncated=!0;let u=c,f=d.length-1,m=c;for(;u<=f;){let _=Math.floor((u+f)/2);l(_),t.estimated_tokens<=r?(m=_,u=_+1):f=_-1}l(m)}}function zu(e,t,r,n=new Map,o,i,s=!1){let a={compacted:!1},c=Object.fromEntries(Object.entries(e).map(([d,l])=>[d,Ea(l,a,s&&d==="diff")]));return cr(e,c),t.strings_compacted=a.compacted,c.read_output=t,K0(c,t,r,n,o,i),Ye(c,t,o),c}import Sa from"node:fs/promises";import Ko from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="658ab1c3-da92-5af6-a170-85ed7befaad6")}catch{}})();function et(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function om(e){let t=["--pm-path",e,"init","--defaults","--agent-guidance","skip"];return{suggested_retry:ir(t),suggested_retry_args:t}}function Yo(e){return new g(`Tracker root is not a directory at ${e}.`,h.USAGE,{code:"tracker_root_not_directory",reason:"not_a_directory",resolved_path:e,nextSteps:["Pass a tracker directory, usually <workspace>/.agents/pm, rather than a file path."]})}function ka(e){return new g(`Tracker root is not readable at ${e}.`,h.GENERIC_FAILURE,{code:"tracker_root_unreadable",reason:"unreadable",resolved_path:e,nextSteps:["Grant read and directory-search permission to the tracker root, then retry."]})}async function Y0(e){let t=Ko.resolve(e),r=Ko.parse(t).root,n=Ko.dirname(t);for(;n!==r;){let o;try{o=await Sa.stat(n)}catch(i){if(et(i,"ENOTDIR"))throw Yo(e);if(!et(i,"ENOENT"))throw i;n=Ko.dirname(n);continue}if(!o.isDirectory())throw Yo(e);return}}async function X0(e){let t;try{t=await Sa.stat(e)}catch(r){throw et(r,"ENOENT")?(await Y0(e),new g(`Tracker is not initialized at ${e}. Tracker root does not exist. Run pm init first.`,h.NOT_FOUND,{code:"tracker_root_missing",reason:"missing",resolved_path:e,nextSteps:["Confirm the tracker root path or initialize it with the emitted retry."],recovery:om(e)})):et(r,"ENOTDIR")?Yo(e):et(r,"EACCES")||et(r,"EPERM")?ka(e):r}if(!t.isDirectory())throw Yo(e);if(process.platform!=="win32"&&((t.mode&292)===0||(t.mode&73)===0))throw ka(e);try{await(await Sa.opendir(e)).close()}catch(r){throw et(r,"EACCES")||et(r,"EPERM")?ka(e):r}}async function rM(e){if(await X0(e),!await ft(Oe(e)))throw new g(`Tracker is not initialized at ${e}. Run pm init first.`,h.NOT_FOUND,{code:"tracker_not_initialized",reason:"settings_missing",resolved_path:e,nextSteps:["Initialize the selected tracker root with the emitted retry."],recovery:om(e)})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6fd537c2-9d10-5a26-81a9-ac931151017b")}catch{}})();var im=["append","cancel","claim","close","comment_add","comment_edit","comment_delete","create","delete","docs_add","docs_remove","files_add","files_remove","files_discover","history_author_acknowledge","history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","import","improvement_observe","learning_add","learning_edit","learning_delete","normalize","note_add","note_edit","note_delete","plan_create_metadata","plan_create_initial_step","plan_add_step","plan_reorder_step","plan_remove_step","plan_link_step","plan_unlink_step","plan_append_decision","plan_append_discovery","plan_append_validation","plan_resume","plan_approve","plan_materialize","plan_update_step","plan_complete_step","plan_block_step","policy_approve","policy_refused","release","reopen","restore","schema_migration","schema_migration_reference","test_run_track","tests_add","tests_remove","tests_update","update","update_audit","update_ownership_bypass","workspace_snapshot_restore","extension_migrations_apply","merge_reconcile"],sm=["history:author-acknowledge","settings:write","init:type_preset","templates:save","profile:apply-types","profile:apply-statuses","profile:apply-fields","profile:apply-config","schema:add-type","schema:remove-type","schema:add-status","schema:remove-status","schema:add-field","schema:remove-field","schema:apply-preset","schema:infer-types","schema:policy-put","schema:policy-remove","schema:policy-mode","assurance:bundle:apply","assurance:gate:verdict","telemetry:install_id","telemetry:first_run_prompt","telemetry:clear","item_format:auto_select_default"],Oa={"init:type-preset":"init:type_preset"},am=["^config:(?:set|unset):[a-z][a-z0-9_.:-]*$","^assurance:(?:measurement|invariant|gate):(?:put|remove)$","^schema_(?:rename_type|rename_status|remap_status|rename_field|remove_type|remove_status|remove_field)(?:_compensate)?$","^extension:[a-z][a-z0-9_-]*:[a-z][a-z0-9_]*$"],oM={version:1,item:im,workspace:sm,aliases:Oa,patterns:am,read_policy:"preserve_original_operation",custom_operation_grammar:"extension:<package_name>:<snake_case_operation>",legacy_custom_operation_grammar:"lowercase segments separated by underscore, hyphen, colon, or dot; optional opaque colon-suffixed retry key",excluded_surfaces:["json_patch","on_write_hook","telemetry_span"]},J0=new Set([...im,...sm]),Z0=am.map(e=>new RegExp(e,"u"));function cm(e){return Object.hasOwn(Oa,e)?Oa[e]:e}function iM(e){let t=cm(e);if(J0.has(t)||Z0.some(r=>r.test(t)))return t;throw new TypeError("Undeclared history operation; use a native contract identity or extension:<package_name>:<snake_case_operation>.")}function dm(e){let t=cm(e),r=t.indexOf(":"),n=r<0?t:t.slice(0,r),o=r<0||r<t.length-1&&!/[\s\p{C}]/u.test(t.slice(r+1));if(/^[a-z][a-z0-9]*(?:[_.-][a-z0-9]+)*$/u.test(n)&&o)return t;throw new TypeError("History operation must use lowercase alphanumeric segments with an optional non-whitespace colon-suffixed retry key.")}import{createHash as Q0}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ca5b60a5-80a7-5e7d-917f-4c7649bcbab6")}catch{}})();var cM=["sha256","sha512"],ek="sha256",lm="sha256";function Tt(e){if(e===void 0)return ek;if(e==="sha256"||e==="sha512")return e;throw new TypeError(`unsupported_history_hash_algorithm:${String(e)}`)}function tt(e,t){return Q0(Tt(t)).update(e,"utf8").digest("hex")}import fm from"node:path";import{link as tk,mkdir as rk,mkdtemp as nk,rm as ok,writeFile as ik}from"node:fs/promises";import Aa from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="71c2fed9-81e1-5723-8e34-e6327c07a130")}catch{}})();async function um(e,t){let r=Aa.dirname(e);await rk(r,{recursive:!0});let n=await nk(Aa.join(r,".pm-seed-")),o=Aa.join(n,"value");try{await ik(o,t,"utf8");try{return await tk(o,e),!0}catch(i){if(i.code==="EEXIST")return!1;throw i}}finally{await ok(n,{recursive:!0,force:!0})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2075887b-6d4b-582f-9da2-bab13198f9a5")}catch{}})();var sk=2e3,Xo=new Map;function rt(e){if(typeof e!="string")return"";let t=Xo.get(e);if(t!==void 0)return t;let r=e.trim().toLowerCase().replaceAll(/[\s-]+/g,"_");return Xo.size>=sk&&Do(Xo),Xo.set(e,r),r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6e07b1b6-1757-54dd-8833-9d3f984ccf79")}catch{}})();var ie=Object.freeze({types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"}),_m=Qc,Ta=Zc,ak=["create","update"],ck=new Set(Gn),dk=new Set(Kt),lk=new Set(Kn),uk=new Set(Yn),fk=new Set(["string","number","boolean","array","object"]),mk=16;function ym(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var pk=[e=>e.type===void 0||typeof e.type=="string"&&fk.has(e.type),e=>!Object.hasOwn(e,"const")||Zo(e.const),e=>e.enum===void 0||Array.isArray(e.enum)&&e.enum.every(t=>Zo(t)),e=>e.min_length===void 0||Number.isInteger(e.min_length)&&e.min_length>=0,e=>e.min_items===void 0||Number.isInteger(e.min_items)&&e.min_items>=0,e=>e.format===void 0||e.format==="date-time",e=>e.required===void 0||Array.isArray(e.required)&&e.required.every(t=>typeof t=="string"&&t.length>0),e=>e.additional_properties===void 0||typeof e.additional_properties=="boolean",e=>e.properties===void 0||ym(e.properties),e=>e.one_of===void 0||Array.isArray(e.one_of)&&e.one_of.length>0];function Zo(e,t=new Set){if(e===null||typeof e=="string"||typeof e=="boolean")return!0;if(typeof e=="number")return Number.isFinite(e);if(typeof e!="object"||t.has(e))return!1;t.add(e);let r=Array.isArray(e)?e.every(n=>Zo(n,t)):Object.values(e).every(n=>Zo(n,t));return t.delete(e),r}function Jo(e,t=0,r=new Set){if(!ym(e)||t>mk||r.has(e))return;r.add(e);let n=e,o=n.type,i=n.enum,s=n.one_of,a=n.properties,c=n.items,d=n.required,l=n.min_length,u=n.min_items,f=n.format,m=n.additional_properties;if(!pk.every(v=>v(n))){r.delete(e);return}let _=a===void 0?void 0:Object.fromEntries(Object.entries(a).map(([v,I])=>[v,Jo(I,t+1,r)])),y=c===void 0?void 0:Jo(c,t+1,r),w=s===void 0?void 0:s.map(v=>Jo(v,t+1,r));if([...Object.values(_??{}),...c===void 0?[]:[y],...w??[]].some(v=>v===void 0)){r.delete(e);return}return r.delete(e),Object.fromEntries(Object.entries({type:o,const:Object.hasOwn(n,"const")?n.const:void 0,enum:i,min_length:l,min_items:u,format:f,properties:_,required:d===void 0?void 0:[...new Set(d)],additional_properties:m,items:y,one_of:w}).filter(([,v])=>v!==void 0))}function vn(e){let t=Array.isArray(e)?e:[];return[...new Set(t.map(r=>typeof r=="string"?r.trim():"").filter(r=>r.length>0))].sort((r,n)=>r.localeCompare(n))}function ye(e){if(typeof e!="string"||e.length===0)return;let t=rt(e);return t.length>0?t:void 0}function _k(e){return e.startsWith("--")?e.slice(2):e}function mm(e){return typeof e=="string"?_k(e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-")):""}function hm(e){return e.replaceAll("_","-")}function yk(e){let t=e.replaceAll(/[^A-Za-z0-9]+/g," ").trim().split(/\s+/).filter(o=>o.length>0).map(o=>o.toLowerCase());if(t.length===0)return e;let[r,...n]=t;return`${r}${n.map(o=>`${o.slice(0,1).toUpperCase()}${o.slice(1)}`).join("")}`}function Ia(e,t){let r=ye(e.id);if(!r)return null;let n=[...new Set(vn(e.aliases).map(rt).filter(a=>a.length>0))].sort((a,c)=>a.localeCompare(c)),o=vn(e.roles).filter(a=>ck.has(a)),i=e.description?.trim(),s=typeof e.order=="number"&&Number.isFinite(e.order)?e.order:t;return{id:r,aliases:n,roles:o,description:i&&i.length>0?i:void 0,order:s}}function hk(e){return{draft_status:ye(e?.draft_status),open_status:ye(e?.open_status),in_progress_status:ye(e?.in_progress_status),blocked_status:ye(e?.blocked_status),close_status:ye(e?.close_status),canceled_status:ye(e?.canceled_status)}}function gm(e,t){if(!Array.isArray(t)||t.length!==2)return;let r=rt(t[0]),n=rt(t[1]);r.length===0||n.length===0||e.pairs.some(o=>o[0]===r&&o[1]===n)||e.pairs.push([r,n])}function gk(e){let t=typeof e?.type=="string"?e.type.trim():"";if(t.length===0||!Array.isArray(e?.allowed_transitions))return null;let r={type:t,pairs:[],denyAll:e.allowed_transitions.length===0};for(let n of e.allowed_transitions)gm(r,n);return{typeKey:t.toLowerCase(),record:r}}function bk(e){if(!Array.isArray(e)||e.length===0)return;let t=new Map;for(let n of e){let o=gk(n);if(o===null)continue;let i=t.get(o.typeKey)??o.record;i.denyAll||=o.record.denyAll;for(let s of o.record.pairs)gm(i,s);t.set(o.typeKey,i)}let r=[];for(let n of t.values())(n.pairs.length>0||n.denyAll)&&r.push({type:n.type,allowed_transitions:n.pairs});return r.sort((n,o)=>n.type.localeCompare(o.type)),r.length>0?r:void 0}function bm(e){let t=rt(e.key??"");if(!t)return null;let r=rt(e.metadata_key??e.front_matter_key??t),n=mm(e.cli_flag??hm(t));if(!n)return null;let o=vn(e.cli_aliases).map(u=>mm(u)).filter(u=>u.length>0&&u!==n),i=typeof e.type=="string"?e.type.trim().toLowerCase():"string",s=dk.has(i)?i:"string",a=(()=>{let u=vn(e.commands).filter(f=>lk.has(f));return u.length>0?u:[...ak]})(),c=e.description?.trim(),d=vn(e.required_types),l=e.value_schema===void 0?void 0:Jo(e.value_schema);return e.value_schema!==void 0&&l===void 0?null:{key:t,metadata_key:r,cli_flag:n,cli_aliases:o,description:c&&c.length>0?c:void 0,type:s,commands:a,repeatable:[e.repeatable===!0,s==="string_array"].includes(!0),required:e.required===!0,required_on_create:e.required_on_create===!0,required_types:d,allow_unset:e.allow_unset!==!1,value_schema:l}}function wk(e){let t=new Map;for(let[n,o]of e.entries()){let i=Ia(o,n);i&&t.set(i.id,i)}let r=pm([...t.values()]);return r.length>0?r:pm(Ta.map((n,o)=>Ia(n,o)).filter(n=>n!==null))}function pm(e){return e.sort((t,r)=>t.order===r.order?t.id.localeCompare(r.id):t.order-r.order)}function vk(e){let t=new Map;for(let r of e??[]){let n=bm(r);n&&t.set(n.key,n)}return[...t.values()].sort((r,n)=>r.key.localeCompare(n.key))}function Ek(e){return{id:e.id,aliases:e.aliases.length>0?[...e.aliases]:void 0,roles:e.roles.length>0?[...e.roles]:void 0,description:e.description,order:e.order}}function kk(e){return{key:e.key,metadata_key:e.metadata_key!==e.key?e.metadata_key:void 0,cli_flag:e.cli_flag!==hm(e.key)?e.cli_flag:void 0,cli_aliases:e.cli_aliases.length>0?[...e.cli_aliases]:void 0,description:e.description,type:e.type,commands:[...e.commands],repeatable:e.repeatable===!0?!0:void 0,required:e.required===!0?!0:void 0,required_on_create:e.required_on_create===!0?!0:void 0,required_types:e.required_types.length>0?[...e.required_types]:void 0,allow_unset:e.allow_unset===!1?!1:void 0,value_schema:e.value_schema}}function Sk(e){let t=typeof e=="string"?e.trim().toLowerCase():"allow";return uk.has(t)?t:"allow"}function Te(e){let t={...ie,...e?.files},r=e?.statuses&&e.statuses.length>0?e.statuses:Ta,n=wk(r),o=vk(e?.fields);return{version:typeof e?.version=="number"&&Number.isFinite(e.version)?Math.floor(e.version):1,files:t,statuses:n.map(Ek),fields:o.map(kk),workflow:{..._m,...hk(e?.workflow)},type_workflows:bk(e?.type_workflows),unknown_field_policy:Sk(e?.unknown_field_policy)}}function Ok(e,t,r){try{return JSON.parse(e)}catch{r.push(t);return}}function Ak(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.definitions))return t.definitions;if(typeof t.item_types=="object"&&t.item_types!==null){let r=t.item_types;if(Array.isArray(r.definitions))return r.definitions}}function Ik(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.statuses))return t.statuses;if(Array.isArray(t.definitions))return t.definitions}function Tk(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.fields))return t.fields;if(Array.isArray(t.definitions))return t.definitions}function Ck(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;return typeof t.workflow=="object"&&t.workflow!==null&&!Array.isArray(t.workflow)?t.workflow:typeof t.workflows=="object"&&t.workflows!==null&&!Array.isArray(t.workflows)?t.workflows:t}function Rk(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;if(Array.isArray(t.type_workflows))return t.type_workflows}function ue(e,t,r){let n=t?.trim()||r;return fm.isAbsolute(n)?n:fm.join(e,n)}function vM(e,t){return ue(e,t.files.types,ie.types)}async function EM(e,t){let r=Te(t),n=[{path:ue(e,r.files.types,ie.types),seed:{definitions:[]}},{path:ue(e,r.files.statuses,ie.statuses),seed:{statuses:Ta}},{path:ue(e,r.files.fields,ie.fields),seed:{fields:[]}},{path:ue(e,r.files.workflows,ie.workflows),seed:{workflow:_m}}],o=[];for(let i of n)await ft(i.path)||await um(i.path,`${JSON.stringify(i.seed,null,2)}
|
|
35
|
-
`)&&o.push(i.path);return{created_paths:o}}async function wm(e,t){let r=Te(t),n=[],o=ue(e,r.files.types,ie.types),i=ue(e,r.files.statuses,ie.statuses),s=ue(e,r.files.fields,ie.fields),a=ue(e,r.files.workflows,ie.workflows),c,d,l,u,f,m=async(I,z)=>{let X=await we(I);if(X!==null)return Ok(X,z,n)},_=await m(o,"runtime_schema_types_invalid_json");_!==void 0&&(c=Ak(_),c===void 0&&n.push("runtime_schema_types_invalid_shape"));let y=await m(i,"runtime_schema_statuses_invalid_json");y!==void 0&&(d=Ik(y),d===void 0&&n.push("runtime_schema_statuses_invalid_shape"));let w=await m(s,"runtime_schema_fields_invalid_json");w!==void 0&&(l=Tk(w),l===void 0&&n.push("runtime_schema_fields_invalid_shape"));let v=await m(a,"runtime_schema_workflows_invalid_json");return v!==void 0&&(u=Ck(v),u===void 0&&n.push("runtime_schema_workflows_invalid_shape"),f=Rk(v)),{schema:Te({...r,statuses:[...r.statuses,...d??[]],fields:[...r.fields,...l??[]],workflow:{...r.workflow,...u},type_workflows:[...r.type_workflows??[],...f??[]]}),type_definitions_from_file:c,warnings:n,created_paths:[]}}function wn(e,t,r,n=!1){let o=r.map(s=>ye(s)).filter(s=>typeof s=="string").find(s=>e.some(a=>a.id===s));if(n&&o!==void 0)return o;let i=e.find(s=>s.roles.includes(t));return i!==void 0?i.id:o??e[0]?.id}function xk(e){let t=new Map,r=new Map;for(let n of e){r.set(n.id,n),t.set(n.id,n.id),t.set(n.id.replaceAll("_","-"),n.id),t.set(n.id.replaceAll("_"," "),n.id);for(let o of n.aliases)t.set(o,n.id),t.set(o.replaceAll("_","-"),n.id),t.set(o.replaceAll("_"," "),n.id)}return{aliasToId:t,byId:r}}function Nk(e){let t={activeStatuses:new Set,blockedStatuses:new Set,draftStatuses:new Set,terminalCanceledStatuses:new Set,terminalDoneStatuses:new Set,terminalStatuses:new Set};for(let r of e){let n=new Set(r.roles);(n.has("terminal")||n.has("terminal_done")||n.has("terminal_canceled"))&&t.terminalStatuses.add(r.id),n.has("terminal_done")&&t.terminalDoneStatuses.add(r.id),n.has("terminal_canceled")&&t.terminalCanceledStatuses.add(r.id),n.has("active")&&t.activeStatuses.add(r.id),n.has("blocked")&&t.blockedStatuses.add(r.id),n.has("draft")&&t.draftStatuses.add(r.id)}return t}function vm(e){let t=Te(e),r=t.statuses.map((v,I)=>Ia(v,I)).filter(v=>v!==null),{aliasToId:n,byId:o}=xk(r),{activeStatuses:i,blockedStatuses:s,draftStatuses:a,terminalCanceledStatuses:c,terminalDoneStatuses:d,terminalStatuses:l}=Nk(r),u=t.workflow,f=ye(u.open_status)??wn(r,"default_open",["open","in_progress",Gt[0]]),m=ye(u.in_progress_status)??wn(r,"active",["in_progress","in-progress",f],!0),_=ye(u.blocked_status)??wn(r,"blocked",["blocked"]),y=ye(u.close_status)??wn(r,"default_close",["closed","done","complete"]),w=ye(u.canceled_status)??wn(r,"default_cancel",["canceled","cancelled"]);return{definitions:r,by_id:o,alias_to_id:n,terminal_statuses:l,terminal_done_statuses:d,terminal_canceled_statuses:c,active_statuses:i,blocked_statuses:s,draft_statuses:a,open_status:f,in_progress_status:m,blocked_status:_,close_status:y,canceled_status:w}}function Ca(e,t){let r=rt(e);if(r)return t.alias_to_id.get(r)}function Em(e){let t=Te(e),r=new Map,n=t.fields.map(c=>bm(c)).filter(c=>c!==null);for(let c of n)r.set(c.key,c);let o=[...r.values()].sort((c,d)=>c.key.localeCompare(d.key)),i=new Map,s=new Map,a=new Map;for(let c of o){i.set(c.key,c),s.set(c.cli_flag,c);for(let d of c.cli_aliases)s.set(d,c);for(let d of c.commands){let l=a.get(d)??[];l.push(c),a.set(d,l)}}for(let[c,d]of a.entries())d.sort((l,u)=>l.key.localeCompare(u.key)),a.set(c,d);return{definitions:o,by_key:i,by_cli_token:s,command_to_fields:a}}function km(e){return yk(e.key)}function kM(e,t){let r=Ca(e,t);return r?t.terminal_statuses.has(r):!1}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d5692ce-ec33-5eb4-bd9b-7497ffe25b0e")}catch{}})();var Dk=16;function Ra(e){let t=e.trim().replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(o=>o.length>0).map(o=>o.toLowerCase());if(t.length===0)return e;let[r,...n]=t;return`${r}${n.map(o=>`${o.slice(0,1).toUpperCase()}${o.slice(1)}`).join("")}`}function Pk(e){return[...new Set([km(e),Ra(e.key),Ra(e.cli_flag),...e.cli_aliases.map(t=>Ra(t))])]}function Am(e,t){for(let r of Pk(t)){if(!Object.hasOwn(e,r))continue;let n=e[r];if(n!==void 0)return n}}function Im(e){return Array.isArray(e)?e.flatMap(t=>Im(t)).map(t=>t.trim()).filter(t=>t.length>0):typeof e=="string"?e.split(/[,\n|]/).map(t=>t.trim()).filter(t=>t.length>0):e==null?[]:[String(e).trim()].filter(t=>t.length>0)}function Sm(e,t){if(typeof e=="boolean")return e;if(typeof e=="number"){if(e===1)return!0;if(e===0)return!1}if(typeof e=="string"){let r=e.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1}throw new g(`${t} must be one of true|false|1|0|yes|no`,h.USAGE)}function Om(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;let r=typeof e=="string"?e.trim():String(e),n=Number(r);if(!Number.isFinite(n))throw new g(`${t} must be a number`,h.USAGE);return n}function Mk(e,t,r){let n=typeof e=="string"?(()=>{try{return JSON.parse(e)}catch{return}})():e;if(r==="array"&&Array.isArray(n)||r==="object"&&typeof n=="object"&&n!==null&&!Array.isArray(n))return n;throw new g(`${t} must be valid JSON ${r}`,h.USAGE)}function $k(e,t){return t===void 0?!0:t==="array"?Array.isArray(e):t==="object"?typeof e=="object"&&e!==null&&!Array.isArray(e):typeof e===t}function jk(e,t,r){if(t.const!==void 0&&R(e)!==R(t.const))return`${r} must equal ${R(t.const)}`;if(t.enum!==void 0&&!t.enum.some(n=>R(n)===R(e)))return`${r} must be one of ${t.enum.map(n=>R(n)).join("|")}`;if(!$k(e,t.type))return`${r} must match configured type ${String(t.type)}`;if(typeof e=="string"){if(t.min_length!==void 0&&e.length<t.min_length)return`${r} must contain at least ${t.min_length} characters`;if(t.format==="date-time"&&!_n(e))return`${r} must be an RFC 3339 date-time`}}function Lk(e,t,r,n){if(Array.isArray(e)){if(t.min_items!==void 0&&e.length<t.min_items)return`${r} must contain at least ${t.min_items} items`;if(t.items)for(let[o,i]of e.entries()){let s=Qo(i,t.items,`${r}[${o}]`,n+1);if(s)return s}}}function Fk(e,t,r,n){if(typeof e!="object"||e===null||Array.isArray(e))return;let o=e;for(let i of t.required??[])if(!Object.hasOwn(o,i))return`${r}.${i} is required`;for(let[i,s]of Object.entries(o)){let a=t.properties?.[i];if(!a){if(t.additional_properties===!1)return`${r}.${i} is not allowed`;continue}let c=Qo(s,a,`${r}.${i}`,n+1);if(c)return c}}function Qo(e,t,r,n=0){if(n>Dk)return`${r} value schema exceeds maximum depth`;let o=jk(e,t,r);if(o)return o;let i=Lk(e,t,r,n);if(i)return i;let s=Fk(e,t,r,n);if(s)return s;if(!t.one_of)return;let a=0;for(let c of t.one_of)if(Qo(e,c,r,n+1)===void 0&&(a+=1,a>1))break;return a===1?void 0:`${r} must match exactly one configured schema variant`}function Ct(e,t,r){if(!e.value_schema||t===void 0)return t;let n=Qo(t,e.value_schema,r);if(n)throw new g(n,h.USAGE);return t}function zk(e,t,r,n){let o=n==="option"&&Array.isArray(t)?t[t.length-1]:t;if(o!==void 0)return Ct(e,Mk(o,r,e.type),r)}function En(e,t,r,n="option"){let o=r??`--${e.cli_flag}`;if(e.type==="array"||e.type==="object")return zk(e,t,o,n);if(e.repeatable||e.type==="string_array"){let s=Im(t);return e.type==="number"?Ct(e,s.map(a=>Om(a,o)),o):e.type==="boolean"?Ct(e,s.map(a=>Sm(a,o)),o):Ct(e,s,o)}let i=Array.isArray(t)?t[t.length-1]:t;if(i!==void 0)return e.type==="number"?Ct(e,Om(i,o),o):e.type==="boolean"?Ct(e,Sm(i,o),o):Ct(e,typeof i=="string"?i:String(i),o)}function Uk(e,t){return!e.required&&!e.required_on_create?!1:e.required_types.length===0?!0:t?e.required_types.map(r=>r.toLowerCase()).includes(t.trim().toLowerCase()):!1}function RM(e,t,r){let n={},o=[];for(let i of t.command_to_fields.get("create")??[]){let s=Am(e,i);if(s===void 0){Uk(i,r)&&o.push(`--${i.cli_flag}`);continue}n[i.metadata_key]=En(i,s)}return{values:n,missing_required_flags:[...new Set(o)].sort((i,s)=>i.localeCompare(s))}}function xM(e,t,r=["update"]){let n={},o=(r??["update"]).flatMap(s=>t.command_to_fields.get(s)??[]),i=new Set;for(let s of o){let a=Am(e,s);a!==void 0&&(i.has(s.metadata_key)||(i.add(s.metadata_key),n[s.metadata_key]=En(s,a)))}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c35d4830-d7d1-5ee4-99bc-ab52cc3e4e09")}catch{}})();var xa=1,Na=2;function DM(e){return Math.max(Da(e),e.tests?.some(t=>t.updated_by!==void 0||t.updated_at!==void 0)?2:1)}function Da(e){let t=e.pm_format_version;return typeof t=="number"&&Number.isInteger(t)&&t>=1?t:1}function Tm(e){if(!(typeof e!="number"||!Number.isInteger(e)||e<=1))return e}function Hk(e,t=2,r=t){return e<r?"outdated":e>t?"ahead":"current"}function PM(e,t=2,r=t){let n=[],o=[];for(let i of e){let s=Hk(i.version,t,r);s==="outdated"?n.push(i.ref):s==="ahead"&&o.push(i.ref)}return{outdated:n.sort((i,s)=>i.localeCompare(s)),ahead:o.sort((i,s)=>i.localeCompare(s))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="515840b7-cf86-5d71-8ac1-beac7fd7c8a8")}catch{}})();var qk={"in-progress":"in_progress",cancelled:"canceled"};function ei(e,t){if(t){let o=Ca(e,t);if(o)return o}if(typeof e!="string")return;let r=e.trim().toLowerCase();if(!r)return;let n=qk[r]??r;if(Gt.includes(n))return n}function Vk(e,t){return ei(e,t)??e}function LM(e,t){return t.terminal_statuses.has(Vk(e,t))}import{encode as Kk}from"@toon-format/toon";import{isDeepStrictEqual as Cm}from"node:util";import{decode as Bk}from"@toon-format/toon";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aaa2be03-9478-5fbe-82e6-e4fc86e3735b")}catch{}})();function Pa(e){return{value:Bk(e),usedScalarBracketEscape:!1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="79626299-17a8-573a-9b66-ce37c65e2f5d")}catch{}})();var Wk=/^\s*(<<<<<<<|=======|>>>>>>>)(?:\s.*)?$/;function Gk(e){if(e.length===0)return[];let t=e.split(/\r?\n/),r=[];for(let n=0;n<t.length;n+=1){let o=t[n]??"",i=o.match(Wk);if(!i)continue;let s=i[1];r.push({line:n+1,marker:s,text:o})}return r}function ti(e){return Gk(e)[0]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2789e87f-0706-52e8-8f4c-3855c65c618c")}catch{}})();var La=new Set(["schema","tracker","auto","none"]),Pm=new Set(["source","isolated","snapshot"]),Yk=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]),Xk=new Set(["passed","failed","stopped","canceled"]),Jk=new Set(ld);function wr(e){return e.replaceAll("\\","/")}function Mm(e){for(let t of e)if(t!==0)return t;return 0}function ni(e){for(let[t,r]of Object.entries(e))r===void 0&&delete e[t]}var $m=["id","title","description","created_at","updated_at"],Zk=new Set(Ee);function jm(e){if(e?.schema)return{statusRegistry:vm(e.schema),fieldRegistry:Em(e.schema),unknownFieldPolicy:e.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(e.extensionFieldNames??[]),onWarning:e.onWarning}}function Qk(e,t){return e.required?e.required_types.length===0?!0:e.required_types.map(r=>r.toLowerCase()).includes(t.trim().toLowerCase()):!1}function nt(e){let t=e.match(/^([a-z_][\w.]*)\s/u)?.[1];throw new g(`Invalid item metadata: ${e}`,h.GENERIC_FAILURE,{code:"item_document_invalid",reason:e.includes("required")?"missing_required_field":"schema_validation_error",...t?{field:t}:{},required:"Provide an item document whose metadata satisfies the active runtime schema.",why:e})}function On(e,t){throw new g(t,h.GENERIC_FAILURE,{code:"item_document_invalid",reason:"syntax_error",format:e,required:`Provide a syntactically valid ${e==="toon"?"TOON":"JSON Markdown"} item document.`,why:"The document could not be decoded far enough to validate item metadata."})}function Lm(e,t){if(!t||typeof e!="object"||e===null)return;let r=Da(e);if(!(r<=Na))throw new g(`Stored item uses format version ${r}; this runtime supports up to ${Na}. Upgrade pm before reading or changing this item.`,h.CONFLICT,{code:"item_format_version_unsupported",format_version:r,required:"Upgrade to a pm runtime supporting the stored item format.",nextSteps:["Preserve the original item and history; do not lower pm_format_version to bypass compatibility checks."]})}function Fm(e){let t=new Set(Zk);for(let r of e.fieldRegistry?.definitions??[])t.add(r.metadata_key);for(let r of e.extensionFieldNames)t.add(r);return t}function O(e,t){e||nt(t)}function An(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&nt(t),e}function Ma(e,t){let r=e[t];O(typeof r=="string",`${t} must be a string`),O(je(r),`${t} must be a valid ISO timestamp`)}function Rm(e,t,r){let n=e[t];n!==void 0&&O(typeof n=="number"&&Number.isInteger(n)&&n>=1,`${r} must be an integer >= 1`)}function Fa(e,t,r){let n=e[t];n!==void 0&&(O(typeof n=="string",`${r} must be a string`),O(je(n),`${r} must be a valid ISO timestamp`))}function eS(e){if(e!==void 0){O(Array.isArray(e),"event.recurrence.by_weekday must be an array");for(let t of e){O(typeof t=="string","event.recurrence.by_weekday entries must be strings");let r=t.trim().toLowerCase();O(Mr.includes(r),`event.recurrence.by_weekday entries must be one of: ${Mr.join(", ")}`)}}}function tS(e){if(e!==void 0){O(Array.isArray(e),"event.recurrence.by_month_day must be an array");for(let t of e)O(typeof t=="number"&&Number.isInteger(t)&&t>=1&&t<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function rS(e){if(e!==void 0){O(Array.isArray(e),"event.recurrence.exdates must be an array");for(let t of e)O(typeof t=="string","event.recurrence.exdates entries must be strings"),O(je(t),"event.recurrence.exdates entries must be valid ISO timestamps")}}function nS(e){let t=An(e,"event.recurrence must be an object");O(typeof t.freq=="string","event.recurrence.freq must be a string");let r=t.freq.trim().toLowerCase();O(Zn.includes(r),`event.recurrence.freq must be one of: ${Zn.join(", ")}`),Rm(t,"interval","event.recurrence.interval"),Rm(t,"count","event.recurrence.count"),Fa(t,"until","event.recurrence.until"),eS(t.by_weekday),tS(t.by_month_day),rS(t.exdates)}function oS(e){for(let n of $m)O(typeof e[n]=="string",`${n} is required and must be a string`);let t=e.type;O(typeof t=="string"&&t.trim().length>0,"type must be a non-empty string");let r=e.pm_format_version;return r!==void 0&&O(typeof r=="number"&&Number.isInteger(r)&&r>=xa,`pm_format_version must be an integer >= ${xa}`),t}function iS(e,t){let r=e.status;O(typeof r=="string"&&r.trim().length>0,"status must be a non-empty string");let n=t?.statusRegistry,o=ei(r,n),i=n?n.definitions.map(s=>s.id):[...Gt];O(o!==void 0,`status must be one of: ${i.join(", ")}`)}function sS(e){let t=e.priority;O(typeof t=="number"&&Number.isInteger(t)&&[0,1,2,3,4].includes(t),"priority must be an integer 0..4");let r=e.tags;O(Array.isArray(r),"tags must be an array");for(let n of r)O(typeof n=="string","tags entries must be strings")}function aS(e){let t=e.confidence;if(t!==void 0){if(typeof t=="number"){O(Number.isInteger(t)&&t>=0&&t<=100,"confidence number value must be an integer 0..100");return}if(typeof t=="string"){let r=t.trim().toLowerCase(),n=r==="med"||Jn.includes(r);O(n,`confidence string value must be one of: ${[...Jn,"med"].join(", ")}`);return}O(!1,"confidence must be a number or string")}}function cS(e){let t=e.severity;if(t===void 0)return;typeof t!="string"&&nt("severity must be a string");let r=t.trim().toLowerCase(),n=r==="med"||Xn.includes(r);O(n,`severity value must be one of: ${[...Xn,"med"].join(", ")}`)}function dS(e){e.regression!==void 0&&typeof e.regression!="boolean"&&nt("regression must be a boolean")}function lS(e){let t=e.reminders;if(t!==void 0){O(Array.isArray(t),"reminders must be an array");for(let r of t){let n=An(r,"reminders entries must be objects");O(typeof n.at=="string","reminder.at must be a string"),O(je(n.at),"reminder.at must be a valid ISO timestamp"),O(typeof n.text=="string","reminder.text must be a string"),O(n.text.trim().length>0,"reminder.text must not be empty")}}}function uS(e){for(let t of["title","description","location","timezone"])e[t]!==void 0&&(O(typeof e[t]=="string",`event.${t} must be a string`),O(e[t].trim().length>0,`event.${t} must not be empty`))}function fS(e){e.recurrence!==void 0&&(nS(e.recurrence),e.recurrence.until!==void 0&&O(oe(e.recurrence.until,e.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function mS(e){let t=An(e,"events entries must be objects");O(typeof t.start_at=="string","event.start_at must be a string"),O(je(t.start_at),"event.start_at must be a valid ISO timestamp"),t.end_at!==void 0&&(O(typeof t.end_at=="string","event.end_at must be a string"),O(je(t.end_at),"event.end_at must be a valid ISO timestamp"),O(oe(t.end_at,t.start_at)>0,"event.end_at must be after event.start_at")),uS(t),t.all_day!==void 0&&O(typeof t.all_day=="boolean","event.all_day must be a boolean"),fS(t)}function pS(e){let t=e.events;if(t!==void 0){O(Array.isArray(t),"events must be an array");for(let r of t)mS(r)}}function _S(e){for(let t of["source_type","source_owner","design","external_ref"]){let r=e[t];r!==void 0&&O(typeof r=="string",`${t} must be a string`)}}function yS(e){let t=e.type_options;if(t===void 0)return;let r=An(t,"type_options must be an object");for(let[n,o]of Object.entries(r))O(n.trim().length>0,"type_options keys must be non-empty"),O(typeof o=="string","type_options values must be strings"),O(o.trim().length>0,"type_options values must be non-empty strings")}function hS(e,t,r){if(r?.fieldRegistry)for(let n of r.fieldRegistry.definitions){let o=e[n.metadata_key];if(o===void 0){Qk(n,t)&&nt(`missing required schema field: ${n.metadata_key}`);continue}try{e[n.metadata_key]=En(n,o,`metadata field "${n.metadata_key}"`,"metadata")}catch(i){nt(String(i?.message).replace(/^Invalid\s+/u,""))}}}function gS(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let r=Fm(t),n=Object.keys(e).filter(o=>!r.has(o)).sort((o,i)=>o.localeCompare(i));n.length!==0&&(t.unknownFieldPolicy==="reject"?nt(`unknown schema fields are not allowed: ${n.join(", ")}`):t.onWarning?.(`item_unknown_schema_fields:${n.join(",")}`))}function za(e,t){let r=An(e,"item metadata must be an object"),n=oS(r);iS(r,t),sS(r),aS(r),cS(r),dS(r),Ma(r,"created_at"),Ma(r,"updated_at"),r.deadline!==void 0&&Ma(r,"deadline"),lS(r),pS(r),Fa(r,"closed_at","closed_at"),Fa(r,"completed_at","completed_at"),_S(r),yS(r),hS(r,n,t),gS(r,t)}function bS(e){if(!(!e||e.length===0))return[...e].map((t,r)=>(O(t.created_at===void 0||typeof t.created_at=="string"&&_n(t.created_at),`dependencies.${r}.created_at requires a valid timestamp; restore the dependency timestamp from its source record`),{id:t.id.trim(),kind:t.kind,created_at:t.created_at,author:t.author?.trim()||void 0,source_kind:t.source_kind?.trim()||void 0,author_source:t.author_source})).sort((t,r)=>{let n=oe(t.created_at??"",r.created_at??"");if(n!==0)return n;let o=t.id.localeCompare(r.id);if(o!==0)return o;let i=t.kind.localeCompare(r.kind);return i!==0?i:(t.source_kind??"").localeCompare(r.source_kind??"")})}function $a(e){if(!(!e||e.length===0))return[...e].sort((t,r)=>{let n=oe(t.created_at,r.created_at);if(n!==0)return n;let o=t.text.localeCompare(r.text);return o!==0?o:t.author.localeCompare(r.author)})}function wS(e){if(!e||e.length===0)return;let t=[...e].map(r=>({at:r.at,text:r.text.trim()})).filter(r=>r.text.length>0).sort((r,n)=>{let o=oe(r.at,n.at);return o!==0?o:r.text.localeCompare(n.text)});return t.length===0?void 0:t}function vS(e){if(!e)return;let t=e.freq.trim().toLowerCase();if(!Zn.includes(t))return;let r=Array.from(new Set((e.by_weekday??[]).map(s=>s.trim().toLowerCase()).filter(s=>Mr.includes(s)))).sort((s,a)=>Wi(s)-Wi(a)),n=Array.from(new Set((e.by_month_day??[]).filter(s=>Number.isInteger(s)&&s>=1&&s<=31).map(s=>s))).sort((s,a)=>s-a),o=Array.from(new Set((e.exdates??[]).map(s=>s.trim()).filter(s=>je(s)))).sort((s,a)=>oe(s,a)),i={freq:t,interval:e.interval!==void 0&&e.interval>1?e.interval:void 0,count:e.count,until:e.until?.trim()||void 0,by_weekday:r.length>0?r:void 0,by_month_day:n.length>0?n:void 0,exdates:o.length>0?o:void 0};for(let[s,a]of Object.entries(i))a===void 0&&delete i[s];return i}function ES(e){return!Array.isArray(e)||e.length===0?void 0:[...e].map(kS).sort(SS)}function kS(e){let t={start_at:e.start_at,end_at:e.end_at||void 0,title:e.title?.trim()||void 0,description:e.description?.trim()||void 0,location:e.location?.trim()||void 0,all_day:e.all_day,timezone:e.timezone?.trim()||void 0,recurrence:vS(e.recurrence)};return ni(t),t}function SS(e,t){return Mm([oe(e.start_at,t.start_at),(e.end_at??"").localeCompare(t.end_at??""),(e.title??"").localeCompare(t.title??""),+!!e.all_day-+!!t.all_day,(e.timezone??"").localeCompare(t.timezone??""),(e.location??"").localeCompare(t.location??""),(e.description??"").localeCompare(t.description??""),JSON.stringify(e.recurrence??{}).localeCompare(JSON.stringify(t.recurrence??{}))])}function OS(e){if(!(!e||e.length===0))return e.map(t=>({path:wr(t.path),scope:t.scope,note:t.note?.trim()||void 0}))}function AS(e){if(!e||e.length===0)return;let t=e.map(RS).filter(r=>r.run_id.length>0&&r.started_at.length>0&&r.finished_at.length>0&&r.recorded_at.length>0).sort((r,n)=>Mm([oe(r.recorded_at,n.recorded_at),r.run_id.localeCompare(n.run_id),r.kind.localeCompare(n.kind)]));return t.length>0?t:void 0}function gr(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0}function IS(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function ja(e){return typeof e=="string"?e:""}function TS(e){if(!Array.isArray(e))return;let t=e.filter(n=>n!==null&&typeof n=="object"&&typeof n.name=="string"&&n.name.trim().length>0&&typeof n.value=="number"&&Number.isFinite(n.value)&&typeof n.recorded_at=="string"&&n.recorded_at.trim().length>0).map(n=>({name:n.name.trim(),value:n.value,unit:typeof n.unit=="string"&&n.unit.trim()||void 0,threshold:typeof n.threshold=="number"&&Number.isFinite(n.threshold)?n.threshold:void 0,recorded_at:n.recorded_at.trim()})),r=[...new Map(t.map(n=>[n.name,n])).values()].sort((n,o)=>n.name.localeCompare(o.name)).slice(0,32);return r.length>0?r:void 0}function ri(e,t){return typeof e=="string"&&t.has(e)?e:void 0}function CS(e){if(!Array.isArray(e))return;let t=e.filter(r=>r&&typeof r.command=="string"&&r.command.trim().length>0).slice(0,32).map(r=>({command:r.command.trim(),requested_pm_context_mode:ri(r.requested_pm_context_mode,La),pm_context_mode:ri(r.pm_context_mode,La),workspace_context_mode:ri(r.workspace_context_mode,Pm),trust_reason:ri(r.trust_reason,Yk)}));return t.length>0?t:void 0}function RS(e){let t=typeof e.run_id=="string"?e.run_id.trim():"",r=e.kind==="test"||e.kind==="test-all"?e.kind:"test",n=Xk.has(e.status)?e.status:"failed",o={run_id:t,kind:r,status:n,started_at:ja(e.started_at),finished_at:ja(e.finished_at),recorded_at:ja(e.recorded_at),attempt:IS(e.attempt),resumed_from:e.resumed_from?.trim()||void 0,passed:gr(e.passed)??0,failed:gr(e.failed)??0,skipped:gr(e.skipped)??0,items:gr(e.items),linked_tests:gr(e.linked_tests),fail_on_skipped_triggered:e.fail_on_skipped_triggered===!0?!0:void 0,measurements:TS(e.measurements),executions:CS(e.executions)};return ni(o),o}function xS(e){if(!(!Array.isArray(e)||e.length===0))return e.map($S)}function kn(e){if(!Array.isArray(e))return;let t=[...new Set(e.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0))].sort((r,n)=>r.localeCompare(n));return t.length>0?t:void 0}function Va(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ba(e){return e==="__proto__"||e==="constructor"||e==="prototype"}function xm(e){if(!Va(e))return;let t=Object.entries(e).map(([r,n])=>[r.trim(),String(n).trim()]).filter(([r,n])=>r.length>0&&!Ba(r)&&n.length>0).sort(([r],[n])=>r.localeCompare(n));return t.length>0?Object.fromEntries(t):void 0}function NS(e){if(!Va(e))return;let t=Object.entries(e).map(([r,n])=>[r.trim(),Number(n)]).filter(([r,n])=>r.length>0&&!Ba(r)&&Number.isFinite(n)).sort(([r],[n])=>r.localeCompare(n));return t.length>0?Object.fromEntries(t):void 0}function DS(e){let t=e?.trim().toLowerCase();if(!(!t||!La.has(t)))return t}function PS(e){let t=e?.trim().toLowerCase();if(!(!t||!Pm.has(t)))return t}function MS(e,t){if(t===!0)return{provenance_invalid:!0};if(e===void 0)return{};if(!Va(e))return{provenance_invalid:!0};let r=E(e.author),n=E(e.created_at),o=e.source_kind;return!r||!n||!je(n)||o!=="local_mutation"&&o!=="merge_union"?{provenance_invalid:!0}:{provenance:{author:r,created_at:n,source_kind:o,source_ref:E(e.source_ref)}}}function $S(e){let t={command:e.command?.trim()||void 0,path:e.path?wr(e.path):void 0,scope:e.scope,timeout_seconds:typeof e.timeout_seconds=="number"&&Number.isFinite(e.timeout_seconds)&&e.timeout_seconds>0?e.timeout_seconds:void 0,pm_context_mode:DS(e.pm_context_mode),workspace_context_mode:PS(e.workspace_context_mode),...MS(e.provenance,e.provenance_invalid),updated_by:E(e.updated_by),updated_at:E(e.updated_at),env_set:xm(e.env_set),env_clear:kn(e.env_clear),shared_host_safe:e.shared_host_safe===!0?!0:void 0,assert_stdout_contains:kn(e.assert_stdout_contains),assert_stdout_regex:kn(e.assert_stdout_regex),assert_stderr_contains:kn(e.assert_stderr_contains),assert_stderr_regex:kn(e.assert_stderr_regex),assert_stdout_min_lines:gr(e.assert_stdout_min_lines),assert_json_field_equals:xm(e.assert_json_field_equals),assert_json_field_gte:NS(e.assert_json_field_gte),note:e.note?.trim()||void 0};return ni(t),t}function jS(e){if(!(!e||e.length===0))return[...e].map(t=>({path:wr(t.path),scope:t.scope,note:t.note?.trim()||void 0})).sort((t,r)=>{let n=t.scope.localeCompare(r.scope);if(n!==0)return n;let o=t.path.localeCompare(r.path);return o!==0?o:(t.note??"").localeCompare(r.note??"")})}function E(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function LS(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let n=r,o=E(n.id),i=E(n.kind);if(!o||!i)continue;let s={id:o,kind:i},a=E(n.note);a&&(s.note=a),n.required_before_step===!0&&(s.required_before_step=!0),t.push(s)}return t.length>0?t:void 0}function FS(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let n=r,o=E(n.path);if(!o)continue;let i={path:wr(o)};(n.scope==="project"||n.scope==="global")&&(i.scope=n.scope);let s=E(n.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function zS(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let n=r,o=E(n.command),i=E(n.path);if(!o&&!i)continue;let s={};o&&(s.command=o),i&&(s.path=wr(i));let a=E(n.note);a&&(s.note=a),t.push(s)}return t.length>0?t:void 0}function US(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let n=r,o=E(n.path);if(!o)continue;let i={path:wr(o)};(n.scope==="project"||n.scope==="global")&&(i.scope=n.scope);let s=E(n.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function HS(e){if(e===null||typeof e!="object")return;let t=e,r=E(t.id),n=E(t.title),o=E(t.status),i=o&&Jk.has(o)?o:void 0,s=Wn(t.order)??Number.NaN,a=typeof t.created_at=="string"?t.created_at:"",c=typeof t.updated_at=="string"?t.updated_at:"";if(!r||!n||!i||!Number.isFinite(s)||!a||!c)return;let d={id:r,order:s,title:n,status:i,created_at:a,updated_at:c};return qS(d,t),d}function qS(e,t){let r=[["body","body"],["owner","owner"],["evidence","evidence"],["blocked_reason","blocked_reason"],["superseded_by","superseded_by"]];for(let[i,s]of r){let a=E(t[s]);a&&(e[i]=a)}let n=typeof t.completed_at=="string"?t.completed_at:void 0;n&&n.length>0&&(e.completed_at=n);let o=[["linked_items","linked_items",LS],["files","files",FS],["tests","tests",zS],["docs","docs",US]];for(let[i,s,a]of o){let c=a(t[s]);c&&(e[i]=c)}}function VS(e){if(!Array.isArray(e))return;let t=e.flatMap(r=>{let n=HS(r);return n?[n]:[]});return t.sort((r,n)=>r.order-n.order),t.length>0?t:void 0}function BS(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let n=r,o=typeof n.ts=="string"?n.ts:"",i=typeof n.author=="string"?n.author:"",s=E(n.decision);if(!o||!i||!s)continue;let a={ts:o,author:i,decision:s},c=E(n.rationale);c&&(a.rationale=c);let d=E(n.evidence);d&&(a.evidence=d);let l=E(n.step_id);l&&(a.step_id=l),t.push(a)}return t.length>0?t:void 0}function WS(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let n=r,o=typeof n.ts=="string"?n.ts:"",i=typeof n.author=="string"?n.author:"",s=E(n.text);if(!o||!i||!s)continue;let a={ts:o,author:i,text:s},c=E(n.step_id);c&&(a.step_id=c),t.push(a)}return t.length>0?t:void 0}function GS(e){if(!Array.isArray(e))return;let t=[];for(let r of e){if(r===null||typeof r!="object")continue;let n=r,o=E(n.text);if(!o)continue;let i={text:o},s=E(n.command);s&&(i.command=s);let a=E(n.expected);a&&(i.expected=a),t.push(i)}return t.length>0?t:void 0}function KS(e){if(!e)return;let t=Object.entries(e).map(([r,n])=>[r.trim(),n.trim()]).filter(([r,n])=>r.length>0&&n.length>0).sort((r,n)=>r[0].localeCompare(n[0]));if(t.length!==0)return Object.fromEntries(t)}function br(e){let t=0;for(;t<e.length&&e[t]===`
|
|
36
|
-
`;)t+=1;return e.slice(t).trimEnd()}function YS(e){if(e===void 0)return;if(typeof e=="number")return e;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Jn.includes(t))return t}function XS(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Xn.includes(t))return t}function Sn(e){return e||void 0}function JS(e,t){let r=e,n=t;for(let[o,i]of Object.entries(n))Ba(o)||Object.prototype.hasOwnProperty.call(r,o)||i===void 0||(r[o]=i)}function ZS(e,t){if(!t?.fieldRegistry)return;let r=e;for(let n of t.fieldRegistry.definitions){let o=r[n.metadata_key];o!==void 0&&(r[n.metadata_key]=En(n,o,`metadata field "${n.metadata_key}"`,"metadata"))}}function QS(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let r=Fm(t),n=Object.keys(e).filter(o=>!r.has(o)).sort((o,i)=>o.localeCompare(i));n.length>0&&t.unknownFieldPolicy==="reject"&&nt(`unknown schema fields are not allowed: ${n.join(", ")}`),n.length>0&&t.onWarning?.(`item_unknown_schema_fields:${n.join(",")}`)}function oi(e,t={}){let r=jm(t),n=ei(e.status,r?.statusRegistry)??e.status,o=Array.from(new Set((Array.isArray(e.tags)?e.tags:[]).filter(s=>typeof s=="string").map(s=>s.trim().toLowerCase()).filter(Boolean))).sort((s,a)=>s.localeCompare(a)),i={id:e.id,title:e.title,description:e.description,type:e.type,pm_format_version:Tm(e.pm_format_version),source_type:E(e.source_type),type_options:KS(e.type_options),status:n,priority:e.priority,tags:o,created_at:e.created_at,updated_at:e.updated_at,dependencies:bS(e.dependencies),comments:$a(e.comments),notes:$a(e.notes),learnings:$a(e.learnings),files:OS(e.files),tests:xS(e.tests),test_runs:AS(e.test_runs),docs:jS(e.docs),deadline:Sn(e.deadline),reminders:wS(e.reminders),events:ES(e.events),closed_at:Sn(e.closed_at),completed_at:Sn(e.completed_at),assignee:E(e.assignee),claim_principal:E(e.claim_principal),source_owner:E(e.source_owner),author:Sn(e.author),estimated_minutes:e.estimated_minutes,acceptance_criteria:e.acceptance_criteria??void 0,design:e.design??void 0,external_ref:e.external_ref??void 0,definition_of_ready:E(e.definition_of_ready),order:e.order,goal:E(e.goal),objective:E(e.objective),value:E(e.value),impact:E(e.impact),outcome:E(e.outcome),why_now:E(e.why_now),parent:E(e.parent),reviewer:E(e.reviewer),risk:e.risk??void 0,confidence:YS(e.confidence),sprint:E(e.sprint),release:E(e.release),blocked_by:E(e.blocked_by),blocked_reason:E(e.blocked_reason),unblock_note:E(e.unblock_note),reporter:E(e.reporter),severity:XS(e.severity),environment:E(e.environment),repro_steps:E(e.repro_steps),resolution:E(e.resolution),expected_result:E(e.expected_result),actual_result:E(e.actual_result),affected_version:E(e.affected_version),fixed_version:E(e.fixed_version),component:E(e.component),regression:e.regression,customer_impact:E(e.customer_impact),close_reason:Sn(e.close_reason),plan_mode:E(e.plan_mode),plan_scope:E(e.plan_scope),plan_harness:E(e.plan_harness),plan_resume_context:E(e.plan_resume_context),plan_steps:VS(e.plan_steps),plan_decisions:BS(e.plan_decisions),plan_discoveries:WS(e.plan_discoveries),plan_validation:GS(e.plan_validation)};return JS(i,e),ZS(i,r),QS(i,r),ni(i),i}function zm(e){return A(e,Ee)}function eO(e){let t=0,r=!1,n=!1;for(let o=0;o<e.length;o+=1){let i=e[o];if(r){if(n){n=!1;continue}if(i==="\\"){n=!0;continue}i==='"'&&(r=!1);continue}if(i==='"'){r=!0;continue}if(i==="{"){t+=1;continue}if(i==="}"&&(t-=1,t===0))return o}return-1}function tO(e){if(!e.startsWith("{"))return{frontMatter:"",body:e};let t=eO(e);if(t<0)return{frontMatter:"",body:e};let r=e.slice(0,t+1),n=e.slice(t+1).replace(/^\r?\n+/,"");return{frontMatter:r,body:n}}function rO(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,r=t.match(/^[ \t]*---[ \t]*(?:\r?\n|$)/);if(!r)return{content:t,stripped:!1};let n=r[0].length;for(;n<t.length;){let o=t.indexOf(`
|
|
37
|
-
`,n),i=o===-1?t.length:o,s=t.slice(n,i).replace(/\r$/,""),a=o===-1?i:i+1;if(s.trim()==="---")return{content:t.slice(a).replace(/^\s+/,""),stripped:!0};n=a}return{content:t,stripped:!1}}function Ua(e,t){return oi(e,{...t,onWarning:void 0})}function nO(e,t,r={}){let n=rO(e);n.stripped&&r.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored");let{frontMatter:o,body:i}=tO(n.content);o||(e.trimStart().startsWith("{")&&On("json_markdown","JSON front matter is not valid JSON"),On("json_markdown","JSON Markdown item document is missing JSON front matter"));let s;try{s=JSON.parse(o)}catch{On("json_markdown","JSON front matter is not valid JSON")}return Lm(s,r.requireSupportedFormat),za(s,t),{metadata:Ua(s,r),body:br(i)}}function oO(e,t,r={}){let n;try{n=Pa(e).value}catch{On("toon","TOON item document is not valid TOON")}O(typeof n=="object"&&n!==null&&!Array.isArray(n),"TOON item document must be an object");let o=n;if(Lm(Object.prototype.hasOwnProperty.call(o,"front_matter")?o.front_matter:o,r.requireSupportedFormat),!$m.some(a=>Object.prototype.hasOwnProperty.call(o,a))&&!Object.prototype.hasOwnProperty.call(o,"front_matter")&&On("toon","TOON input does not have the shape of an item document"),Object.prototype.hasOwnProperty.call(o,"front_matter"))return za(o.front_matter,t),O(o.body===void 0||typeof o.body=="string","TOON item document body must be a string"),{metadata:Ua(o.front_matter,r),body:br(typeof o.body=="string"?o.body:"")};let{body:i,...s}=o;return O(i===void 0||typeof i=="string","TOON item document body must be a string"),za(s,t),{metadata:Ua(s,r),body:br(typeof i=="string"?i:"")}}function iO(e,t={}){let r=oi(e.metadata,t),n=zm(r),o=br(e.body??"");qa(JSON.parse(JSON.stringify(n))),qa({body:o});let i=JSON.stringify(n,null,2);return o?`${i}
|
|
38
|
-
|
|
39
|
-
${o}
|
|
40
|
-
`:`${i}
|
|
41
|
-
`}var sO=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;function Ha(e,t){return typeof e=="string"?Nm(e,t):e===null||typeof e!="object"?null:Array.isArray(e)?Dm(e.map((r,n)=>()=>Ha(r,`${t}[${n}]`))):Dm(Object.entries(e).map(([r,n])=>()=>{let o=t?`${t}.${r}`:r;return Nm(r,`${o} (key)`)??Ha(n,o)}))}function Nm(e,t){let r=e.search(sO);return r<0?null:{path:t,index:r}}function Dm(e){for(let t of e){let r=t();if(r!==null)return r}return null}function qa(e){let t=Ha(e,"");if(t!==null)throw new g(`Item field ${t.path} contains an unpaired surrogate code unit at index ${t.index}; persisted item text requires well-formed Unicode.`,h.USAGE,{code:"text_unpaired_surrogate",field:t.path,required:"Provide well-formed UTF-16 text: keep emoji and other astral characters whole and avoid lone \\uD800-\\uDFFF JSON escapes.",why:"Persisted item text must remain well-formed in every supported format; a lone surrogate can cause an unclassified encoder fault.",nextSteps:[`Repair the ${t.path} value (for example String.prototype.toWellFormed() or re-truncate on a character boundary) and retry.`,"Run pm <command> --help --json to review the text fields the command accepts."]})}function aO(e,t={}){let r=oi(e.metadata,t),n=zm(r),o=br(e.body??""),i={...n,body:o},s=JSON.parse(JSON.stringify(i));qa(s);let a=Kk(s),c;try{c=Pa(a).value}catch(d){throw new g("Refusing to persist a TOON item document that the configured decoder cannot read back.",h.GENERIC_FAILURE,{code:"item_document_roundtrip_failed",reason:"encode_decode_error",format:"toon",required:"Upgrade or repair the TOON codec before retrying the mutation; no item bytes were written.",why:d instanceof Error?d.message:String(d)})}if(!Cm(c,s)){let d=typeof c=="object"&&c!==null&&!Array.isArray(c)?c:{},l=Object.keys(s).find(u=>!Cm(s[u],d[u]))??"document";throw new g(`Refusing to persist a lossy TOON item document; round-trip mismatch at field "${l}".`,h.GENERIC_FAILURE,{code:"item_document_roundtrip_failed",reason:"encode_decode_mismatch",format:"toon",field:l,required:"Upgrade or repair the TOON codec before retrying the mutation; no item bytes were written.",why:"The encoded document decoded to a value different from the canonical item payload."})}return`${a}
|
|
42
|
-
`}function n$(e,t={}){let r=ti(e);if(r)throw new g(`Merge conflict markers detected in item document at line ${r.line} (${r.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,h.GENERIC_FAILURE,{code:"merge_conflict_markers_detected",reason:"merge_conflict",required:"Resolve merge-conflict markers in the item file before parsing or mutation commands.",why:"Partially merged documents can corrupt item metadata and history integrity.",examples:["git status","git add <resolved-file> && git commit"],nextSteps:["Resolve conflicts, save the file, then rerun the pm command."]});let n=t.format??"toon",o=jm(t);return n==="toon"?oO(e,o,t):nO(e,o,t)}function o$(e,t={}){return(t.format??"toon")==="toon"?aO(e,t):iO(e,t)}function vr(e,t={}){return{metadata:oi(e.metadata,t),body:br(e.body??"")}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="82c79093-2a40-5b4c-8d41-637b0ae03c4f")}catch{}})();function Um(e){return e}import{AsyncLocalStorage as cO}from"node:async_hooks";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1fbb183b-c6d8-5834-b4cb-e4fb515572b9")}catch{}})();var Wa=new cO,Hm=/^[A-Za-z0-9](?:[A-Za-z0-9._:-]{0,127})$/u;function ii(e,t){let r=typeof e=="string"?e.trim():"";return r.length>0?r.slice(0,t):void 0}function Rt(e,t){if(e===void 0)return;let r=typeof e=="object"&&e!==null?e:{},n=ii(r.id,128),o=ii(r.parent_id,128);if(n===void 0||!Hm.test(n)||o!==void 0&&!Hm.test(o)){if(t)throw new Error("Agent episode ids must be 1-128 letters, digits, dots, underscores, colons, or hyphens.");return}let i=ii(r.label,256);return{id:n,...i===void 0?{}:{label:i},...o===void 0?{}:{parent_id:o}}}function Er(e){let t={};for(let[r,n]of Object.entries(e??{}).slice(0,32)){let o=r.trim().toLowerCase().slice(0,64),i=ii(n,256);/^[a-z][a-z0-9_-]{0,63}$/u.test(o)&&i!==void 0&&(t[o]=i)}return t}function dO(e,t,r){let n=Wa.getStore(),o=Er({role:t.PM_AGENT_SESSION_ROLE,topic:t.PM_AGENT_SESSION_TOPIC}),i=Rt(t.PM_AGENT_EPISODE_ID===void 0?void 0:{id:t.PM_AGENT_EPISODE_ID,label:t.PM_AGENT_EPISODE_LABEL,parent_id:t.PM_AGENT_EPISODE_PARENT_ID},!1),s={...Er(n?.provenance),...o,...Er(e?.provenance)},a=Rt(e?.episode,!1)??Rt(r,!1)??i??Rt(n?.episode,!1);return Object.keys(s).length===0&&a===void 0?void 0:{...Object.keys(s).length===0?{}:{provenance:s},...a===void 0?{}:{episode:a}}}function Ga(e,t){return dO(e.session_context,t,e.client_info?.episode)??{}}function c$(e,t){let r=Wa.getStore(),n=Rt(e.episode,!0),o=Rt(r?.episode,!1),i=n!==void 0&&n.parent_id===void 0&&o!==void 0?{...n,parent_id:o.id}:n,s={...Er(r?.provenance),...Er(e.provenance)};return Wa.run({...Object.keys(s).length===0?{}:{provenance:s},...i===void 0?o===void 0?{}:{episode:o}:{episode:i}},t)}function d$(e){let t=Er(e.provenance),r=Rt(e.episode,!0);return{...r===void 0?{}:{PM_AGENT_EPISODE_ID:r.id,...r.label===void 0?{}:{PM_AGENT_EPISODE_LABEL:r.label},...r.parent_id===void 0?{}:{PM_AGENT_EPISODE_PARENT_ID:r.parent_id}},...t.role===void 0?{}:{PM_AGENT_SESSION_ROLE:t.role},...t.topic===void 0?{}:{PM_AGENT_SESSION_TOPIC:t.topic}}}import{createHash as qm}from"node:crypto";import{existsSync as Ka,promises as Vm,readFileSync as lO}from"node:fs";import Ce from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="06c9f6f4-c2f0-549c-9a0f-4f4269cc5f49")}catch{}})();var uO="session.json";function Ya(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function Bm(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,r=["implementer","planner","release-operator"].includes(String(t.role)),n=["high","medium"].includes(String(t.confidence)),o=Ya(t.topic,256),i=Array.isArray(t.evidence)&&t.evidence.length<=32&&t.evidence.every(c=>typeof c=="string"&&c.length<=128),s=Array.isArray(t.active_item_ids)&&t.active_item_ids.length<=64&&t.active_item_ids.every(c=>Ya(c,128)),a=t.focused_item_id===void 0||Ya(t.focused_item_id,128);if([r,n,o,i,s,a,t.rule_version==="v2"].every(Boolean))return t}function fO(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=Object.entries(e).slice(0,128).flatMap(([r,n])=>{let o=Bm(n);return o&&r.length<=128?[[r,o]]:[]});return t.length>0?Object.fromEntries(t):void 0}function Xa(e){return Ce.join(Zi(e),uO)}async function Wm(e){try{let t=await Vm.readFile(Xa(e),"utf8"),r=JSON.parse(t);if(r===null||typeof r!="object"||Array.isArray(r))return{};let n=r,o=n.focused_item,i=fO(n.semantic_attribution);return typeof o=="string"&&o.trim().length>0?{focused_item:o,...i?{semantic_attribution:i}:{}}:i?{semantic_attribution:i}:{}}catch{return{}}}async function Ja(e,t){let r=await le(e,"session-state",S.locks.ttl_seconds,"session-state",!1,!0,S.locks.wait_ms);try{let n=await Wm(e);t(n);let o=Xa(e);await Vm.mkdir(Ce.dirname(o),{recursive:!0}),await mt(o,JSON.stringify(n))}finally{await r()}}function Za(e){return/#([a-f0-9]{24})$/u.exec(e.trim())?.[1]??`author-${qm("sha256").update(e).digest("hex").slice(0,24)}`}function Qa(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].slice(0,32).map(t=>t.slice(0,128))}function ec(e){let t=[...new Set(e)].sort((n,o)=>n.localeCompare(o));if(t.length===1)return t[0];let r=`workset:${t.join("+")}`;return r.length<=256?r:`workset:${t.join("+").slice(0,230)}+${qm("sha256").update(t.join("\0")).digest("hex").slice(0,12)}`}async function tc(e,t,r){await Ja(e,n=>{let o={...n.semantic_attribution},i=r(o[t]);i===void 0?delete o[t]:o[t]=i,Object.keys(o).length===0?delete n.semantic_attribution:n.semantic_attribution=o})}async function g$(e){let t=Za(e.principal);await tc(e.pmRoot,t,r=>{let n=[...new Set([...r?.active_item_ids??[],e.itemId])].slice(-64).sort((i,s)=>i.localeCompare(s)),o=r?.focused_item_id;return{role:"implementer",topic:o??ec(n),confidence:o?"high":"medium",rule_version:"v2",evidence:Qa([...n.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],...(e.lineageIds??[]).map(i=>`lineage:${i}`)]),active_item_ids:n,...o?{focused_item_id:o}:{}}})}async function b$(e){let t=Za(e.principal);await tc(e.pmRoot,t,r=>{if(!r)return;let n=r.active_item_ids.filter(i=>i!==e.itemId);if(n.length===0&&!r.focused_item_id)return;let o=r.focused_item_id;return{...r,role:"release-operator",topic:o??ec(n),confidence:o?"high":"medium",evidence:Qa([...n.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],`release:${e.itemId}`]),active_item_ids:n}})}async function w$(e){let t=Za(e.principal);await tc(e.pmRoot,t,r=>{let n=r?.active_item_ids??[];if(!e.itemId&&n.length===0)return;let o=e.itemId;return{role:o?"planner":r.role,topic:o??ec(n),confidence:o?"high":"medium",rule_version:"v2",evidence:Qa([...n.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],...(e.lineageIds??[]).map(i=>`lineage:${i}`)]),active_item_ids:n,...o?{focused_item_id:o}:{}}})}function mO(e,t){let r=t.PM_PATH?.trim();if(r){let o=Ce.resolve(e,r);if(Ka(Ce.join(o,"settings.json")))return o;let i=Ce.join(o,".agents","pm");if(Ka(Ce.join(i,"settings.json")))return i}let n=Ce.resolve(e);for(let o=0;o<32;o+=1){let i=Ce.join(n,".agents","pm");if(Ka(Ce.join(i,"settings.json")))return i;let s=Ce.dirname(n);if(s===n)break;n=s}}function Gm(e){if(!e.key)return;let t=mO(e.cwd,e.env);if(t)try{let r=JSON.parse(lO(Xa(t),"utf8"));return Bm(r.semantic_attribution?.[e.key])}catch{return}}async function v$(e){return(await Wm(e)).focused_item}async function E$(e,t){await Ja(e,r=>{r.focused_item=t})}async function k$(e){await Ja(e,t=>{delete t.focused_item})}import{AsyncLocalStorage as sc}from"node:async_hooks";import{createHash as pO}from"node:crypto";import fe from"node:fs";import Jm from"node:os";import Dt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a69b86e2-6633-5abc-81b7-6a54a592d36c")}catch{}})();var ac=["model","effort","role","topic","version"],ci=new sc,Zm=new sc,di=new sc,cc=[{harness:"claude-code",environment_keys:["CLAUDE_CODE","CLAUDECODE"],model_environment_keys:["ANTHROPIC_MODEL","CLAUDE_MODEL"],session_environment_keys:["CLAUDE_CODE_SESSION_ID"],provenance_environment_keys:{effort:["CLAUDE_EFFORT"]},provenance_resolvers:{model:"claude_session_file",version:"claude_session_file"},provenance_unavailable_dimensions:["role","topic"],argv_markers:["claude","claude-code"],client_names:["claude","claude-code","claude code"]},{harness:"codex",environment_keys:["CODEX_HOME","CODEX_CI","CODEX_THREAD_ID"],model_environment_keys:["CODEX_MODEL"],session_environment_keys:["CODEX_THREAD_ID"],provenance_environment_keys:{effort:["CODEX_REASONING_EFFORT","CODEX_EFFORT"],role:["CODEX_SESSION_ROLE"]},provenance_resolvers:{model:"codex_session_file",effort:"codex_session_file",version:"ai_agent_version"},provenance_unavailable_dimensions:["topic"],argv_markers:["codex"],client_names:["codex"]},{harness:"pi",environment_keys:["PI_AGENT","PI_CODING_AGENT"],model_environment_keys:["PI_MODEL"],session_environment_keys:["PI_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["pi"],client_names:["pi"]},{harness:"opencode",environment_keys:["OPENCODE","OPENCODE_SESSION_ID"],model_environment_keys:["OPENCODE_MODEL"],session_environment_keys:["OPENCODE_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["opencode"],client_names:["opencode"]},{harness:"cursor",environment_keys:["CURSOR_AGENT","CURSOR_TRACE_ID"],model_environment_keys:["CURSOR_MODEL"],session_environment_keys:["CURSOR_TRACE_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["cursor"],client_names:["cursor"]},{harness:"aider",environment_keys:["AIDER","AIDER_MODEL"],model_environment_keys:["AIDER_MODEL"],session_environment_keys:["AIDER_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["aider"],client_names:["aider"]},{harness:"gemini-cli",environment_keys:["GEMINI_CLI","GEMINI_CLI_HOME"],model_environment_keys:["GEMINI_MODEL"],session_environment_keys:["GEMINI_CLI_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["gemini","gemini-cli"],client_names:["gemini","gemini-cli","gemini cli"]},{harness:"ci",environment_keys:["CI","GITHUB_ACTIONS","BUILDKITE","GITLAB_CI"],provenance_unavailable_dimensions:["model","effort","role","topic"],argv_markers:[],client_names:[]}],Qm=Object.freeze({max_bytes:1048576,max_lines:4096,network_access:!1,subprocess_access:!1}),_O=Object.freeze({...Qm,max_bytes:4194304}),rc=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function yO(e){let t=it(e).provenance_unavailable_dimensions,r=new Set(["model","version",...Object.keys(e.provenance_environment_keys??{}),...Object.keys(e.provenance_resolvers??{})]);return Object.freeze({contract_version:1,adapter_version:"v1",priority:0,harness:e.harness,descriptor:e,supported_dimensions:Object.freeze([...r].sort()),native_sources:Object.freeze(["environment","argv","mcp_client",...Object.values(e.provenance_resolvers??{}).some(n=>n?.endsWith("session_file"))?["session_file"]:[]]),probe_policy:e.harness==="codex"?_O:Qm,normalization:Object.freeze({model_family:"v1",effort:"v1",preserve_raw:!0}),confidence:"high",waivers:Object.freeze(Object.fromEntries(t.map(n=>[n,"Harness does not expose this dimension."])))})}var ep=Object.freeze(cc.filter(e=>e.harness!=="ci").map(yO).sort((e,t)=>e.harness.localeCompare(t.harness))),Nt=new Map,kr=new Map;function q(e){let t=typeof e=="string"?e.trim():void 0;return t&&t.length>0?t:void 0}function ot(e){return[...new Set((e??[]).slice(0,64).map(t=>t.trim()).filter(t=>t.length>0).map(t=>t.slice(0,128)))]}function it(e){let t=e.harness.trim().toLowerCase();if(!rc.test(t))throw new Error(`Invalid harness signal descriptor namespace: ${e.harness}`);return{harness:t,environment_keys:ot(e.environment_keys),model_environment_keys:ot(e.model_environment_keys),session_environment_keys:ot(e.session_environment_keys),provenance_environment_keys:Object.fromEntries(Object.entries(e.provenance_environment_keys??{}).slice(0,32).map(([r,n])=>[r.trim().toLowerCase().slice(0,64),ot(n)]).filter(([r])=>rc.test(r))),provenance_resolvers:Object.fromEntries(Object.entries(e.provenance_resolvers??{}).slice(0,32).map(([r,n])=>[r.trim().toLowerCase().slice(0,64),n]).filter(r=>typeof r[0]=="string"&&rc.test(r[0])&&(r[1]==="ai_agent_version"||r[1]==="claude_session_file"||r[1]==="codex_session_file"))),provenance_unavailable_dimensions:ot(e.provenance_unavailable_dimensions).map(r=>r.toLowerCase()),argv_markers:ot(e.argv_markers).map(r=>r.toLowerCase()),client_names:ot(e.client_names).map(r=>r.toLowerCase())}}var tp=cc.map(it);function hO(e,t){return JSON.stringify(e)===JSON.stringify(t)}function ai(e,t){return e.toLowerCase().slice(0,512).split(/[/\\\s:=]+/u).filter(r=>r.length>0).includes(t)||e.trim().toLowerCase()===t}function dc(e=[]){let t=new Map(cc.filter(o=>o.harness!=="ci").map(o=>[o.harness,it(o)]));for(let{adapter:o}of Nt.values())t.set(o.harness,it(o.descriptor));let r=[...t.values(),...tp.filter(o=>o.harness==="ci"),...[...kr.values()].map(o=>o.descriptor),...di.getStore()?.descriptors??[],...e.map(it)],n=new Set;for(let o of r){if(n.has(o.harness))throw new Error(`Harness signal descriptor collision for "${o.harness}"`);n.add(o.harness)}return r}function lc(e,t){for(let r of t??[]){let n=q(e[r]);if(n)return n.slice(0,256)}}function gO(e,t){if(t==="role"){let r=e.slice(0,8).map(n=>n.trim().toLowerCase()).find(n=>["claim","create","update","close","release","review"].includes(n));if(r==="review")return"reviewer";if(r)return"implementer"}}function rp(e,t){let r=t==="model"?["--model","--agent-model"]:[`--agent-${t}`],n=e.slice(0,8);for(let o=0;o<n.length;o+=1){let i=n[o].slice(0,512);if(r.includes(i))return q(n[o+1])?.slice(0,256);let s=r.find(a=>i.startsWith(`${a}=`));if(s)return q(i.slice(s.length+1))?.slice(0,256)}}var bO=new Set(["implementation","implementer","investigator","orchestrator","planner","release-operator","reviewer"]);function xt(e,t){if(e!=="role"||t===void 0)return t;let r=t.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");return bO.has(r)?r:void 0}function nc(e,t){return q(e?.[t])?.slice(0,256)}var wO=1048576,ic=4194304,si=new Map,Km=Object.freeze({}),oc=new Map,Ym=Object.freeze({});function Xm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function vO(e){let t;try{t=JSON.parse(e)}catch{return Ym}let r=Xm(t);if(!r)return Ym;let n=[{value:r,depth:0}],o=0,i,s;for(;n.length>0&&o<64;){let a=n.shift();if(o+=1,i??=q(a.value.model)?.slice(0,256),s??=q(a.value.version)?.slice(0,256),i&&s)break;if(!(a.depth>=4))for(let c of Object.values(a.value)){let d=Xm(c);d&&n.push({value:d,depth:a.depth+1})}}return Object.freeze({model:i,version:s})}function np(e){try{return fe.lstatSync(e).isFile()?"available":"missing"}catch(t){return Se(t)?"missing":"failed"}}function EO(e,t){let r;try{r=fe.readdirSync(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).sort((o,i)=>o.name.localeCompare(i.name)).slice(0,512).map(o=>{let i=Dt.join(e,o.name,`${t}.jsonl`);return{candidate:i,status:np(i)}})}catch(o){return{status:Se(o)?"missing":"failed"}}let n=r.filter(({status:o})=>o==="available").map(({candidate:o})=>o);return n.length===0?{status:r.some(({status:o})=>o==="failed")?"failed":"missing"}:n.length>1?{status:"ambiguous"}:{status:"available",path:n[0]}}function op(e,t){let r=q(t.CLAUDE_CODE_SESSION_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return{status:"unavailable"};let n=Dt.resolve(e.cwd??process.cwd()).replaceAll(/[^A-Za-z0-9-]/gu,"-"),o=Dt.join(e.home_dir??Jm.homedir(),".claude","projects"),i=Dt.join(o,n,`${r}.jsonl`),s=q(e.session_file),a=s&&Dt.basename(s)===`${r}.jsonl`?s:void 0;for(let c of[a,i]){if(!c)continue;let d=np(c);if(d==="available")return{status:d,path:c};if(d==="failed")return{status:d}}return EO(o,r)}function kO(e,t,r){let n=op(t,r);if(n.status==="available")try{let o=fe.openSync(n.path,fe.constants.O_RDONLY|fe.constants.O_NOFOLLOW);try{let i=fe.fstatSync(o),s=`${n.path}\0${i.size}\0${i.mtimeMs}`,a=oc.get(s);if(a)return a[e];let c=Math.min(i.size,wO),d=Math.min(c,Math.ceil(c/2)),l=Math.min(c-d,i.size-d),u=Buffer.alloc(d);fe.readSync(o,u,0,d,0);let f=Buffer.alloc(l);l>0&&fe.readSync(o,f,0,l,i.size-l);let m={},_=i.size<=c?Buffer.concat([u,f]).toString("utf8").split(`
|
|
43
|
-
`):[...u.toString("utf8").split(`
|
|
44
|
-
`).slice(0,4096),...f.toString("utf8").split(`
|
|
45
|
-
`).slice(-4096)];for(let w of _){if(w.length===0||w.length>262144)continue;let v=vO(w);if(m.model??=v.model,m.version??=v.version,m.model&&m.version)break}let y=Object.freeze(m);return oc.clear(),oc.set(s,y),y[e]}finally{fe.closeSync(o)}}catch{return}}function SO(e,t){let r=0,n=(o,i)=>{if(i>4||r>=512)return;let s;try{s=fe.readdirSync(o,{withFileTypes:!0}).sort((a,c)=>c.name.localeCompare(a.name))}catch{return}for(let a of s){if(r+=1,r>512)return;let c=Dt.join(o,a.name);if(a.isFile()&&a.name.endsWith(`-${t}.jsonl`))return c;if(a.isDirectory()){let d=n(c,i+1);if(d)return d}}};return n(e,0)}function OO(e){if(e<=ic)return[{offset:0,length:e}];let t=Math.floor(ic/2);return[{offset:e-t,length:t},{offset:0,length:t}]}function AO(e,t){if(t.length===0||t.length>262144)return;let r;try{r=JSON.parse(t)}catch{return}if(typeof r!="object"||r===null||Array.isArray(r))return;let n=r;if(n.type!=="turn_context")return;let o=typeof n.payload=="object"&&n.payload!==null?n.payload:void 0;e.model??=q(o?.model)?.slice(0,256),e.effort??=q(o?.effort)?.slice(0,256)}function IO(e,t){let r={},n=4096;for(let o of OO(t)){let i=Buffer.alloc(o.length);fe.readSync(e,i,0,o.length,o.offset);let s=i.toString("utf8").split(`
|
|
46
|
-
`).reverse().slice(0,n);n-=s.length;for(let a of s)if(AO(r,a),r.model&&r.effort)break;if(r.model&&r.effort||n<=0)break}return r}function TO(e,t,r){let n=q(r.CODEX_THREAD_ID);if(!n||!/^[A-Za-z0-9_-]{1,128}$/u.test(n))return;let o=Dt.join(t.home_dir??Jm.homedir(),".codex","sessions"),i=`${o}\0${n}`,s=si.get(i);if(s)return s[e];let a=SO(o,n);if(!a){si.set(i,Km);return}try{let c=fe.openSync(a,"r");try{let d=fe.fstatSync(c).size,l=IO(c,d);return si.set(i,l),l[e]}finally{fe.closeSync(c)}}catch{si.set(i,Km);return}}function CO(e,t,r,n){let o=di.getStore();if(!(t.probes_enabled!==!1&&o?.probesEnabled!==!1&&!["0","false","off"].includes(q(r.PM_AGENT_PROBES)?.toLowerCase()??"")))return;let i=n?.provenance_resolvers[e];if(i==="claude_session_file")return kO(e,t,r);if(i==="codex_session_file")return TO(e,t,r);if(i==="ai_agent_version"){let s=q(r.AI_AGENT);return!s||!n||!ai(s,n.harness)?void 0:/(?:^|[@/\s])v?(\d+\.\d+(?:\.\d+)?(?:[-+][A-Za-z0-9.-]+)?)$/u.exec(s)?.[1]?.slice(0,256)}}function RO(e,t,r,n){if(e==="ai_agent_version"){let o=q(n.AI_AGENT);return o!==void 0&&ai(o,t.harness)?"available":"unavailable"}return e==="codex_session_file"?q(n.CODEX_THREAD_ID)!==void 0?"available":"unavailable":op(r,n).status}function uc(e){return e||(Zm.getStore()??{env:process.env,argv:process.argv})}function xO(e,t,r,n){let o=e.environment_keys.some(a=>q(t[a])!==void 0),i=e.argv_markers.some(a=>r.some(c=>{let d=c.replaceAll("\\","/");return ai(d.slice(d.lastIndexOf("/")+1),a)})),s=e.client_names.some(a=>n===a||ai(n,a));return o||i||s}function NO(e,t){if(!t)return;let r;if(e==="topic"&&(r=t.topic),e==="role"&&(r=t.role),!!r)return{value:r,source:"inferred",confidence:t.confidence,rule_version:t.rule_version,evidence:t.evidence}}function DO(e){let t=e.find(([r])=>r!==void 0);return t?.[0]?{value:t[0],source:t[1]}:void 0}function PO(e,t,r,n,o,i){let s=`PM_AGENT_${e.toUpperCase().replaceAll("-","_")}`,a=new Set([...ac,...Object.keys(n?.provenance_environment_keys??{})]),c,d,l;a.has(e)&&(c=xt(e,q(r[s])?.slice(0,256)),l=xt(e,rp(t.argv??[],e)),d=xt(e,gO(t.argv??[],e)));let u={...n?.provenance_environment_keys,model:n?.model_environment_keys},f={...t.client_info?.provenance,model:t.client_info?.model},m=nc(o?.provenance,e),_=xt(e,lc(r,u[e])),y=xt(e,nc(f,e)),w=xt(e,nc(t.provenance,e)),v=CO(e,t,r,n);return DO([[c,"override"],[m,"session"],[l,"argv"],[_,"environment"],[y,"mcp_client"],[w,"host"],[v,"probe"]])??NO(e,i)??(d?{value:d,source:"argv"}:void 0)}function MO(e,t){if(!(!e||!t))return pO("sha256").update(`pm-agent-instance:v1\0${e}\0${t}`).digest("hex").slice(0,24)}function $O(e,t,r,n,o){let i=Object.keys(r?.provenance_environment_keys??{}),s=new Set([...ac,...i,...Object.keys(r?.provenance_resolvers??{}),...Object.keys(e.provenance??{}),...Object.keys(e.client_info?.provenance??{}),...Object.keys(n?.provenance??{})]),a={};for(let c of s){let d=PO(c,e,t,r,n,o);d?a[c]=d:r&&(c!=="version"||r.provenance_unavailable_dimensions.includes(c))&&(a[c]=null)}return a}function D$(e){let t=e.map(it),r=new Map(tp.map(i=>[i.harness,i])),n=new Set;for(let i of t){if(n.has(i.harness)||r.has(i.harness))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);let s=kr.get(i.harness);if(s&&!hO(s.descriptor,i))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);n.add(i.harness)}for(let i of t){let s=kr.get(i.harness);kr.set(i.harness,{descriptor:i,registrations:(s?.registrations??0)+1})}let o=!0;return()=>{if(o){o=!1;for(let i of t){let s=kr.get(i.harness);!s||s.registrations<=1?kr.delete(i.harness):s.registrations-=1}}}}function jO(e){let t=it(e.descriptor),r=e.harness.trim().toLowerCase();if(e.contract_version!==1)throw new Error(`Unsupported provenance adapter contract for "${r}": ${e.contract_version}`);if(t.harness!==r)throw new Error(`Provenance adapter harness "${r}" does not match descriptor "${t.harness}".`);let n=q(e.adapter_version)?.slice(0,64);if(!n)throw new Error(`Provenance adapter "${r}" requires a version.`);if(!Number.isSafeInteger(e.priority))throw new Error(`Provenance adapter "${r}" requires an integer priority.`);if(e.probe_policy.network_access!==!1||e.probe_policy.subprocess_access!==!1||e.probe_policy.max_bytes>ic||e.probe_policy.max_lines>4096)throw new Error(`Provenance adapter "${r}" exceeds the bounded local probe policy.`);return Object.freeze({...e,adapter_version:n,harness:r,descriptor:t,supported_dimensions:Object.freeze(ot(e.supported_dimensions).map(o=>o.toLowerCase()).sort()),native_sources:Object.freeze([...new Set(e.native_sources)]),probe_policy:Object.freeze({...e.probe_policy}),normalization:Object.freeze({...e.normalization}),...e.waivers?{waivers:Object.freeze(Object.fromEntries(Object.entries(e.waivers).slice(0,32).map(([o,i])=>[o.slice(0,64),i.slice(0,256)])))}:{}})}function P$(){let e=new Map(ep.map(t=>[t.harness,t]));for(let{adapter:t}of Nt.values())e.set(t.harness,t);return Object.freeze([...e.values()].sort((t,r)=>t.harness.localeCompare(r.harness)))}function M$(e){let t=e.map(jO),r=new Map(ep.map(i=>[i.harness,i])),n=new Set;for(let i of t){if(n.has(i.harness))throw new Error(`Provenance adapter collision for "${i.harness}".`);let s=r.get(i.harness);if(s&&i.priority<=s.priority)throw new Error(`Provenance adapter override for "${i.harness}" requires priority greater than ${s.priority}.`);let a=Nt.get(i.harness);if(a&&JSON.stringify(a.adapter)!==JSON.stringify(i))throw new Error(`Provenance adapter collision for "${i.harness}".`);n.add(i.harness)}for(let i of t){let s=Nt.get(i.harness);Nt.set(i.harness,{adapter:i,registrations:(s?.registrations??0)+1})}let o=!0;return()=>{if(o){o=!1;for(let i of t){let s=Nt.get(i.harness);!s||s.registrations<=1?Nt.delete(i.harness):s.registrations-=1}}}}function $$(e,t){let r=t.trim().slice(0,256),n=r.toLowerCase();if(e==="model"){let o=/^(gpt-\d+(?:\.\d+)?)/u.exec(n)?.[1];o&&(n=o)}else n=n.replaceAll(/[_\s-]+/gu,""),n={minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max",ultra:"ultra"}[n]??n;return{raw:r,normalized:n,vocabulary:"v1"}}function j$(e,t){return Zm.run(e,t)}function L$(e,t,r={}){let n=e.map(it);return dc(n),di.run({descriptors:n,probesEnabled:r.probesEnabled!==!1},t)}function fc(e){let t=uc(e),r=t.env??{},n=dc(t.descriptors),o=[...(t.argv??[]).slice(0,3),...t.process_labels??[]].slice(0,64).map(_=>_.slice(0,512)),i=t.client_info?.name.trim().toLowerCase()??"",s=n.find(_=>xO(_,r,o,i)),a=Ga(t,r),c=[lc(r,s?.session_environment_keys),q(t.client_info?.session)?.slice(0,256)].find(_=>_!==void 0),d=MO(s?.harness,c),l=Gm({cwd:t.cwd??process.cwd(),env:r,key:d}),u=$O(t,r,s,a,l),f=u.model,m=[["harness",s?.harness],["model",f?.value],["model_source",f?.source],["session",c],["instance",d],["provenance",Object.keys(u).length>0?u:void 0],["episode",a.episode]];return Object.fromEntries(m.filter(_=>_[1]!==void 0))}function LO(e){return e==="unavailable"?{status:"unavailable",reason:"harness_unavailable"}:e==="missing"?{status:"unavailable",reason:"resolver_input_missing"}:{status:"failed",reason:"resolver_failed"}}function FO(e,t,r,n,o,i,s){let a=r?.provenance_resolvers[e];if(t.provenance?.[e])return{status:"resolved",...a?{resolver:a}:{},rule_version:"v1"};if(s)return{status:"unavailable",reason:"invalid_value",rule_version:"v1"};if(a){if(!i)return{status:"unavailable",reason:"probes_disabled",resolver:a,rule_version:"v1"};let c=RO(a,r,n,o);return{...LO(c),resolver:a,rule_version:"v1"}}return{status:r?.provenance_unavailable_dimensions.includes(e)?"unavailable":"not_configured",reason:r?.provenance_unavailable_dimensions.includes(e)?"harness_unavailable":"resolver_not_configured",rule_version:"v1"}}function ip(e){let t=uc(e),r=fc(t),n=dc(t.descriptors).find(d=>d.harness===r.harness),o=t.env??{},i=t.probes_enabled!==!1&&di.getStore()?.probesEnabled!==!1&&!["0","false","off"].includes(q(o.PM_AGENT_PROBES)?.toLowerCase()??""),s=Ga(t,o),a=[o.PM_AGENT_ROLE,s.provenance?.role,lc(o,n?.provenance_environment_keys.role),t.client_info?.provenance?.role,t.provenance?.role,rp(t.argv??[],"role")].some(d=>{let l=q(d)?.slice(0,256);return l!==void 0&&xt("role",l)===void 0}),c=Object.fromEntries(ac.map(d=>[d,FO(d,r,n,t,o,i,d==="role"&&a)]));return{...r,provenance_outcomes:c}}function F$(){return process.env.PM_AUTHOR}function z$(e){e===void 0?delete process.env.PM_AUTHOR:process.env.PM_AUTHOR=e}function U$(e){return fc(e).harness}function zO(e,t,r){let n=uc(r),o=fc(n);if(e!==void 0){let s=q(e);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}if(n.env?.PM_AUTHOR!==void 0){let s=q(n.env.PM_AUTHOR);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}let i=q(t);return i?{author:i,source:"configured",...o}:o.harness?{author:`harness:${o.harness}`,source:"detected",...o}:{author:"unknown",source:"unknown",...o}}function sp(e){let t=ci.getStore();return t?.author===e?t.source:e.startsWith("harness:")?"detected":e==="unknown"?"unknown":"asserted"}function ap(e){let t=ci.getStore();return t?.author!==e?e.startsWith("harness:")?{harness:e.slice(8)}:{}:{...t.harness?{harness:t.harness}:{},...t.model?{model:t.model}:{},...t.model_source?{model_source:t.model_source}:{},...t.session?{session:t.session}:{},...t.instance?{instance:t.instance}:{},...t.provenance?{provenance:t.provenance}:{},...t.episode?{episode:t.episode}:{}}}function H$(e){let t=ci.getStore();return t?.author===e&&t.source==="detected"&&t.instance?`${e}#${t.instance}`:e}function cp(e,t){let r=zO(e,t);return ci.enterWith(r),r.author}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cfedb84f-0525-5e02-af0a-d0e5691b5e0a")}catch{}})();async function UO(e,t){let r=await we(e);if(r===null)return{raw:r,entries:[]};if(await nr({path:e,scope:"project"}),r.trim()==="")return{raw:r,entries:[]};let n=ti(r);if(n)throw new g(`History for ${t} contains merge conflict markers at line ${n.line} (${n.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,h.GENERIC_FAILURE,{code:"history_merge_conflict_markers_detected",required:"Repair the history stream by resolving merge-conflict markers.",why:"Conflict markers break JSONL parsing and invalidate deterministic audit history.",examples:[`pm history ${t}`,`pm restore ${t} <timestamp-or-version>`],nextSteps:["Resolve or restore the history file, then rerun the command."]});let o=[];for(let[i,s]of r.split(/\r?\n/).entries()){let a=s.trim();if(a)try{o.push(JSON.parse(a))}catch{throw new g(`History for ${t} contains invalid JSON at line ${i+1}. Repair or restore the history stream and retry.`,h.GENERIC_FAILURE,{code:"history_json_invalid",nextSteps:[`Run pm history-repair ${t} --salvage-tail --dry-run to check whether only an invalid suffix is damaged.`]})}}return{raw:r,entries:o}}async function Fe(e,t){return(await UO(e,t)).entries}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3c2c29c0-0034-54d4-9dbd-2e9af047784e")}catch{}})();var X$=1,HO=["docs_add","files_add","history:author-acknowledge","history_author_acknowledge","history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","normalize","release","test_run_track","tests_add","tests_remove","tests_update","update_audit","update_ownership_bypass"],qO=["append","cancel","claim","close","comment_add","create","learning_add","note_add","reopen"],VO=new Set(HO),BO=new Set(qO),WO=new Set(["actual_result","affected_version","assignee","blocked_by","blocked_reason","close_reason","confidence","customer_impact","definition_of_ready","dependencies","docs","environment","expected_result","files","fixed_version","goal","impact","learnings","notes","objective","order","outcome","parent","release","reminders","reporter","repro_steps","resolution","reviewer","severity","sprint","tests","test_runs","unblock_note","updated_at","value","why_now"]);function GO(e){let t=e.path.split("/").filter(Boolean);return t[0]==="metadata"||t[0]==="front_matter"?t[1]:t[0]==="body"?"body":void 0}function Sr(e){return e.event_class==="substantive"||e.event_class==="maintenance"?e.event_class:VO.has(e.op)?"maintenance":BO.has(e.op)||e.op!=="update"?"substantive":Array.isArray(e.patch)&&e.patch.length>0&&e.patch.every(t=>{let r=GO(t);return r!==void 0&&WO.has(r)})?"maintenance":"substantive"}import jp from"fast-json-patch";import Dp from"node:fs/promises";import wA from"node:path";import j from"node:fs/promises";import B from"node:path";import{randomUUID as hc}from"node:crypto";import{createRequire as KO}from"node:module";import{setImmediate as up}from"node:timers/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="812b558d-59f3-58d6-b04e-6a4f8689e866")}catch{}})();function dp(e){let t=process.emitWarning;process.emitWarning=(r,...n)=>{r==="SQLite is an experimental feature and might change at any time"&&n[0]==="ExperimentalWarning"||Reflect.apply(t,process,[r,...n])};try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}finally{process.emitWarning=t}}function lp(e,t){let r=Number.parseInt(e,10);return Number.isFinite(r)&&r>=22?dp(t):null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f0373f8f-7396-57df-9c8d-9a3315168b5a")}catch{}})();var YO="history-event-index.sqlite",gc="6",XO=8,gp="history-event-index",JO="history-event-index:append:",ZO=5e3,bc=300,bp=3e4,QO="history-event-index-invalidation",eA="history-event-index-invalidations",tA=bc*2*1e3,st=Symbol("history-index-changed"),Pt=new Map;function $t(e){return B.join(e,"runtime",YO)}function wp(e){return B.join(e,"runtime","history-event-index-repair-deferred")}async function vp(e){try{let t=Number(await j.readFile(wp(e),"utf8")),r=Date.now()-t;return r>=0&&r<ZO}catch{return!1}}async function fp(e){try{await j.writeFile(wp(e),`${Date.now()}
|
|
47
|
-
`)}catch{}}function In(e){return B.join(e,"runtime",eA)}async function fi(e){let t=await j.readdir(In(e)).catch(r=>{if(me(r))return[];throw r});return{pending:t.filter(r=>r.endsWith(".pending")).sort(),committed:t.filter(r=>r.endsWith(".committed")).sort()}}async function mp(e){let t=await fi(e);return{pending:(await Promise.all(t.pending.map(async r=>{let n=/^(\d+)-(unknown|\d+)-(\d+)-.+\.pending$/u.exec(r);if(n!==null){let o=n[2];if(await hn({pid:Number(n[1]),...o==="unknown"?{}:{process_start_identity:o}},Math.max(0,Date.now()-Number(n[3])),tA))return r}return await j.rm(B.join(In(e),r),{force:!0}),null}))).filter(r=>r!==null),committed:t.committed}}async function _c(e,t,r=bp){let n=await le(e,QO,bc,`history-event-index-invalidation:${process.pid}`,!1,!1,r,r===0?{maxWaitMs:0}:void 0);try{return await t()}finally{await n()}}async function rA(e){let t=In(e);await j.mkdir(t,{recursive:!0});let r=hc(),n=await yn(),o=B.join(t,`${n.pid}-${n.process_start_identity??"unknown"}-${Date.now()}-${r}.pending`);return await j.writeFile(o,`pending
|
|
48
|
-
`,{flag:"wx"}),{pendingPath:o,committedPath:B.join(t,`${r}.committed`)}}function nA(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}async function mi(e){try{await j.rm($t(e),{force:!0})}catch{}}async function mc(e,t){let r=In(e);await j.mkdir(r,{recursive:!0}),await j.writeFile(B.join(r,`${hc()}${t?".contended":""}.committed`),`committed
|
|
49
|
-
`,{flag:"wx"}),t||await mi(e)}function pi(e){return e.committed.some(t=>t.endsWith(".contended.committed"))}function yc(e,t){let r;try{return r=new t($t(e)),r.exec("PRAGMA busy_timeout = 0"),r.exec("BEGIN EXCLUSIVE"),!1}catch(n){return Mt(n)}finally{r?.close()}}async function pp(e,t){return t.pending.length>0||await Of(e,gp,JO)}async function Ep(e,t,r=bp,n="rebuild"){let o=await le(e,gp,bc,`history-event-index:${n}:${process.pid}`,!1,!1,r,r===0?{maxWaitMs:0}:void 0);try{return await t()}finally{await o()}}async function kp(e){let t=B.join(e,"history"),r=await j.readdir(t,{withFileTypes:!0}).catch(s=>{if(typeof s=="object"&&s!==null&&"code"in s&&s.code==="ENOENT")return[];throw s}),n=Pt.get(e)??{streams:new Map,ordered_events:[]},o=new Set,i=!Pt.has(e);for(let s of r.filter(a=>a.isFile()&&a.name.endsWith(".jsonl")).sort((a,c)=>a.name.localeCompare(c.name))){let a=s.name.slice(0,-6);o.add(a);let c=B.join(t,s.name),d=await j.stat(c,{bigint:!0}),l=[d.dev,d.ino,d.size,d.mtimeNs,d.ctimeNs].join(":");if(n.streams.get(a)?.signature===l)continue;let u=await Sp(c,a);n.streams.set(a,{signature:l,byte_size:Number(d.size),events:u.map((f,m)=>({stream_id:a,stream_offset:m,entry:f}))}),i=!0}for(let s of n.streams.keys())o.has(s)||(n.streams.delete(s),i=!0);if(i&&(n.ordered_events=[...n.streams.values()].flatMap(s=>s.events).sort(wc)),Pt.delete(e),Pt.set(e,n),Pt.size>XO){let s=Pt.keys().next().value;Pt.delete(s)}return{events:n.ordered_events,stream_byte_sizes:new Map([...n.streams].map(([s,a])=>[s,a.byte_size]))}}async function Sp(e,t){let r=await Fe(e,t);for(let[n,o]of r.entries())if(typeof o.ts!="string"||!ur(o.ts.trim()))throw new g(`History for ${t} contains an invalid or sub-millisecond timestamp at line ${n+1}. Repair or restore the history stream and retry.`,h.GENERIC_FAILURE,{code:"history_timestamp_invalid"});return r.map(n=>({...n,ts:new Date(n.ts.trim()).toISOString()}))}async function oA(e){return(await kp(e)).events}var pc;function yi(){return pc!==void 0||(pc=lp(process.versions.node,KO(import.meta.url))),pc}function iA(e){e.exec(`
|
|
50
|
-
PRAGMA journal_mode = OFF;
|
|
51
|
-
PRAGMA synchronous = OFF;
|
|
52
|
-
CREATE TABLE metadata (
|
|
53
|
-
key TEXT PRIMARY KEY,
|
|
54
|
-
value TEXT NOT NULL
|
|
55
|
-
) STRICT;
|
|
56
|
-
CREATE TABLE events (
|
|
57
|
-
stream_id TEXT NOT NULL,
|
|
58
|
-
stream_offset INTEGER NOT NULL,
|
|
59
|
-
ts TEXT NOT NULL,
|
|
60
|
-
author TEXT NOT NULL,
|
|
61
|
-
agent_harness TEXT,
|
|
62
|
-
agent_instance TEXT,
|
|
63
|
-
op TEXT NOT NULL,
|
|
64
|
-
event_class TEXT NOT NULL CHECK(event_class IN ('substantive', 'maintenance')),
|
|
65
|
-
entry_json TEXT NOT NULL,
|
|
66
|
-
PRIMARY KEY(stream_id, stream_offset)
|
|
67
|
-
) STRICT;
|
|
68
|
-
CREATE TABLE streams (
|
|
69
|
-
stream_id TEXT PRIMARY KEY,
|
|
70
|
-
byte_size INTEGER NOT NULL CHECK(byte_size >= 0)
|
|
71
|
-
) STRICT;
|
|
72
|
-
CREATE INDEX events_order
|
|
73
|
-
ON events(ts, stream_id, stream_offset);
|
|
74
|
-
CREATE INDEX events_op_order
|
|
75
|
-
ON events(op, ts, stream_id, stream_offset);
|
|
76
|
-
CREATE INDEX events_class_stream_order
|
|
77
|
-
ON events(event_class, stream_id, ts, stream_offset);
|
|
78
|
-
CREATE INDEX events_author_order
|
|
79
|
-
ON events(author, ts, stream_id, stream_offset);
|
|
80
|
-
CREATE INDEX events_harness_order
|
|
81
|
-
ON events(agent_harness, ts, stream_id, stream_offset);
|
|
82
|
-
CREATE INDEX events_instance_order
|
|
83
|
-
ON events(agent_instance, ts, stream_id, stream_offset);
|
|
84
|
-
`),e.prepare("INSERT INTO metadata(key, value) VALUES ('version', ?)").run(gc)}function Op(e,t){let r={...t.entry,ts:new Date(t.entry.ts.trim()).toISOString()};e.prepare(`INSERT INTO events(
|
|
85
|
-
stream_id, stream_offset, ts, author, agent_harness,
|
|
86
|
-
agent_instance, op, event_class, entry_json
|
|
87
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(t.stream_id,t.stream_offset,r.ts,r.author,r.agent_harness??null,r.agent_instance??null,r.op,Sr(r),JSON.stringify(r))}function Ap(e){let t=JSON.parse(String(e.entry_json));return typeof t.ts!="string"||!ur(t.ts.trim())?null:{stream_id:String(e.stream_id),stream_offset:Number(e.stream_offset),entry:{...t,ts:new Date(t.ts.trim()).toISOString()}}}function Ip(e,t,r){e.prepare(`INSERT INTO streams(stream_id, byte_size) VALUES (?, ?)
|
|
88
|
-
ON CONFLICT(stream_id) DO UPDATE SET byte_size = excluded.byte_size`).run(t,r)}async function sA(e,t={}){let r=yi();return r?Ep(e,async()=>{let n;try{n=await _c(e,()=>mp(e),t.lockWaitMs)}catch(a){if(a instanceof g&&a.code==="lock_conflict")return!1;throw a}if(n.pending.length>0||pi(n)&&yc(e,r))return!1;let o=$t(e);await j.mkdir(B.dirname(o),{recursive:!0});let i=`${o}.${hc()}.tmp`,s;try{s=new r(i),iA(s),s.exec("BEGIN IMMEDIATE");let a=await kp(e);await aA(s,a),s.exec("COMMIT"),s.close(),s=void 0;let c=await _c(e,async()=>{let d=await mp(e);return d.pending.length>0||!nA(n.committed,d.committed)||pi(d)&&yc(e,r)?!1:(await j.rm(o,{force:!0}),await j.rename(i,o),!0)},t.lockWaitMs);return c&&await Promise.all(n.committed.map(d=>j.rm(B.join(In(e),d),{force:!0}))),c||(await fp(e),await j.rm(i,{force:!0})),c}catch(a){throw await fp(e),s?.close(),await j.rm(i,{force:!0}),a}},t.lockWaitMs):!1}async function aA(e,t){let r=0;for(let n of t.events)Op(e,n),++r%500===0&&await up();for(let[n,o]of t.stream_byte_sizes)Ip(e,n,o),++r%500===0&&await up()}function li(e,t){return!t||t.length===0||t.includes(e)}function wc(e,t){return e.entry.ts.localeCompare(t.entry.ts)||e.stream_id.localeCompare(t.stream_id)||e.stream_offset-t.stream_offset}function _i(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():e}function cA(e,t){if(t.after_ts!==void 0&&t.after_stream_id!==void 0&&t.after_stream_offset!==void 0){if(wc(e,{stream_id:t.after_stream_id,stream_offset:t.after_stream_offset,entry:{...e.entry,ts:_i(t.after_ts)}})<=0)return!1}else if(t.since_ts!==void 0&&e.entry.ts<_i(t.since_ts))return!1;return!0}function dA(e,t){return!t.harnesses||t.harnesses.length===0||t.harnesses.includes(e.entry.agent_harness??"")?!0:e.entry.agent_harness===void 0&&(t.harness_alias_authors??[]).includes(e.entry.author)}function lA(e,t){return!cA(e,t)||!li(e.entry.op,t.ops)||!li(e.entry.author,t.authors)||!li(e.entry.agent_instance??"",t.agent_instances)||!li(e.stream_id,t.stream_ids)||!dA(e,t)?!1:(t.provenance??[]).every(r=>{let n=e.entry.agent_provenance?.[r.dimension]?.value;return n!==void 0&&r.values.includes(n)})}async function fj(e,t){let r=Math.max(0,Math.floor(t.limit)),n=(await oA(e)).filter(o=>lA(o,t)).slice(0,r+1);return{events:n.slice(0,t.limit),has_more:n.length>t.limit}}async function uA(e,t){let r=e.prepare("SELECT byte_size FROM streams WHERE stream_id = ?").get(B.basename(t,".jsonl")),n=0;try{n=(await j.stat(t)).size}catch(o){if(!me(o))throw o}return Number(r?.byte_size??0)===n}async function Tp(e,t,r){let n=B.dirname(B.dirname(e)),o=yi(),i=!1,s=async()=>{await r(),i=!0};if(!o){await _p(n,s);return}try{await Ep(n,async()=>{let a=$t(n);try{await j.access(a)}catch{await s();return}let c;try{if(c=new o(a),c.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==gc)throw new TypeError("Unsupported history event index version");if(!await uA(c,e))throw new TypeError("Stale history event index append base")}catch(l){if(c?.close(),Mt(l))throw l;await mc(n,!0),await s();return}try{c.exec("PRAGMA busy_timeout = 0"),c.exec("BEGIN IMMEDIATE")}catch(l){if(c.close(),Mt(l)||!(l instanceof Error)||l.code!=="ERR_SQLITE_ERROR")throw l;await mc(n,!1),await s();return}let d=!1;try{await s(),d=!0;let l=B.basename(e,".jsonl"),u=c.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(l);Op(c,{stream_id:l,stream_offset:Number(u.value),entry:t}),Ip(c,l,(await j.stat(e)).size),c.exec("COMMIT"),c.close()}catch(l){if(c?.close(),!d)throw l;await mc(n,Mt(l))}},0,"append")}catch(a){if(i){await mi(n);return}if(!mA(a))throw a;await _p(n,s,Mt(a))}}async function _p(e,t,r=!1){let n=!1,o;try{await _c(e,async()=>{let i=r||pi(await fi(e)),s=await rA(e);o=s.pendingPath;try{await t(),n=!0}catch(a){throw await j.rm(s.pendingPath,{force:!0}),a}await j.rename(s.pendingPath,i?s.committedPath.replace(/\.committed$/u,".contended.committed"):s.committedPath),i||await mi(e)})}catch(i){if(n){await mi(e);try{await j.rm(o,{force:!0})}catch{}return}throw i}}async function vc(e){await j.rm($t(B.dirname(B.dirname(e))),{force:!0})}function ui(e,t,r,n){!n||n.length===0||(e.push(`${r} IN (${n.map(()=>"?").join(", ")})`),t.push(...n))}function fA(e,t,r,n){if(!r||r.length===0)return;let o=r.map(()=>"?").join(", "),i=n??[];if(i.length>0){e.push(`(agent_harness IN (${o}) OR (agent_harness IS NULL AND author IN (${i.map(()=>"?").join(", ")})))`),t.push(...r,...i);return}e.push(`agent_harness IN (${o})`),t.push(...r)}async function Cp(e,t,r,n){let o;try{let i=await fi(e);if(await pp(e,i))return st;let s=await yp(e);if(i.committed.length>0)return pi(i)&&yc(e,t)?st:null;if(o=new t($t(e),{readOnly:!0}),o.exec("BEGIN"),o.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==gc)return null;let a=n(o);if(a===null)return null;let c=pA(o,r),d=o;o=void 0,d.close();let l=await hA([...c.keys()],e,r),u=await yA(c,e,l),f=await fi(e);return f.committed.length>0||await pp(e,f)||s!==await yp(e)?st:u?a:null}catch(i){return Mt(i)?st:null}finally{o?.close()}}function Mt(e){return typeof e=="object"&&e!==null&&"errcode"in e&&[5,6].includes(e.errcode)}function mA(e){return Mt(e)||e instanceof g&&e.code==="lock_conflict"}function pA(e,t){let r=new Map,n=t&&t.length>0?[...new Set(t)]:void 0;if(n===void 0)for(let o of e.prepare("SELECT stream_id, byte_size FROM streams").all())r.set(String(o.stream_id),Number(o.byte_size));else for(let o=0;o<n.length;o+=500){let i=n.slice(o,o+500);for(let s of e.prepare(`SELECT stream_id, byte_size FROM streams WHERE stream_id IN (${i.map(()=>"?").join(", ")})`).all(...i))r.set(String(s.stream_id),Number(s.byte_size))}return r}async function yp(e){let t=await j.stat($t(e),{bigint:!0});return[t.dev,t.ino,t.size,t.mtimeNs,t.ctimeNs].join(":")}async function mj(e,t){let r=yi();if(!r)return{result:null,repair_needed:!1};let n=[],o=[];if(t.after_ts!==void 0&&t.after_stream_id!==void 0&&t.after_stream_offset!==void 0){n.push("(ts > ? OR (ts = ? AND stream_id > ?) OR (ts = ? AND stream_id = ? AND stream_offset > ?))");let a=_i(t.after_ts);o.push(a,a,t.after_stream_id,a,t.after_stream_id,t.after_stream_offset)}else t.since_ts!==void 0&&(n.push("ts >= ?"),o.push(_i(t.since_ts)));ui(n,o,"op",t.ops),ui(n,o,"author",t.authors),fA(n,o,t.harnesses,t.harness_alias_authors),ui(n,o,"agent_instance",t.agent_instances);for(let a of t.provenance??[])n.push(`json_extract(entry_json, '$.agent_provenance.${a.dimension}.value') IN (${a.values.map(()=>"?").join(", ")})`),o.push(...a.values);ui(n,o,"stream_id",t.stream_ids);let i=n.length===0?"":` WHERE ${n.join(" AND ")}`,s=await Cp(e,r,t.stream_ids,a=>{let c=a.prepare(`SELECT stream_id, stream_offset, entry_json
|
|
89
|
-
FROM events${i}
|
|
90
|
-
ORDER BY ts, stream_id, stream_offset
|
|
91
|
-
LIMIT ?`).all(...o,Math.max(0,Math.floor(t.limit))+1),d=c.slice(0,t.limit).map(Ap);return d.includes(null)?null:{events:d,has_more:c.length>t.limit}});return{result:s===st?null:s,repair_needed:s===null&&!await vp(e)}}function Rp(e,t){let r=Object.create(null);for(let n of e){if(!t.has(n.stream_id)||Sr(n.entry)!=="substantive")continue;let o=r[n.stream_id];(o===void 0||wc(o,n)<0)&&(r[n.stream_id]=n)}return r}async function _A(e,t){if(B.basename(t)!==t)return null;try{return(await j.stat(B.join(e,"history",`${t}.jsonl`))).size}catch(r){if(me(r))return 0;throw r}}async function yA(e,t,r){for(let n=0;n<r.length;n+=500){let o=r.slice(n,n+500),i=await Promise.all(o.map(s=>_A(t,s)));for(let[s,a]of i.entries()){if(a===null)return!1;let c=o[s],d=e.get(c);if(!(a===0&&d===void 0)&&a!==d)return!1}}return!0}async function hA(e,t,r){if(r&&r.length>0)return[...new Set(r.filter(o=>o.trim().length>0))];let n=await j.readdir(B.join(t,"history"),{withFileTypes:!0}).then(o=>o.filter(i=>i.isFile()&&i.name.endsWith(".jsonl")).map(i=>i.name.slice(0,-6))).catch(o=>{if(me(o))return[];throw o});return[...new Set([...e,...n])]}async function hp(e,t,r,n){return e?Cp(t,e,r,o=>{let i=[];for(let s=0;s<r.length;s+=500){let a=r.slice(s,s+500),c=o.prepare(`SELECT stream_id, stream_offset, entry_json
|
|
92
|
-
FROM (
|
|
93
|
-
SELECT stream_id, stream_offset, entry_json,
|
|
94
|
-
ROW_NUMBER() OVER (
|
|
95
|
-
PARTITION BY stream_id
|
|
96
|
-
ORDER BY ts DESC, stream_offset DESC
|
|
97
|
-
) AS recency_rank
|
|
98
|
-
FROM events
|
|
99
|
-
WHERE event_class = 'substantive'
|
|
100
|
-
AND stream_id IN (${a.map(()=>"?").join(", ")})
|
|
101
|
-
)
|
|
102
|
-
WHERE recency_rank = 1`).all(...a).map(Ap);if(c.includes(null))return null;i.push(...c)}return Rp(i,n)}):null}async function pj(e,t){let r=[...new Set(t.filter(a=>a.trim().length>0&&B.basename(a)===a))];if(r.length===0)return{};let n=new Set(r),o=yi(),i=await hp(o,e,r,n);if(i!==null&&i!==st)return i;if(o&&i!==st&&!await vp(e))try{if(await sA(e,{lockWaitMs:0})){let a=await hp(o,e,r,n);if(a!==null&&a!==st)return a}}catch{}let s=[];return await Promise.all(r.map(async a=>{let c=B.join(e,"history",`${a}.jsonl`);(await Sp(c,a).catch(d=>{if(d instanceof g&&d.code==="history_timestamp_invalid")return[];throw d})).forEach((d,l)=>{s.push({stream_id:a,stream_offset:l,entry:d})})})),Rp(s,n)}import Ec from"node:fs/promises";import Or from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="687cbe24-6d5c-5322-962d-455048eb84b5")}catch{}})();var gA=Or.join("runtime","history-drift-cache.json"),xp={EINVAL:"invalid_cache_path",EISDIR:"cache_path_is_directory",ENOENT:"invalid_cache_path",ENOTDIR:"invalid_cache_path",ERR_FS_EISDIR:"cache_path_is_directory"};function Np(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}async function bA(e){let t=Or.join(e,gA),r=!1,n="invalid_cache_path";try{r=(await Ec.stat(await Ec.realpath(e))).isDirectory()}catch(o){let i=Np(o);n=i===void 0?"unknown":xp[i]??"filesystem_error"}if(!r){bn(`[pm] warning: history_drift_cache_invalidation_failed:${n}
|
|
103
|
-
`);return}try{await Ec.rm(t,{force:!0})}catch(o){let i=Np(o);if(me(o))return;let s=i===void 0?"unknown":xp[i]??"filesystem_error";bn(`[pm] warning: history_drift_cache_invalidation_failed:${s}
|
|
104
|
-
`)}}async function hi(e){let t=Or.dirname(Or.resolve(e));Or.basename(t)==="history"&&await bA(Or.dirname(t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4a3c3c82-0398-549c-8910-fdc69d971cb2")}catch{}})();var vA={front_matter:{},body:""},jt=3,Tn=[1,2,3],EA=1,kA=[1];function Lp(e){return tt(R(e),e.hash_algorithm)}function Ar(e){return ro(R(e))}function Lj(e){return ro(R(e))}function Ac(e){let t={...e,record_hash_version:EA},{record_hash:r,...n}=t;return{...t,record_hash:Lp(n)}}function wi(e){try{Tt(e.hash_algorithm)}catch{return{ok:!1,error:"unsupported_history_hash_algorithm"}}if(e.record_hash_version===void 0&&e.record_hash===void 0)return{ok:!0,coverage:"item_state_only"};if(e.record_hash_version===void 0||e.record_hash===void 0)return{ok:!1,error:"incomplete_record_hash_envelope"};if(!kA.includes(e.record_hash_version))return{ok:!1,error:"unsupported_record_hash_version"};let{record_hash:t,...r}=e;return Lp(r)===e.record_hash?{ok:!0,coverage:"record_and_item_state"}:{ok:!1,error:"record_hash_mismatch"}}function SA(e,t){let r={before_hash:e.before_hash,after_hash:e.after_hash,patch_hash:Ar(e.patch)};return e.hash_algorithm!==void 0&&(r.hash_algorithm=e.hash_algorithm),e.item_hash_version!==void 0&&(r.item_hash_version=e.item_hash_version),t.retainOriginalPatch&&(r.patch=structuredClone(e.patch)),t.retainPriorRecordHash!==!1&&e.record_hash_version!==void 0&&e.record_hash!==void 0&&(r.record_hash_version=e.record_hash_version,r.record_hash=e.record_hash,r.record=structuredClone(e)),r}function Fp(e,t,r={}){let n=wi(e);if(!n.ok)throw new TypeError(n.error);let o=Ar(e.patch),i=r.retainPriorRecord===!0||e.before_hash!==t.before_hash||e.after_hash!==t.after_hash||e.item_hash_version!==t.item_hash_version||e.hash_algorithm!==t.hash_algorithm||o!==Ar(t.patch),s=Ac({...t,...i?{reanchor_evidence:[...t.reanchor_evidence??[],SA(e,r)]}:{}}),a=Ic(s);if(!a.ok)throw new TypeError(a.error);return s}function zp(e){return!Array.isArray(e)||Object.keys(e).length!==e.length?!1:e.every(t=>!Lt(t)||typeof t.path!="string"?!1:t.op==="move"||t.op==="copy"?typeof t.from=="string":["add","replace","test"].includes(t.op)?Object.hasOwn(t,"value"):t.op==="remove")}function OA(e){return Lt(e)&&typeof e.ts=="string"&&typeof e.author=="string"&&typeof e.op=="string"&&typeof e.before_hash=="string"&&typeof e.after_hash=="string"&&zp(e.patch)}function AA(e){let t=e.record_hash_version!==void 0,r=e.record_hash!==void 0;return t===r}function IA(e){return!Lt(e)||!AA(e)||typeof e.before_hash!="string"||typeof e.after_hash!="string"||typeof e.patch_hash!="string"||!/^[a-f0-9]{64}$/u.test(e.patch_hash)||e.patch!==void 0&&!zp(e.patch)||e.record_hash_version!==void 0&&typeof e.record_hash_version!="number"||e.record_hash!==void 0&&(typeof e.record_hash!="string"||!/^(?:[a-f0-9]{64}|[a-f0-9]{128})$/u.test(e.record_hash))?!1:e.record===void 0||OA(e.record)}function TA(e){try{for(let t of e){if(!IA(t))return!1;Tt(t.hash_algorithm)}return!0}catch{return!1}}function CA(e){let t=e.record;return t!==void 0&&t.before_hash===e.before_hash&&t.after_hash===e.after_hash&&t.item_hash_version===e.item_hash_version&&t.hash_algorithm===e.hash_algorithm&&t.record_hash_version===e.record_hash_version&&t.record_hash===e.record_hash&&Ar(t.patch)===e.patch_hash}function RA(e,t,r){if(t.patch&&Ar(t.patch)!==t.patch_hash)return{kind:"patch_hash_mismatch"};if(t.record)return CA(t)?{kind:"record",entry:t.record}:{kind:"record_hash_mismatch"};let n=t.patch??e.patch;if(Ar(n)!==t.patch_hash)return{kind:"digest_only"};let o={...e,before_hash:t.before_hash,after_hash:t.after_hash,patch:n,hash_algorithm:t.hash_algorithm,...t.item_hash_version===void 0?{}:{item_hash_version:t.item_hash_version},...t.record_hash_version===void 0?{}:{record_hash_version:t.record_hash_version},...t.record_hash===void 0?{}:{record_hash:t.record_hash},...r.length===0?{}:{reanchor_evidence:r}};return t.hash_algorithm===void 0&&delete o.hash_algorithm,r.length===0&&delete o.reanchor_evidence,t.item_hash_version===void 0&&delete o.item_hash_version,t.record_hash_version===void 0||t.record_hash===void 0?{kind:"legacy",entry:o}:{kind:"record",entry:o}}function Ic(e){let t=e.reanchor_evidence;if(t===void 0)return{ok:!0,coverage:"none"};if(!Array.isArray(t)||!TA(t))return{ok:!1,error:"rewrite_evidence_invalid"};if(t.length===0)return{ok:!0,coverage:"none"};let r=e;for(let n=t.length-1;n>=0;n-=1){let o=t[n],i=RA(r,o,t.slice(0,n));if(i.kind==="patch_hash_mismatch")return{ok:!1,error:"rewrite_evidence_patch_hash_mismatch"};if(i.kind==="record_hash_mismatch")return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};if(i.kind==="digest_only")return{ok:!0,coverage:"digest_only"};if(i.kind==="legacy")return{ok:!0,coverage:"legacy_anchor_only"};if(!wi(i.entry).ok)return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};r=i.entry}return{ok:!0,coverage:"complete"}}function gi(e,t){return(e??"").localeCompare(t??"")}function Pp(e,t){return(e??0)-(t??0)}function at(e,t,r){return JSON.stringify(e??r).localeCompare(JSON.stringify(t??r))}function xA(e,t){return[e.scope.localeCompare(t.scope),gi(e.path,t.path),gi(e.command,t.command),Pp(e.timeout_seconds,t.timeout_seconds),gi(e.pm_context_mode,t.pm_context_mode),+!!e.shared_host_safe-+!!t.shared_host_safe,at(e.env_clear,t.env_clear,[]),at(e.env_set,t.env_set,{}),at(e.assert_stdout_contains,t.assert_stdout_contains,[]),at(e.assert_stdout_regex,t.assert_stdout_regex,[]),at(e.assert_stderr_contains,t.assert_stderr_contains,[]),at(e.assert_stderr_regex,t.assert_stderr_regex,[]),Pp(e.assert_stdout_min_lines,t.assert_stdout_min_lines),at(e.assert_json_field_equals,t.assert_json_field_equals,{}),at(e.assert_json_field_gte,t.assert_json_field_gte,{}),gi(e.note,t.note)].find(r=>r!==0)??0}function NA(e){return!e||e==="/"?[]:e.startsWith("/")?e.slice(1).split("/").map(t=>t.replaceAll("~1","/").replaceAll("~0","~")):[]}function DA(e,t){let r=NA(t);if(r.length===0)return!0;let n=e;for(let o of r){let i=/^(0|[1-9]\d*)$/.test(o)?Number(o):-1,s=Array.isArray(n)?i>=0&&i<n.length?n[i]:void 0:Lt(n)&&Object.prototype.hasOwnProperty.call(n,o)?n[o]:void 0;if(s===void 0)return!1;n=s}return!0}function PA(e,t){let r=[],n=structuredClone(e);for(let o of t){let i=o.op==="replace"&&!DA(n,o.path)?{...o,op:"add"}:o;r.push(i),n=jp.applyPatch(n,[i],!0,!0).newDocument}return r}function bi(e,t,r=!1){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{front_matter:{},body:e.body??""};let n=vr(e),o=t===1||t===2&&r?{...n.metadata,...n.metadata.dependencies===void 0?{}:{dependencies:n.metadata.dependencies.map(s=>({...s,id:s.id.toLowerCase()}))},...n.metadata.tests===void 0?{}:{tests:n.metadata.tests.map(({workspace_context_mode:s,provenance:a,provenance_invalid:c,...d})=>d)},...n.metadata.test_runs===void 0?{}:{test_runs:n.metadata.test_runs.map(({executions:s,...a})=>a)}}:n.metadata,i=t===1&&o.tests?{...o,tests:[...o.tests].sort(xA)}:o;return{front_matter:A(i,Ee),body:n.body}}function Mp(e){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{metadata:{},body:e.body??""};let t=vr(e);return{metadata:A(t.metadata,Ee),body:t.body}}function Fj(e){return Up(e,jt)}function Up(e,t,r){if(!Tn.some(n=>n===t))throw new TypeError(`unsupported_item_hash_version:${String(t)}`);return tt(R(bi(e,t)),r)}function Hp(e,t,r){let n=Up(e,t,r);return t===2?[n,tt(R(bi(e,t,!0)),r)]:[n]}function zj(){return ro(R(vA))}function Cn(e){let t=dm(e.op),r=bi(e.before,jt),n=bi(e.after,jt),o=Mp(e.before),i=Mp(e.after),s=jp.compare(o,i),a=PA(o,s),c=ap(e.author),d=c.harness?Object.fromEntries(Object.entries(ip().provenance_outcomes).filter(([m,_])=>_.resolver!==void 0&&(_.status!=="resolved"||c.provenance?.[m]?.source==="probe"))):void 0,l=d===void 0||Object.keys(d).length===0?e.context:{...e.context,agent_provenance_outcomes:d},u=e.hashAlgorithm??lm,f={hash_algorithm:u,ts:e.nowIso,author:e.author,author_source:e.authorSource??sp(e.author),...c.harness?{agent_harness:c.harness}:{},...c.model?{agent_model:c.model}:{},...c.model_source?{agent_model_source:c.model_source}:{},...c.instance?{agent_instance:c.instance}:{},...c.provenance?{agent_provenance:c.provenance}:{},...c.episode?{agent_episode:c.episode}:{},op:t,patch:a,before_hash:tt(R(r),u),after_hash:tt(R(n),u),item_hash_version:jt,message:e.message===void 0?void 0:e.message,...l===void 0?{}:{context:l}};return Ac({...f,event_class:Sr(f)})}function Lt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kc(e){return new g(e,h.GENERIC_FAILURE,{code:"history_timestamp_invalid"})}function qp(e){let t=e.ts.trim();if(t.length===0)return Ie();if(!ur(t))throw kc("History timestamp must be a valid RFC 3339 date-time with millisecond precision");if(t!==e.ts)throw kc("History timestamp must not contain surrounding whitespace");return e.ts}function $p(e,t){let r=e.ts;if(typeof r=="string"&&r.trim().length>0){if(!ur(r))throw kc("History timestamp must be a valid RFC 3339 date-time with millisecond precision");return e}return{...e,ts:t}}function Sc(e,t){let r=qp(t);if(typeof e=="string"){let n;try{n=JSON.parse(e)}catch{return e}return Lt(n)?JSON.stringify($p(n,r)):e}return Lt(e)?JSON.stringify($p(e,r)):JSON.stringify(e)}async function MA(e,t,r){if(r===!1)return!0;if(typeof r=="string"){let s=Sc(r,t);return await Oc(e,s),await hi(e),await vc(e),!0}if(typeof r!="object"||r===null)return!1;let n=r;if(n.skip===!0)return!0;let o=typeof n.history_path=="string"?n.history_path:e,i=Sc(typeof n.line=="string"?n.line:n.entry??t,t);return await Oc(o,i),await hi(o),await vc(o),!0}async function Oc(e,t){let r;try{r=JSON.parse(t)}catch{r=null}if(!Lt(r)||r.op!=="create"){await rd(e,t);return}await Dp.mkdir(wA.dirname(e),{recursive:!0});try{await Dp.writeFile(e,`${t}
|
|
105
|
-
`,{encoding:"utf8",flag:"wx"})}catch(n){throw n.code!=="EEXIST"?n:new g("This item identity is reserved by an existing history stream.",h.CONFLICT,{code:"item_identity_reserved",required:"Choose a new item ID or restore the original item from its history.",nextSteps:["Run pm history <id> --full, then pm restore <id> <version> to recover the original item."]})}}async function Rn(e,t){let r=await or("history_append",{history_path:e,entry:t});if(r.handled&&await MA(e,t,r.result))return;let n=t.ts.trim().length>0?t:{...t,ts:qp(t)},o=Ac({...n,hash_algorithm:Tt(n.hash_algorithm),event_class:Sr(n)});await Tp(e,o,async()=>{await Oc(e,Sc(o,o))}),await hi(e)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3bfeb8d2-52c2-587a-9611-c4d5817cb47e")}catch{}})();function Vp(e){let t=[],r=e[0]?.op==="history_compact_baseline",n=r?1:void 0,o=!1;for(let[i,s]of e.entries())s.op==="delete"&&(o=!0),s.op==="create"&&(n!==void 0&&t.push({prior_genesis_index:n,repeated_create_index:i+1,sequence:o?"delete_then_create":r?"checkpoint_then_create":"multiple_creates"}),n??=i+1,o=!1);return t}import Cc from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c0cb8c7-4d7d-53f8-8ec2-d6dc98fc6dc5")}catch{}})();var $A={metadata:{},body:""};function vi(){return structuredClone($A)}function Jj(e,t=jt,r){return Tc(e,t,r)[0]}function Tc(e,t,r){if(Object.keys(e.metadata).length===0||Array.isArray(e.metadata.tags))try{return Hp(Ei(e),t,r)}catch{}let n=tt(R({replay_fallback:!0,metadata:e.metadata,body:e.body}),r);return t===2?[n,n]:[n]}function Gp(e,t,r,n,o){let i=Tt(n.hash_algorithm),s=`${r}:${i}`,a=o?.before.get(s)??Tc(e,r,i),c=Tc(t,r,i);return o?.after.set(s,c),{beforeHashes:a,afterHashes:c,pairIndex:a.findIndex((d,l)=>d===n.before_hash&&c[l]===n.after_hash),beforeIndex:a.indexOf(n.before_hash),afterIndex:c.indexOf(n.after_hash)}}function Ei(e){return{metadata:e.metadata,body:e.body}}function Zj(e,t={}){return vr(Ei(e),t)}function Qj(e){if(!e.metadata||Object.keys(e.metadata).length===0)return{metadata:{},body:e.body??""};let t=vr(e);return{metadata:A(t.metadata,Ee),body:t.body}}function Bp(e){return e==="/front_matter"?"/metadata":e.startsWith("/front_matter/")?`/metadata/${e.slice(14)}`:e}function jA(e){return typeof e=="object"&&e!==null&&typeof e.op=="string"&&typeof e.path=="string"}function Kp(e){return Array.isArray(e)?e.filter(jA).map(t=>({...t,path:Bp(t.path),from:typeof t.from=="string"?Bp(t.from):void 0})):[]}function LA(e){return typeof e=="object"&&e!==null&&"metadata"in e&&"body"in e&&typeof e.body=="string"&&typeof e.metadata=="object"&&e.metadata!==null}function ki(e,t){try{let r=Kp(t),n=Cc.applyPatch(structuredClone(e),r,!0,!0).newDocument;return LA(n)?{ok:!0,document:{metadata:n.metadata,body:n.body}}:{ok:!1,error:new Error("history_replay_invalid_document_shape")}}catch(r){return{ok:!1,error:r}}}function FA(e){return[...new Set(e.map(t=>t.item_hash_version).filter(t=>t!==void 0&&Tn.includes(t)))]}function Yp(e){return e!==void 0&&!Tn.includes(e)}function zA(e,t){return e!==void 0?[e]:t===void 0?[...Tn]:[t]}function Xp(e){let t=wi(e);if(!t.ok)return t.error;let r=Ic(e);return r.ok?void 0:r.error}function UA(e,t){let r=Xp(e);if(r)return{ok:!1,error:r};let n=ki(t,e.patch);return n.ok?{ok:!0,document:n.document}:{ok:!1,error:"patch_apply_failed"}}function HA(e,t){let r=Xp(e);if(r)throw new TypeError(`${r}:entry_${t+1}`)}function qA(e,t,r,n,o){let i=[];for(let s of r){let a=Gp(e,t,s,n,o);if(i.push({version:s,match:a}),a.pairIndex>=0)break}return i}function Jp(e){let t=vi(),r=new Map,n,o,i=Vp(e).map(s=>`verify_failed:duplicate_create:entry_${s.repeated_create_index}:prior_${s.prior_genesis_index}`);for(let s=0;s<e.length;s+=1){let a=e[s],c=a.item_hash_version,d=Yp(c);d&&i.push(`verify_failed:unsupported_item_hash_version:${String(c)}:entry_${s+1}`);let l=UA(a,t);if(!l.ok)return{ok:!1,errors:[...i,`verify_failed:${l.error}:entry_${s+1}`]};if(d){t=l.document,r=new Map,n=void 0,o=void 0;continue}let u=zA(c,o),f={before:r,after:new Map},m=qA(t,l.document,u,a,f),_=m.find(({match:w})=>w.pairIndex>=0);if(_===void 0){let w=m.some(({match:v})=>v.beforeIndex>=0);return{ok:!1,errors:[...i,`verify_failed:${w?"after":"before"}_hash_mismatch:entry_${s+1}`]}}let y=_.version;t=l.document,r=f.after,n=y,o=c??o}return i.length>0?{ok:!1,errors:i,...n===void 0?{}:{item_hash_version:n}}:{ok:!0,errors:[],...n===void 0?{}:{item_hash_version:n}}}function Ft(e){let t=Jp(e);return{ok:t.ok,errors:t.errors}}function Wp(e,t){try{return{ok:!0,document:Cc.applyPatch(structuredClone(e),[t],!0,!1).newDocument}}catch{return{ok:!1}}}function VA(e,t){let r=structuredClone(e),n=0,o=0;for(let s of Kp(t)){let a=Wp(r,s);if(a.ok){r=a.document;continue}if(s.op==="replace"){let c=Wp(r,{...s,op:"add"});if(c.ok){r=c.document,n+=1;continue}}o+=1}let i=r;return{document:{metadata:typeof i.metadata=="object"&&i.metadata!==null?i.metadata:{},body:typeof i.body=="string"?i.body:e.body},convertedReplaceToAdd:n,skippedOps:o}}function BA(e){let t=FA(e);if(t.length===1)return t[0];let r=Jp(e);return r.ok&&r.item_hash_version!==void 0?r.item_hash_version:t.length===0?1:jt}function WA(e,t,r=t.patch){let n=ki(e,r);if(n.ok)return{next:n.document,patch:r,repaired:R(r)!==R(t.patch),converted:0,skipped:0};let o=VA(e,r);return{next:o.document,patch:Cc.compare(e,o.document),repaired:!0,converted:o.convertedReplaceToAdd,skipped:o.skippedOps}}function GA(e,t,r){return WA(e,t,r.projectPatch?.(t,e))}function eL(e,t=BA(e),r={}){let n=e.findIndex(m=>Yp(m.item_hash_version));if(n>=0)throw new TypeError(`unsupported_item_hash_version:${String(e[n]?.item_hash_version)}:entry_${n+1}`);let o=vi(),i=[],s=[],a=0,c=0,d=0,l=0,u,f=t!==1||e.some(m=>m.item_hash_version!==void 0);for(let m=0;m<e.length;m+=1){let _=e[m];HA(_,m);let y=GA(o,_,r),{next:w,patch:v,repaired:I,converted:z,skipped:X}=y;d+=z,l+=X,c+=Number(I);let ae=Gp(o,w,t,_);u===void 0||r.continuousHashSurface!==!0?u=[ae.pairIndex,ae.beforeIndex,ae.afterIndex,Math.min(u??0,ae.beforeHashes.length-1)].find(F_=>F_>=0):u=Math.min(u,ae.beforeHashes.length-1);let Gc=ae.beforeHashes[u],Kc=ae.afterHashes[u],$i=Gc!==_.before_hash||Kc!==_.after_hash;$i&&(a+=1);let Vt={..._,patch:v,before_hash:Gc,after_hash:Kc};f?Vt.item_hash_version=t:delete Vt.item_hash_version;let L_=Vt.item_hash_version!==_.item_hash_version;($i||I||L_)&&(Vt=Fp(_,Vt,{retainOriginalPatch:I})),i.push(Vt),s.push({index:m+1,rehashed:$i,patch_repaired:I,converted_replace_to_add:z,skipped_ops:X}),o=w}return{entries:i,finalDocument:o,entriesRehashed:a,entriesPatchRepaired:c,convertedReplaceToAdd:d,skippedOps:l,details:s,itemHashVersion:t,explicitItemHashVersion:f}}function tL(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
106
|
-
`)}
|
|
107
|
-
`}import Zp from"node:fs/promises";import Ir from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="af606b47-d071-5724-b1e7-de4e1e5d7385")}catch{}})();var ct="_workspace";function zt(e){return Ir.join(e,"history",`${ct}.jsonl`)}function Rc(e,t){return{metadata:{id:ct,title:"Workspace state",description:"Audited singleton workspace document state.",type:"Chore",status:"open",priority:2,tags:["workspace-history"],created_at:t,updated_at:t,documents:e},body:""}}function Ut(e,t=e.length){let r=vi();for(let n of e.slice(0,t))r=ki(r,n.patch).document;return Ei(r)}function Tr(e){return"documents"in e.metadata&&typeof e.metadata.documents=="object"&&e.metadata.documents!==null&&!Array.isArray(e.metadata.documents)?e.metadata.documents:{}}function Cr(e){throw new g(`Workspace history verification failed: ${e.join(", ")}`,h.CONFLICT,{code:"workspace_history_chain_invalid",reason:"workspace_history_chain_verification_failed",verification_errors:[...e],required:"Repair the _workspace history chain before reading, reconciling, restoring, or appending audited singleton state.",why:"Continuing against an unverifiable append-only stream could hide or compound workspace state corruption.",examples:["pm history _workspace --verify --json","pm validate --check-history-drift --fix-hints --json"],nextSteps:["Inspect the exact verification_errors and preserve the corrupt stream as evidence.","Use the history-drift remediation returned by validate before retrying the refused operation."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify --json"}})}function Si(e,t){let r=Ir.resolve(t),n=Ir.relative(e,r).replaceAll("\\","/");if(n.length===0||n===".."||n.startsWith("../")||Ir.isAbsolute(n))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath:n,absolutePath:r}}async function pL(e){let t=await Fe(zt(e),ct),r=Ft(t);r.ok||Cr(r.errors);let n=Tr(t.length===0?Nr:Ut(t)),o=[],i=[],s=[],a=[];for(let c of Object.keys(n).sort()){let d;try{let l=Si(e,Ir.resolve(e,c));if(d=await we(l.absolutePath),d===null){s.push(c);continue}let u=JSON.parse(d);(R(u)===R(n[c])?o:i).push(c)}catch{a.push(c)}}return{ok:i.length===0&&s.length===0&&a.length===0,document_count:Object.keys(n).length,matching_documents:o,mismatched_documents:i,missing_documents:s,unreadable_documents:a}}async function Qp(e){let t=zt(e.pmRoot),r=await Fe(t,ct),n=Ft(r);n.ok||Cr(n.errors);let o=e.idempotencyKey===void 0?void 0:r.find(u=>u.op===`${e.op}:${e.idempotencyKey}`);if(o)return{entry:o,historyPath:t};let i=Ie(),s=r.length===0?Nr:Ut(r),a=Tr(s),c=a[e.documentPath];if(c!==void 0&&R(c)!==R(e.before))throw new g(`Workspace history state for "${e.documentPath}" changed outside the audited mutation path.`,h.CONFLICT,{code:"workspace_history_state_conflict",reason:"out_of_band_workspace_state",required:"Reconcile the singleton document with its matching _workspace history state before retrying the mutation.",why:"Accepting the write would make the append-only audit stream describe a state that was not actually observed.",examples:["pm history _workspace --verify","pm validate --check-history-drift --fix-hints"],nextSteps:["Review the version-control change that altered the singleton and preserve the intended document plus its matching workspace history.","Rerun the original mutation only after the on-disk singleton agrees with the latest audited workspace state."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify"}});let d=Rc({...a,[e.documentPath]:e.after},r.length===0?i:s.metadata.created_at),l=Cn({nowIso:i,author:e.author,op:e.idempotencyKey===void 0?e.op:`${e.op}:${e.idempotencyKey}`,before:s,after:d,message:e.message});return await Rn(t,l),{entry:l,historyPath:t}}async function _L(e){let t=await le(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await Qp(e)}finally{await t()}}async function yL(e){let t=await le(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let r=zt(e.pmRoot),n=await Fe(r,ct),o=Ft(n);o.ok||Cr(o.errors);let i=n.length===0?Nr:Ut(n),s=Cn({nowIso:Ie(),author:e.author,op:e.op,before:i,after:i,message:e.message,context:e.context});return await Rn(r,s),{entry:s,historyPath:r}}finally{await t()}}async function e_(e,t){if(t===e.raw)return!1;let r=t===null?null:JSON.parse(t),n=JSON.parse(e.raw);await mt(e.filePath,e.raw);try{(t!==null||e.recordCreation!==!1)&&await Qp({pmRoot:e.pmRoot,documentPath:Ir.relative(e.pmRoot,e.filePath).replaceAll("\\","/"),before:r,after:n,op:e.op,idempotencyKey:e.idempotencyKey,author:e.author,lockTtlSeconds:e.lockTtlSeconds,lockWaitMs:e.lockWaitMs,message:e.message})}catch(o){throw t===null?await Zp.rm(e.filePath,{force:!0}):await mt(e.filePath,t),o}return!0}async function t_(e){let{documentPath:t}=Si(e.pmRoot,e.filePath),r=await le(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let n=await we(e.filePath);if(e.dryRun===!0||e.idempotencyKey!==void 0){let i=await Fe(zt(e.pmRoot),ct),s=Ft(i);s.ok||Cr(s.errors);let a=Tr(i.length===0?Nr:Ut(i))[t];if(a!==void 0&&R(a)!==R(n===null?null:JSON.parse(n)))throw new g(`Workspace history state for "${t}" changed outside the audited mutation path.`,h.CONFLICT,{code:"workspace_history_state_conflict"});if(e.idempotencyKey!==void 0&&i.some(c=>c.op===`${e.op}:${e.idempotencyKey}`))return{changed:!1,result:void 0,replayed:!0}}let o=await e.mutate(n);return JSON.parse(o.raw),e.dryRun===!0?{changed:n!==o.raw,result:o.result}:{changed:await e_({...e,raw:o.raw},n),result:o.result}}finally{await r()}}async function hL(e){let t=await le(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await e_(e,await we(e.filePath))}finally{await t()}}async function gL(e){let t=e.authorizationDecision.trim();if(!t)throw new TypeError("Workspace history reconciliation requires an authorization decision");let r=await le(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let{documentPath:n,absolutePath:o}=Si(e.pmRoot,e.filePath),i=zt(e.pmRoot),s=await Fe(i,ct),a=Ft(s);a.ok||Cr(a.errors);let c=Ut(s),d=Tr(c);if(!Object.hasOwn(d,n))throw new TypeError(`Workspace history does not govern document ${n}`);let l=await we(o);if(l===null)throw new TypeError(`Workspace history document is missing: ${n}`);let u=JSON.parse(l);if(R(d[n])===R(u))return{changed:!1,historyPath:i};let f=Ie(),m=Cn({nowIso:f,author:e.author,op:e.op,before:c,after:Rc({...d,[n]:u},c.metadata.created_at),message:e.message,context:{reason:"out_of_band_workspace_state_reconciliation",document_path:n,authorization_decision:t}});return await Rn(i,m),{changed:!0,entry:m,historyPath:i}}finally{await r()}}async function bL(e){let t=await le(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let{documentPath:r,absolutePath:n}=Si(e.pmRoot,e.filePath),o=await Fe(zt(e.pmRoot),ct),i=Ft(o);if(i.ok||Cr(i.errors),!Number.isInteger(e.targetVersion)||e.targetVersion<1||e.targetVersion>o.length)throw new TypeError(`Invalid workspace history target version: ${String(e.targetVersion)}`);let s=Tr(Ut(o,e.targetVersion))[r];if(s===void 0)throw new TypeError(`Workspace history version ${e.targetVersion} does not contain ${r}`);let a=await we(n),c=`${JSON.stringify(s,null,2)}
|
|
108
|
-
`;if(a===c)return{document_path:r,restored_from_version:e.targetVersion,changed:!1};let d=Ut(o),l=Ie(),u=Cn({nowIso:l,author:e.author,op:e.op,before:d,after:Rc({...Tr(d),[r]:s},d.metadata.created_at),message:e.message,context:{reason:"workspace_state_restore",document_path:r,restored_from_version:e.targetVersion,replaced_out_of_band_state:!0}});await mt(n,c);try{await Rn(zt(e.pmRoot),u)}catch(f){throw a===null?await Zp.rm(n,{force:!0}):await mt(n,a),f}return{document_path:r,restored_from_version:e.targetVersion,changed:!0}}finally{await t()}}import{AsyncLocalStorage as mI}from"node:async_hooks";import{lstat as pI,realpath as u_}from"node:fs/promises";import f_ from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f4ae942c-f11f-5d24-95bf-a2abf3c226da")}catch{}})();var he={ok:!1},b=e=>typeof e=="string"?{ok:!0,value:e}:he,x=e=>typeof e=="boolean"?{ok:!0,value:e}:he;function L(e={}){return t=>typeof t!="number"||!Number.isFinite(t)||e.int&&(!Number.isInteger(t)||!Number.isSafeInteger(t))||e.positive&&t<=0||typeof e.min=="number"&&t<e.min||typeof e.max=="number"&&t>e.max?he:{ok:!0,value:t}}function N(...e){return t=>typeof t=="string"&&e.includes(t)?{ok:!0,value:t}:he}function k(e,t){return r=>{if(!Array.isArray(r)||t!==void 0&&r.length>t)return he;let n=[];for(let o of r){let i=e(o);if(!i.ok)return he;n.push(i.value)}return{ok:!0,value:n}}}function Nc(e,t){return r=>typeof r=="string"&&r.length>0&&r.length<=e&&r===r.trim()&&(t===void 0||t.test(r))?{ok:!0,value:r}:he}function p(e){return t=>t===void 0?{ok:!0,value:void 0}:e(t)}function Oi(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return he;let r={};for(let[n,o]of Object.entries(t)){let i=e(o);if(!i.ok)return he;r[n]=i.value}return{ok:!0,value:r}}}function T(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return he;let r=t,n={};for(let[o,i]of Object.entries(e)){let s=i(r[o]);if(!s.ok)return he;s.value!==void 0&&(n[o]=s.value)}return{ok:!0,value:n}}}var KA=T({key:b,values:k(b),required:p(x),aliases:p(k(b)),description:p(b)}),YA=T({command:N("create","update"),option:b,required:p(x),visible:p(x),enabled:p(x)}),XA=T({name:b,description:p(b),default_status:p(b),execution_role:p(N("agent","human","gate")),folder:p(b),aliases:p(k(b)),required_create_fields:p(k(b)),required_create_repeatables:p(k(b)),options:p(k(KA)),command_option_policies:p(k(YA))}),JA=T({id:b,aliases:p(k(b)),roles:p(k(N(...Gn))),description:p(b),order:p(L())}),ZA=T({key:b,metadata_key:p(b),front_matter_key:p(b),cli_flag:p(b),cli_aliases:p(k(b)),description:p(b),type:p(N(...Kt)),commands:p(k(N(...Kn))),repeatable:p(x),required:p(x),required_on_create:p(x),required_types:p(k(b)),allow_unset:p(x)}),QA=e=>{if(!Array.isArray(e)||e.length!==2)return he;let[t,r]=e;return typeof t!="string"||typeof r!="string"?he:{ok:!0,value:[t,r]}},eI=T({type:b,allowed_transitions:k(QA)}),tI=p(T({version:p(L({int:!0})),files:p(T({types:p(b),statuses:p(b),fields:p(b),workflows:p(b)})),statuses:p(k(JA)),fields:p(k(ZA)),workflow:p(T({draft_status:p(b),open_status:p(b),in_progress_status:p(b),blocked_status:p(b),close_status:p(b),canceled_status:p(b)})),type_workflows:p(k(eI)),unknown_field_policy:p(N(...Yn))})),rI=p(T({preset:p(N(...dd)),ownership_enforcement:p(N("none","warn","strict")),create_mode_default:p(N("progressive","strict")),close_validation_default:p(N("off","warn","strict")),require_close_reason:p(x),parent_reference:p(N("warn","strict_error")),metadata_profile:p(N("core","strict","custom")),force_required_for_stale_lock:p(x),create_default_type:p(b),workflow_enforcement:p(N("off","warn","strict")),duplicate_detection_mode:p(N("off","advisory","strict")),duplicate_detection_threshold:p(L({min:0,max:1})),duplicate_detection_limit:p(L({int:!0,min:0,max:20}))})),nI=T({name:b,disabled:p(x),require_trusted:p(x),require_provenance:p(x),sandbox_profile:p(N("none","restricted","strict")),allowed_capabilities:p(k(b)),blocked_capabilities:p(k(b)),allowed_surfaces:p(k(b)),blocked_surfaces:p(k(b)),allowed_commands:p(k(b)),blocked_commands:p(k(b)),allowed_actions:p(k(b)),blocked_actions:p(k(b)),allowed_services:p(k(b)),blocked_services:p(k(b))}),xc=N("block","warn"),oI=e=>typeof e=="string"?xc(e):T({global:p(xc),project:p(xc)})(e),iI=p(T({mode:p(N("off","warn","enforce")),trust_mode:p(N("off","warn","enforce")),pm_max_version_exceeded_mode:p(oI),require_provenance:p(x),trusted_extensions:p(k(b)),default_sandbox_profile:p(N("none","restricted","strict")),allowed_extensions:p(k(b)),blocked_extensions:p(k(b)),allowed_capabilities:p(k(b)),blocked_capabilities:p(k(b)),allowed_surfaces:p(k(b)),blocked_surfaces:p(k(b)),allowed_commands:p(k(b)),blocked_commands:p(k(b)),allowed_actions:p(k(b)),blocked_actions:p(k(b)),allowed_services:p(k(b)),blocked_services:p(k(b)),extension_overrides:p(k(nI))})),Ht=Nc(128),sI=T({harness:Nc(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),environment_keys:p(k(Ht,64)),model_environment_keys:p(k(Ht,64)),session_environment_keys:p(k(Ht,64)),provenance_environment_keys:p(Oi(k(Ht,64))),provenance_resolvers:p(Oi(N("ai_agent_version","claude_session_file"))),provenance_unavailable_dimensions:p(k(Ht,64)),argv_markers:p(k(Ht,64)),client_names:p(k(Ht,64))}),aI=T({version:L({int:!0}),id_prefix:b,ids:p(T({token_length:p(L({int:!0,min:4,max:12}))})),author_default:b,agent_identity:p(T({probes_enabled:p(x),identity_vocabulary:p(T({version:L({int:!0,positive:!0}),aliases:Oi(Nc(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u))})),harness_signals:k(sI)})),mutation_guard:p(T({require_attributed_author:p(x),secret_guard:p(N("off","advise","block")),stale_in_progress_hours:p(L({int:!0,positive:!0}))})),item_format:p(N("toon","json_markdown")),locks:T({ttl_seconds:L({int:!0}),wait_ms:p(L({int:!0,min:0}))}),checkpoints:p(T({retention_days:p(L({int:!0,positive:!0}))})),output:T({default_format:N("toon","json")}),ux:p(T({deprecation_hints:p(x)})),history:p(T({missing_stream:N("auto_create","strict_error"),compact_policy:p(T({enabled:p(x),max_entries:p(L({int:!0,positive:!0})),trigger:p(N("health_warn","auto"))}))})),validation:p(T({sprint_release_format:N("warn","strict_error"),parent_reference:p(N("warn","strict_error")),metadata_profile:p(N("core","strict","custom")),metadata_required_fields:p(k(b)),lifecycle_stale_blocker_reason_patterns:p(k(b)),lifecycle_closure_like_blocked_reason_patterns:p(k(b)),lifecycle_closure_like_resolution_patterns:p(k(b)),lifecycle_closure_like_actual_result_patterns:p(k(b)),estimate_defaults_by_type:p(Oi(L({int:!0,positive:!0})))})),governance:rI,workflow:p(T({definition_of_done:k(b)})),testing:p(T({record_results_to_items:x,allow_untrusted_linked_tests:p(x)})),telemetry:p(T({enabled:x,first_run_prompt_completed:p(x),capture_level:p(N("minimal","redacted","max")),endpoint:p(b),installation_id:p(b),retention_days:p(L({int:!0,positive:!0}))})),agent_guidance:p(T({prompt_completed:p(x),declined:p(x),declined_at:p(b),template_version:p(L({int:!0,positive:!0})),last_checked_files:p(k(b))})),item_types:p(T({definitions:k(XA)})),schema:tI,context:p(T({default_depth:p(N("brief","standard","deep")),activity_limit:p(L({int:!0,positive:!0})),stale_threshold_days:p(L({int:!0,positive:!0})),sections:p(T({hierarchy:p(x),activity:p(x),progress:p(x),recently_created:p(x),unparented:p(x),blockers:p(x),files:p(x),workload:p(x),staleness:p(x),tests:p(x)}))})),extensions:T({enabled:k(b),disabled:k(b),policy:iI}),search:T({score_threshold:L(),hybrid_semantic_weight:p(L()),max_results:L({int:!0}),embedding_model:b,embedding_corpus_max_characters:p(L()),embedding_batch_size:L({int:!0}),embedding_timeout_ms:p(L({int:!0})),scanner_max_batch_retries:L({int:!0}),provider:p(b),default_mode:p(N("auto","keyword","semantic","hybrid")),corpus_fields:p(k(b)),mutation_refresh_policy:p(N("cache_only","semantic_configured","semantic_auto")),query_expansion:p(T({enabled:p(x),provider:p(b)})),rerank:p(T({enabled:p(x),model:p(b),top_k:p(L({int:!0,positive:!0}))})),bm25:p(T({k1:p(L()),b:p(L())}))}),providers:T({openai:T({base_url:b,api_key:b,model:b}),ollama:T({base_url:b,model:b})}),vector_store:T({adapter:p(b),collection_name:p(b),qdrant:T({url:b,api_key:b}),lancedb:T({path:b})})});function Dc(e){let t=aI(e);return t.ok?{success:!0,data:t.value}:{success:!1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a0ca9902-540c-50fe-a4e2-9c234c4a01f3")}catch{}})();function Ai(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pc(e,t,r,n=[]){if(W(e,t)&&(n.length>0||Ai(r)))return r;if(W(e,r)||W(t,r))return t;if((e===void 0||Ai(e))&&Ai(t)&&Ai(r)){let o=e??{},i=new Set([...Object.keys(o),...Object.keys(t),...Object.keys(r)]);return Object.fromEntries([...i].flatMap(s=>{let a=Pc(Object.hasOwn(o,s)?o[s]:void 0,Object.hasOwn(t,s)?t[s]:void 0,Object.hasOwn(r,s)?r[s]:void 0,[...n,s]);return a===void 0?[]:[[s,a]]}))}throw new g(`Settings changed concurrently at ${n.join(".")||"<root>"}; read the latest settings and reapply the intended change.`,h.CONFLICT,{reason:"stale_settings_snapshot",required:"Read a fresh settings snapshot and reapply the intended change.",why:"Another writer changed the same setting after this snapshot was read.",examples:["pm config project export --json"],nextSteps:["Read the current settings, then retry the original config operation."]})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="de43e8e6-d7ef-53cc-94b0-ccdf1c4f94a3")}catch{}})();var cI={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},r_=120;function Mc(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function o_(e){let t=new Map;for(let[r,n]of Object.entries(e))t.set(r.toLowerCase(),n);return t}var dI=o_(cI),n_=new WeakMap;function lI(e){let t=n_.get(e);if(t)return t;let r=o_(e);return n_.set(e,r),r}function IL(e,t){let r=(e??"").trim().toLowerCase();if(r.length===0)return r_;if(t){let o=lI(t).get(r);if(Mc(o))return Math.floor(o)}let n=dI.get(r);return Mc(n)?Math.floor(n):r_}function $c(e){let t={};if(e===null||typeof e!="object"||Array.isArray(e))return t;for(let[r,n]of Object.entries(e)){let o=r.trim();o.length===0||!Mc(n)||(t[o]=Math.floor(n))}return t}import{stat as uI}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="78c79deb-5cf0-54fe-b98c-a0d5b3671ab2")}catch{}})();var Ii=new Map;function i_(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}async function fI(e){try{let t=await uI(e);return{path:e,mtime_ms:t.mtimeMs,size:t.size}}catch{return{path:e,mtime_ms:null,size:null}}}async function dt(e){let t=i_(e),r=await Promise.all(t.map(n=>fI(n)));return r.sort((n,o)=>n.path.localeCompare(o.path)),r}function xn(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1){let n=e[r],o=t[r];if(n.path!==o.path||n.mtime_ms!==o.mtime_ms||n.size!==o.size)return!1}return!0}function s_(e){return Ii.get(e)}function Ti(e,t){let r=i_(t.tracked_paths),n=[...t.signatures].map(o=>({path:o.path,mtime_ms:o.mtime_ms,size:o.size})).sort((o,i)=>o.path.localeCompare(i.path));Ii.set(e,{tracked_paths:r,signatures:n,value:t.value})}function qt(e){if(e){Ii.delete(e);return}Ii.clear()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f4308e20-251e-52d4-81a4-044e910e87fa")}catch{}})();var zc=new mI;async function KL(e,t,r=()=>!0){let n=new Set([f_.resolve(e)]);try{n.add(await u_(e))}catch{}return zc.run([...zc.getStore()??[],[n,r]],t)}function _I(e){let t=f_.resolve(e);return zc.getStore()?.some(([r,n])=>r.has(t)&&n())??!1}var yI="settings:write",m_=Symbol("pm.settings.persist_source"),hI=128,gI=new Set(["off","advisory","strict"]);function a_(e){return structuredClone(ed[e])}function bI(e){return e==="minimal"||e==="default"||e==="strict"||e==="custom"?e:S.governance.preset}function c_(e,t){let r=typeof t.create_default_type=="string"?t.create_default_type.trim():void 0;return r&&r.length>0&&(e.create_default_type=r),(t.workflow_enforcement==="off"||t.workflow_enforcement==="warn"||t.workflow_enforcement==="strict")&&(e.workflow_enforcement=t.workflow_enforcement),t.require_close_reason===!1&&(e.require_close_reason=!1),e.duplicate_detection_mode=t.duplicate_detection_mode,e.duplicate_detection_threshold=t.duplicate_detection_threshold,e.duplicate_detection_limit=t.duplicate_detection_limit,e}function wI(e){return e.preset==="custom"?c_({preset:"custom",ownership_enforcement:e.ownership_enforcement,create_mode_default:e.create_mode_default,close_validation_default:e.close_validation_default,parent_reference:e.parent_reference,metadata_profile:e.metadata_profile,force_required_for_stale_lock:e.force_required_for_stale_lock},e):c_({preset:e.preset},e)}function vI(e){let t=typeof e.create_default_type=="string"?e.create_default_type.trim():void 0,r={};t&&t.length>0&&(r.create_default_type=t),(e.workflow_enforcement==="off"||e.workflow_enforcement==="warn"||e.workflow_enforcement==="strict")&&(r.workflow_enforcement=e.workflow_enforcement),typeof e.require_close_reason=="boolean"&&(r.require_close_reason=e.require_close_reason),gI.has(String(e.duplicate_detection_mode))&&(r.duplicate_detection_mode=e.duplicate_detection_mode);let n=e.duplicate_detection_threshold;[typeof n=="number",Number.isFinite(n),Number(n)>=0,Number(n)<=1].every(Boolean)&&(r.duplicate_detection_threshold=n);let o=e.duplicate_detection_limit;return[typeof o=="number",Number.isSafeInteger(o),Number(o)>=0,Number(o)<=20].every(Boolean)&&(r.duplicate_detection_limit=o),r}function p_(e){let t=e.governance??{},r=bI(t.preset),n=vI(t);if(r==="custom"){let s=a_("default"),a=n.require_close_reason??s.require_close_reason;return{preset:r,ownership_enforcement:t.ownership_enforcement??s.ownership_enforcement,create_mode_default:t.create_mode_default??s.create_mode_default,close_validation_default:t.close_validation_default??s.close_validation_default,parent_reference:t.parent_reference??s.parent_reference,metadata_profile:t.metadata_profile??s.metadata_profile,force_required_for_stale_lock:t.force_required_for_stale_lock??s.force_required_for_stale_lock,...n,require_close_reason:a,duplicate_detection_mode:n.duplicate_detection_mode??s.duplicate_detection_mode,duplicate_detection_threshold:n.duplicate_detection_threshold??s.duplicate_detection_threshold,duplicate_detection_limit:n.duplicate_detection_limit??s.duplicate_detection_limit}}let o=a_(r),i=n.require_close_reason??o.require_close_reason;return{preset:r,...o,...n,require_close_reason:i}}function __(){return structuredClone(S)}function y_(e){return e==="cache_only"||e==="semantic_configured"||e==="semantic_auto"?e:S.search.mutation_refresh_policy}function h_(e){return e==="auto"||e==="keyword"||e==="semantic"||e==="hybrid"?e:"auto"}function g_(e){return typeof e=="boolean"?e:S.search.query_expansion.enabled}function b_(e){return typeof e!="string"?S.search.query_expansion.provider:e.trim()}function w_(e){return typeof e=="boolean"?e:S.search.rerank.enabled}function v_(e){return typeof e!="string"?S.search.rerank.model:e.trim()}function E_(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0?e:S.search.rerank.top_k}function k_(e){if(typeof e!="string")return S.vector_store.collection_name;let t=e.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,hI);return t.length>0?t:S.vector_store.collection_name}function jc(e){return{present:Array.isArray(e),values:Array.isArray(e)?structuredClone(e):[]}}function S_(e,t){let r=e.schema,n=jc(r?.statuses),o=jc(r?.fields),i=jc(r?.type_workflows);return{persisted_settings:structuredClone(e),source_settings:structuredClone(e),has_source_item_type_definitions:Array.isArray(e.item_types?.definitions),source_item_type_definitions:Rr(e.item_types?.definitions),has_source_schema_statuses:n.present,source_schema_statuses:n.values,has_source_schema_fields:o.present,source_schema_fields:o.values,has_source_schema_type_workflows:i.present,source_schema_type_workflows:i.values,runtime_item_type_definitions:Rr(t.item_types?.definitions),runtime_schema_statuses:structuredClone(t.schema.statuses),runtime_schema_fields:structuredClone(t.schema.fields),runtime_schema_type_workflows:structuredClone(t.schema.type_workflows??[])}}function xi(e,t){Object.defineProperty(e,m_,{value:t,writable:!0,configurable:!0,enumerable:!1})}function qc(e){let t=e[m_];if(!(!t||typeof t!="object"))return t}function YL(e){let t=qc(e);if(t){let r=structuredClone(t);r.source_settings.item_format=e.item_format,xi(e,r)}}function Ci(e){let t=structuredClone(e.settings),r=qc(e.settings);return r&&xi(t,r),{settings:t,metadata:{has_explicit_item_format:e.metadata.has_explicit_item_format},warnings:[...e.warnings]}}function EI(e,t,r){let n=Te(t);return[r,ue(e,n.files.types,ie.types),ue(e,n.files.statuses,ie.statuses),ue(e,n.files.fields,ie.fields),ue(e,n.files.workflows,ie.workflows)]}async function kI(e,t,r){let n=await dt(t);Ti(e,{tracked_paths:t,signatures:n,value:Ci(r)})}async function SI(e,t,r){try{await kI(e,t,r)}catch{qt(e)}}function d_(e,t){return e.find(r=>r.path===t)}function OI(e,t,r){for(let n of r){let o=d_(e,n),i=d_(t,n);if(!o||!i||!xn([o],[i]))return!1}return!0}async function Lc(e,t,r,n,o){try{let i=await dt(t);if(!OI(n,i,o)){qt(e);return}Ti(e,{tracked_paths:t,signatures:i,value:Ci(r)})}catch{qt(e)}}function AI(e,t){let r=Te(e.schema),n=Rr(e.item_types?.definitions);if(!t)return{item_type_definitions:n,schema_statuses:r.statuses,schema_fields:r.fields,schema_type_workflows:r.type_workflows};let o=r.type_workflows??[],i=W(n,t.runtime_item_type_definitions),s=W(r.statuses,t.runtime_schema_statuses),a=W(r.fields,t.runtime_schema_fields),c=W(o,t.runtime_schema_type_workflows);return{item_type_definitions:i?t.has_source_item_type_definitions?Rr(t.source_item_type_definitions):[]:n,schema_statuses:s?t.has_source_schema_statuses?structuredClone(t.source_schema_statuses):[]:r.statuses,schema_fields:a?t.has_source_schema_fields?structuredClone(t.source_schema_fields):[]:r.fields,schema_type_workflows:c?t.has_source_schema_type_workflows?structuredClone(t.source_schema_type_workflows):void 0:r.type_workflows}}function Re(e){return{settings:__(),metadata:{has_explicit_item_format:!1},warnings:e?[e]:[]}}function O_(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.item_format;return t==="toon"||t==="json_markdown"}function Uc(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}function A_(e){let t=S.agent_guidance,r=e?.template_version;return{prompt_completed:e?.prompt_completed===!0,declined:e?.declined===!0,declined_at:typeof e?.declined_at=="string"?e.declined_at:t.declined_at,template_version:typeof r=="number"&&Number.isInteger(r)&&r>0?r:t.template_version,last_checked_files:Uc(e?.last_checked_files??t.last_checked_files)}}function ke(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}function II(e){return e==="off"||e==="warn"||e==="enforce"?e:S.extensions.policy.mode}function TI(e){return e==="off"||e==="warn"||e==="enforce"?e:S.extensions.policy.trust_mode}function I_(e){return e==="none"||e==="restricted"||e==="strict"?e:S.extensions.policy.default_sandbox_profile}function CI(e){let t=e.name.trim().toLowerCase();if(t.length===0)return null;let r={name:t};e.disabled===!0&&(r.disabled=!0),e.require_trusted===!0&&(r.require_trusted=!0),e.require_provenance===!0&&(r.require_provenance=!0),e.sandbox_profile!==void 0&&(r.sandbox_profile=I_(e.sandbox_profile));let n=ke(e.allowed_capabilities),o=ke(e.blocked_capabilities),i=ke(e.allowed_surfaces),s=ke(e.blocked_surfaces),a=ke(e.allowed_commands),c=ke(e.blocked_commands),d=ke(e.allowed_actions),l=ke(e.blocked_actions),u=ke(e.allowed_services),f=ke(e.blocked_services);return n.length>0&&(r.allowed_capabilities=n),o.length>0&&(r.blocked_capabilities=o),i.length>0&&(r.allowed_surfaces=i),s.length>0&&(r.blocked_surfaces=s),a.length>0&&(r.allowed_commands=a),c.length>0&&(r.blocked_commands=c),d.length>0&&(r.allowed_actions=d),l.length>0&&(r.blocked_actions=l),u.length>0&&(r.allowed_services=u),f.length>0&&(r.blocked_services=f),r}function RI(e){let t=new Map;for(let r of e??[]){let n=CI(r);n&&t.set(n.name,n)}return[...t.values()].sort((r,n)=>r.name.localeCompare(n.name))}function Fc(e){return e==="block"||e==="warn"?e:void 0}function xI(e){if(typeof e=="string")return Fc(e);if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=Fc(e.global),r=Fc(e.project);return t===void 0&&r===void 0?void 0:{...t!==void 0?{global:t}:{},...r!==void 0?{project:r}:{}}}}function ge(e,t){return ke(e?.[t]??S.extensions.policy[t])}function T_(e){let t=xI(e?.pm_max_version_exceeded_mode);return{mode:II(e?.mode),trust_mode:TI(e?.trust_mode),...t!==void 0?{pm_max_version_exceeded_mode:t}:{},require_provenance:e?.require_provenance===!0,trusted_extensions:ge(e,"trusted_extensions"),default_sandbox_profile:I_(e?.default_sandbox_profile),allowed_extensions:ge(e,"allowed_extensions"),blocked_extensions:ge(e,"blocked_extensions"),allowed_capabilities:ge(e,"allowed_capabilities"),blocked_capabilities:ge(e,"blocked_capabilities"),allowed_surfaces:ge(e,"allowed_surfaces"),blocked_surfaces:ge(e,"blocked_surfaces"),allowed_commands:ge(e,"allowed_commands"),blocked_commands:ge(e,"blocked_commands"),allowed_actions:ge(e,"allowed_actions"),blocked_actions:ge(e,"blocked_actions"),allowed_services:ge(e,"allowed_services"),blocked_services:ge(e,"blocked_services"),extension_overrides:RI(e?.extension_overrides??S.extensions.policy.extension_overrides)}}function C_(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase().replaceAll("-","_")))].filter(t=>t.length>0).sort((t,r)=>t.localeCompare(r)).filter(t=>["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"].includes(t))}function lt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}function G(e,t){return e===void 0?t:e}function be(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function Hc(e){return Array.isArray(e)?e:[]}function NI(e,t,r){return{...t.validation,...e.validation,parent_reference:r.parent_reference,metadata_profile:r.metadata_profile,metadata_required_fields:C_(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:lt(e.validation?.lifecycle_stale_blocker_reason_patterns??t.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:lt(e.validation?.lifecycle_closure_like_blocked_reason_patterns??t.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:lt(e.validation?.lifecycle_closure_like_resolution_patterns??t.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:lt(e.validation?.lifecycle_closure_like_actual_result_patterns??t.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:$c(e.validation?.estimate_defaults_by_type)}}function DI(e,t){return{enabled:e.telemetry?.enabled??t.telemetry.enabled,first_run_prompt_completed:e.telemetry?.first_run_prompt_completed??t.telemetry.first_run_prompt_completed,capture_level:e.telemetry?.capture_level??t.telemetry.capture_level,endpoint:e.telemetry?.endpoint??t.telemetry.endpoint,installation_id:e.telemetry?.installation_id??t.telemetry.installation_id,retention_days:e.telemetry?.retention_days??t.telemetry.retention_days}}function PI(e,t){return{...t.search,...e.search,default_mode:h_(e.search?.default_mode),mutation_refresh_policy:y_(e.search?.mutation_refresh_policy),query_expansion:{...t.search.query_expansion,...e.search?.query_expansion,enabled:g_(e.search?.query_expansion?.enabled),provider:b_(e.search?.query_expansion?.provider)},rerank:{...t.search.rerank,...e.search?.rerank,enabled:w_(e.search?.rerank?.enabled),model:v_(e.search?.rerank?.model),top_k:E_(e.search?.rerank?.top_k)}}}function MI(e,t){return{adapter:e.vector_store.adapter??t.vector_store.adapter,collection_name:k_(e.vector_store.collection_name),qdrant:{...t.vector_store.qdrant,...e.vector_store.qdrant},lancedb:{...t.vector_store.lancedb,...e.vector_store.lancedb}}}function $I(e,t){return e.item_format==="json_markdown"?"toon":e.item_format??t.item_format}function jI(e,t){return{default_depth:e.context?.default_depth??t.context.default_depth,activity_limit:e.context?.activity_limit??t.context.activity_limit,stale_threshold_days:e.context?.stale_threshold_days??t.context.stale_threshold_days,sections:{...t.context.sections,...e.context?.sections}}}function LI(e,t){return{openai:{...t.providers.openai,...e.providers.openai},ollama:{...t.providers.ollama,...e.providers.ollama}}}function Rr(e){let t=(e??[]).map(n=>Qn(n)).filter(n=>n!==null),r=new Map;for(let n of t)r.set(n.name.toLowerCase(),n);return[...r.values()].sort((n,o)=>n.name.localeCompare(o.name))}function Ri(e){let t=__(),r=p_({governance:e.governance??{preset:"default"}});return{...t,...e,item_format:$I(e,t),locks:{...t.locks,...e.locks},ids:{...t.ids,...e.ids},agent_identity:structuredClone(e.agent_identity??t.agent_identity),mutation_guard:{...t.mutation_guard,...e.mutation_guard},checkpoints:{...t.checkpoints,...e.checkpoints},output:{...t.output,...e.output},ux:{...t.ux,...e.ux},history:{...t.history,...e.history,compact_policy:{...t.history.compact_policy,...e.history?.compact_policy}},validation:NI(e,t,r),governance:r,workflow:{definition_of_done:[...e.workflow?.definition_of_done??t.workflow.definition_of_done]},testing:{record_results_to_items:e.testing?.record_results_to_items??t.testing.record_results_to_items,allow_untrusted_linked_tests:e.testing?.allow_untrusted_linked_tests??t.testing.allow_untrusted_linked_tests},telemetry:DI(e,t),agent_guidance:A_(e.agent_guidance??t.agent_guidance),item_types:{definitions:Rr(e.item_types?.definitions)},schema:Te(e.schema??t.schema),context:jI(e,t),extensions:{enabled:[...e.extensions.enabled],disabled:[...e.extensions.disabled],policy:T_(e.extensions.policy??t.extensions.policy)},search:PI(e,t),providers:LI(e,t),vector_store:MI(e,t)}}function FI(e){e.agent_identity=A(e.agent_identity,["probes_enabled","identity_vocabulary","harness_signals"]);let t=e.agent_identity;Object.hasOwn(t,"identity_vocabulary")&&(t.identity_vocabulary=A(be(t.identity_vocabulary),["version","aliases"])),e.agent_identity.harness_signals=Hc(e.agent_identity.harness_signals).map(r=>A(be(r),["harness","environment_keys","model_environment_keys","session_environment_keys","provenance_environment_keys","provenance_resolvers","provenance_unavailable_dimensions","argv_markers","client_names"])),e.locks=A(e.locks,["ttl_seconds","wait_ms"]),e.ids=A(e.ids,["token_length"]),e.mutation_guard=A(e.mutation_guard,["require_attributed_author","secret_guard","stale_in_progress_hours"]),e.checkpoints=A(e.checkpoints,["retention_days"]),e.output=A(e.output,["default_format"]),e.ux=A(e.ux,["deprecation_hints"]),e.history=A(e.history,["missing_stream","compact_policy"]),e.validation=A(e.validation,["sprint_release_format","parent_reference","metadata_profile","metadata_required_fields","lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns","estimate_defaults_by_type"]),e.governance=A(e.governance,["preset","ownership_enforcement","create_mode_default","close_validation_default","require_close_reason","parent_reference","metadata_profile","force_required_for_stale_lock","create_default_type","workflow_enforcement","duplicate_detection_mode","duplicate_detection_threshold","duplicate_detection_limit"]),e.workflow=A(e.workflow,["definition_of_done"]),e.testing=A(e.testing,["record_results_to_items","allow_untrusted_linked_tests"]),e.telemetry=A(e.telemetry,["enabled","first_run_prompt_completed","capture_level","endpoint","installation_id","retention_days"]),e.agent_guidance=A(e.agent_guidance,["prompt_completed","declined","declined_at","template_version","last_checked_files"]),e.item_types=A(e.item_types,["definitions"]),e.schema=A(e.schema,["version","files","statuses","fields","workflow","type_workflows","unknown_field_policy"]),e.schema.files=A(be(e.schema.files),["types","statuses","fields","workflows"]),e.schema.workflow=A(be(e.schema.workflow),["draft_status","open_status","in_progress_status","blocked_status","close_status","canceled_status"]),e.context=A(e.context,["default_depth","activity_limit","stale_threshold_days","sections"]),e.context.sections=A(be(e.context.sections),["hierarchy","activity","progress","blockers","files","workload","staleness","tests"]),e.extensions=A(e.extensions,["enabled","disabled","policy"]),e.extensions.policy=A(be(e.extensions.policy),["mode","trust_mode","pm_max_version_exceeded_mode","require_provenance","trusted_extensions","default_sandbox_profile","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services","extension_overrides"]),e.extensions.policy.extension_overrides=Hc(e.extensions.policy.extension_overrides).map(r=>A(be(r),["name","disabled","require_trusted","require_provenance","sandbox_profile","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"])),e.search=A(e.search,["score_threshold","hybrid_semantic_weight","max_results","embedding_model","embedding_corpus_max_characters","embedding_batch_size","embedding_timeout_ms","scanner_max_batch_retries","provider","default_mode","mutation_refresh_policy","query_expansion","rerank"]),e.search.query_expansion=A(be(e.search.query_expansion),["enabled","provider"]),e.search.rerank=A(be(e.search.rerank),["enabled","model","top_k"]),e.providers=A(e.providers,["openai","ollama"]),e.providers.openai=A(be(e.providers.openai),["base_url","api_key","model"]),e.providers.ollama=A(be(e.providers.ollama),["base_url","model"]),e.vector_store=A(e.vector_store,["adapter","collection_name","qdrant","lancedb"]),e.vector_store.qdrant=A(be(e.vector_store.qdrant),["url","api_key"]),e.vector_store.lancedb=A(be(e.vector_store.lancedb),["path"])}function zI(e){return{...e,locks:G(e.locks,S.locks),ids:G(e.ids,S.ids),agent_identity:G(e.agent_identity,S.agent_identity),mutation_guard:G(e.mutation_guard,S.mutation_guard),checkpoints:G(e.checkpoints,S.checkpoints),output:G(e.output,S.output),ux:G(e.ux,S.ux),history:G(e.history,S.history),validation:G(e.validation,S.validation),workflow:G(e.workflow,S.workflow),testing:G(e.testing,S.testing),telemetry:G(e.telemetry,S.telemetry),agent_guidance:G(e.agent_guidance,S.agent_guidance),item_types:G(e.item_types,S.item_types),schema:G(e.schema,S.schema),context:G(e.context,S.context),extensions:G(e.extensions,S.extensions),search:G(e.search,S.search),providers:G(e.providers,S.providers),vector_store:G(e.vector_store,S.vector_store)}}function UI(e,t){return{...e.validation,parent_reference:t.parent_reference,metadata_profile:t.metadata_profile,metadata_required_fields:C_(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:lt(e.validation?.lifecycle_stale_blocker_reason_patterns??S.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:lt(e.validation?.lifecycle_closure_like_blocked_reason_patterns??S.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:lt(e.validation?.lifecycle_closure_like_resolution_patterns??S.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:lt(e.validation?.lifecycle_closure_like_actual_result_patterns??S.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:$c(e.validation?.estimate_defaults_by_type)}}function HI(e){return{...S.search,...e.search,default_mode:h_(e.search?.default_mode),mutation_refresh_policy:y_(e.search?.mutation_refresh_policy),query_expansion:{...S.search.query_expansion,...e.search?.query_expansion,enabled:g_(e.search?.query_expansion?.enabled),provider:b_(e.search?.query_expansion?.provider)},rerank:{...S.search.rerank,...e.search?.rerank,enabled:w_(e.search?.rerank?.enabled),model:v_(e.search?.rerank?.model),top_k:E_(e.search?.rerank?.top_k)}}}function qI(e){return{default_depth:e.context?.default_depth??S.context.default_depth,activity_limit:e.context?.activity_limit??S.context.activity_limit,stale_threshold_days:e.context?.stale_threshold_days??S.context.stale_threshold_days,sections:{...S.context.sections,...e.context?.sections}}}function VI(e){return{...e.vector_store,adapter:e.vector_store?.adapter??S.vector_store.adapter,collection_name:k_(e.vector_store?.collection_name),qdrant:{...e.vector_store?.qdrant},lancedb:{...e.vector_store?.lancedb}}}function BI(e,t,r,n){return{...e,item_format:"toon",validation:UI(e,t),governance:t,agent_guidance:A_(e.agent_guidance),item_types:{definitions:n.item_type_definitions},schema:{...r,statuses:n.schema_statuses,fields:n.schema_fields,type_workflows:n.schema_type_workflows},search:HI(e),context:qI(e),extensions:{enabled:Uc(e.extensions?.enabled),disabled:Uc(e.extensions?.disabled),policy:T_(e.extensions?.policy)},vector_store:VI(e)}}function R_(e,t){for(let r of Object.keys(t)){let n=Reflect.get(t,r),o=e[r];typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof o=="object"&&o!==null&&!Array.isArray(o)?R_(o,n):e[r]=structuredClone(n)}}function x_(e,t,r){let n=new Set([...Object.keys(t),...Object.keys(r)]);for(let o of n){let i=t[o],s=r[o];if(!W(i,s)){if(s===void 0){delete e[o];continue}if(typeof i=="object"&&i!==null&&!Array.isArray(i)&&typeof s=="object"&&s!==null&&!Array.isArray(s)){let a=e[o],c=typeof a=="object"&&a!==null&&!Array.isArray(a)?a:{};x_(c,i,s),Object.keys(c).length>0?e[o]=c:delete e[o];continue}e[o]=structuredClone(s)}}}var Vc=["version","id_prefix","ids","author_default","agent_identity","mutation_guard","item_format","locks","checkpoints","output","ux","history","validation","governance","workflow","testing","telemetry","agent_guidance","item_types","schema","context","extensions","search","providers","vector_store"];function l_(e,t){let r=zI(e),n=p_(r),o=Te(r.schema),i=AI(r,t),s=BI(r,n,o,i),a=A({...s,governance:wI(n)},Vc);return FI(a),a}function WI(e,t={}){let r=t.source===void 0?t.persist_source:S_(t.source.validated,Ri(t.source.validated)),n=l_(e,r);if(r){let o=Ri(r.source_settings);o.item_types={definitions:structuredClone(r.runtime_item_type_definitions)},o.schema={...o.schema,statuses:structuredClone(r.runtime_schema_statuses),fields:structuredClone(r.runtime_schema_fields),type_workflows:structuredClone(r.runtime_schema_type_workflows)};let i=l_(o,r);t.source!==void 0&&R_(i,t.source.validated);let s=structuredClone(t.source===void 0?r.source_settings:t.source.raw);return x_(s,i,n),`${JSON.stringify(A(s,Vc),null,2)}
|
|
109
|
-
`}return`${JSON.stringify(n,null,2)}
|
|
110
|
-
`}async function GI(e){let t;try{t=await u_(e)}catch(a){if(Se(a))return Re();throw a}let r=Oe(t),n;try{n=await pI(r)}catch(a){if(Se(a))return Re();throw a}if(!n.isFile())throw Li("settings.json");let o;try{o=await td(r,Li("settings.json"))}catch(a){if(Se(a))return Re();throw a}let i;try{i=JSON.parse(o)}catch{return Re("settings_read_invalid_json")}let s=Dc(i);return s.success?{settings:Ri(s.data),metadata:{has_explicit_item_format:O_(i)},warnings:s.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[]}:Re("settings_read_invalid_schema")}async function N_(e){if(_I(e))return GI(e);let t=Oe(e),r=[t];await nr({path:t,scope:"project"});let n=s_(e);if(n){let d=await dt(n.tracked_paths);if(xn(d,n.signatures))return Ci(n.value)}let o=await dt([t]),i;try{i=await we(t)}catch{return Re("settings_read_fs_error")}if(i===null){let d=Re();return await Lc(e,[t],d,o,[t]),d}let s=await dt([t]);if(!xn(o,s))return qt(e),N_(e);let a;try{a=JSON.parse(i)}catch{let d=Re("settings_read_invalid_json");return await Lc(e,[t],d,s,[t]),d}let c=Dc(a);if(!c.success){let d=Re("settings_read_invalid_schema");return await Lc(e,[t],d,s,[t]),d}try{let d=Ri(c.data),l=EI(e,d.schema,t);r=l;let u=await dt(l),f=await wm(e,d.schema),m=await dt(l),_={...d,item_types:{definitions:Rr([...d.item_types.definitions,...Hc(f.type_definitions_from_file)])},schema:f.schema};xi(_,S_(c.data,_));let y={settings:_,metadata:{has_explicit_item_format:O_(a)},warnings:[...c.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[],...f.warnings]};return xn(u,m)?Ti(e,{tracked_paths:l,signatures:m,value:Ci(y)}):qt(e),y}catch{let d=Re("settings_read_merge_failed");return await SI(e,r,d),d}}async function XL(e){return(await N_(e)).settings}async function JL(e,t,r=yI){let n=Oe(e),o=qc(t),i=WI(t,{persist_source:o}),s=JSON.parse(i);try{await t_({pmRoot:e,filePath:n,mutate:a=>{let c=null;if(a!==null)try{c=JSON.parse(a)}catch{throw new g("Existing settings.json is malformed; the settings write was refused.",h.USAGE,{code:"settings_write_invalid_existing_json",reason:"existing_settings_json_malformed",why:"Writing defaults over malformed settings could destroy intended project configuration.",nextSteps:["Repair the syntax in .agents/pm/settings.json, then retry the original command.","Run pm health to confirm the settings warning has cleared."]})}return{raw:o?`${JSON.stringify(A(Pc(o.persisted_settings,s,c),Vc),null,2)}
|
|
111
|
-
`:i,result:void 0}},op:r,author:cp(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms,recordCreation:!1}),o&&xi(t,{...o,persisted_settings:structuredClone(s)}),await vo({path:n,scope:"project",op:r})}finally{qt(e)}}import D_ from"node:fs";import Nn from"node:path";import{createRequire as KI}from"node:module";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="19d9b802-1efa-5716-8176-ecbf5b153ff0")}catch{}})();var Dn="@unbrained/pm-cli",YI=new Set(["append","claim","changelog","close","close-many","close-task","comments","config","copy","create","dedupe-merge","delete","deps","docs","extension","event","events","files","focus","gc","history-author-acknowledge","history-compact","history-redact","history-repair","init","install","item","learnings","meet","merge","normalize","notes","package","packages","pause-task","plan","profile","reindex","release","remind","restore","schema","start-task","test","test-all","test-runs","test-runs-worker","telemetry","templates","twin","update","update-many","upgrade","vcs","workspace"]),P_=new Set(["--author","--output-budget","--output-format","--output-include","--output-limit","--output-session","--path","--pm-path"]),Wc=/\b(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-(\d+))?\b/u,Mi="2026.8.31";function se(e,t){return e.some(r=>t.includes(r.split("=",1)[0]))}function Bc(e,t){return["activate","adopt","adopt-all","deactivate","init","install","migrate","reload","uninstall"].includes(t[0]??"")||se(e,["--activate","--adopt","--adopt-all","--deactivate","--fix-managed-state","--init","--install","--output","--reload","--scaffold","--uninstall"])}var XI={changelog:(e,t)=>{if(t[0]==="generate")return!se(e,["--check"]);let r=e.indexOf("export");return t[0]==="export"&&(se(e,["--output"])||r>=0&&e[r+1]!==void 0&&!e[r+1].startsWith("-"))},comments:e=>se(e,["--add","--delete","--edit","--file","--stdin"]),config:(e,t)=>(t[0]==="project"||t[0]==="global"?t[1]:t[0])==="set",deps:()=>!1,docs:e=>se(e,["--add","--add-glob","--migrate","--remove"]),duplicates:()=>!1,events:()=>!1,extension:Bc,files:(e,t)=>se(e,["--add","--add-glob","--migrate","--remove"])||t[0]==="discover"&&se(e,["--apply"]),health:e=>!se(e,["--check-only","--no-refresh","--skip-vectors"]),learnings:e=>se(e,["--add","--delete","--edit","--file","--stdin"]),merge:(e,t)=>t[0]!=="report",notes:e=>se(e,["--add","--delete","--edit","--file","--stdin"]),package:Bc,packages:Bc,profile:(e,t)=>t[0]==="apply",schema:(e,t)=>["add-field","add-status","add-type","remove-field","remove-status","remove-type","remap-status","rename-field","rename-type"].includes(t[0]??"")&&!(se(e,["--infer"])&&!se(e,["--apply"])),telemetry:(e,t)=>t.slice(0,2).some(r=>["clear","flush"].includes(r)),templates:(e,t)=>t[0]==="save",test:e=>se(e,["--update","--update-index","--add","--add-json","--background","--measure","--remove","--resume","--run","--stop"]),validate:e=>se(e,["--auto-fix","--prune-missing"]),vcs:(e,t)=>["abandon","create","merge","propose","ref-create"].includes(t[0]??""),workspace:(e,t)=>t[0]==="snapshot"&&["create","delete","restore"].includes(t[1]??"")};function Di(e){let t=e.match(Wc);return t?[Number(t[1]),Number(t[2]),Number(t[3]),Number(t[4]??0)]:null}function ut(e,t){let r=Di(e),n=Di(t);if(!r||!n)return null;for(let o=0;o<r.length;o+=1){let i=r[o]-n[o];if(i!==0)return Math.sign(i)}return 0}function Ni(e){return ut(e,Mi)!==-1?3:2}function JI(e,t){if(t===3)return e.filter(r=>r.history_epoch_compatible===!1).map(r=>({...r,declaration:r.declaration??r.version})).sort((r,n)=>ut(r.version,n.version))[0]}function Pi(e){try{let t=JSON.parse(D_.readFileSync(e,"utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function ZI(e){let t=[...e.matchAll(/(<=|<)\s*v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/gu)].map(n=>({inclusive:n[1]==="<=",version:n[2]})),r=e.match(/\b\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?\s+-\s+v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/u);return r?[...t,{inclusive:!0,version:r[1]}]:t}function QI(e){let t=e.split("||").map(r=>ZI(r));return{bounded:t.some(r=>r.length>0),compatible:t.some(r=>r.every(n=>{let o=ut(Mi,n.version);return o!==null&&(n.inclusive?o!==1:o===-1)}))}}function M_(e){return["dependencies","devDependencies","optionalDependencies","peerDependencies"].flatMap(t=>{let r=e[t];if(typeof r!="object"||r===null)return[];let n=r[Dn];return typeof n=="string"?[n.trim()]:[]})}function eT(e){return M_(e).flatMap(t=>{let r=/^[<!]/u.test(t)?void 0:t.match(Wc)?.[0];if(!r)return[];let n=/^(?:=|v)?\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?$/u.test(t),o=QI(t);return[{version:r,constraint:n?"exact":o.bounded?"range":"minimum",...n?{}:{declaration:t},history_epoch_compatible:n?ut(r,Mi)!==-1:o.compatible}]})}function tT(e){let t=Pi(Nn.join(e,"package-lock.json"))?.packages;if(typeof t!="object"||t===null)return;let r=t["node_modules/@unbrained/pm-cli"];if(typeof r!="object"||r===null)return;let n=r.version;return typeof n=="string"?n:void 0}function rT(e,t){try{let r=D_.readFileSync(Nn.join(e,t),"utf8").split(/\r?\n/u),n=r.findIndex(s=>s.includes(Dn));if(n<0)return;let o=r[n].match(/^\s*/u)[0].length,i=[r[n]];for(let s=n+1;s<r.length;s+=1){let a=r[s],c=a.trim(),d=a.match(/^\s*/u)[0].length;if(c.length>0&&d<=o)break;i.push(a)}return i.join(`
|
|
112
|
-
`).match(/^\s*version(?::\s*|\s+)["']?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/mu)?.[1]??i[0].match(Wc)?.[0]}catch{return}}function $_(e){let t=[],r=Pi(Nn.join(e,"package.json"));r&&t.push(...eT(r).map(i=>({...i,source:"package.json"})));let n=Pi(Nn.join(e,"node_modules","@unbrained","pm-cli","package.json"))?.version;typeof n=="string"&&Di(n)&&t.push({version:n,source:"installed-package",constraint:"exact",history_epoch_compatible:Ni(n)===3});let o=tT(e);o&&Di(o)&&t.push({version:o,source:"package-lock.json",constraint:"exact",history_epoch_compatible:Ni(o)===3});for(let i of["pnpm-lock.yaml","yarn.lock"]){let s=rT(e,i);s&&t.push({version:s,source:i,constraint:"exact",history_epoch_compatible:Ni(s)===3})}return t}function oF(e,t){if(t<=1)return;let{minVersion:r,lt:n}=KI(import.meta.url)("semver"),o=M_(Pi(Nn.join(e,"package.json"))??{}).find(s=>{try{let a=r(s);return a!==null&&n(a,"2026.10.10")}catch{return!1}}),i=o===void 0?$_(e).find(s=>ut(s.version,"2026.10.10")===-1):{version:o,source:"package.json"};if(i)throw new g(`The project selects pm ${i.version}, which cannot safely refuse item format ${t}.`,h.CONFLICT,{code:"project_runtime_item_format_incompatible",reason:i.source,required:"Upgrade project pins, installed SDKs, CI hosts and Git merge drivers before writing guarded item formats.",nextSteps:["Use a pm runtime supporting the required item format throughout the project; preserve original item and history bytes, and never re-anchor history to satisfy an older host."]})}function j_(e){for(let t=0;t<e.length;t+=1){let r=e[t];if(P_.has(r)){t+=1;continue}if(!r.startsWith("-"))return{command:r.toLowerCase(),index:t}}}function nT(e){let t=j_(e);if(!t||se(e,["--help","-h","--dry-run"]))return!1;let{command:r,index:n}=t,o=[];for(let s=n+1;s<e.length;s+=1){let a=e[s];if(P_.has(a)){s+=1;continue}a.startsWith("-")||o.push(a.toLowerCase())}let i=XI[r];return i?i(e,o):YI.has(r)}function oT(e){let t=j_(e.argv)?.command,r=nT(e.argv),n=$_(e.projectRoot).filter(l=>ut(l.version,e.executingVersion)!==null).sort((l,u)=>ut(u.version,l.version)),o=n[0],i=o!==void 0&&ut(e.executingVersion,o.version)===-1,s=Ni(e.executingVersion),a=JI(n,s),c=r&&a!==void 0,d=i&&!r?{code:"project_runtime_stale_read",executing_version:e.executingVersion,project_version:o.version,source:o.source,message:"This read is using an older pm runtime than the project requires.",next_steps:[`Run the command through the project's installed ${Dn} ${o.version}.`,"Install the project dependencies with its declared package manager if the local executable is missing."]}:void 0;return{compatible:!r||!i&&!c||e.allowStale===!0,executing_version:e.executingVersion,...o?{project_version:o.version,source:o.source}:{},...t?{command:t}:{},mutating:r,stale:i,history_epoch_incompatible:c,writer_item_hash_version:s,...a?{incompatible_project_version:a.declaration,incompatible_source:a.source}:{},...d?{warning:d}:{},override_applied:r&&(i||c)&&e.allowStale===!0}}function iF(e){let t=oT(e);if(t.compatible)return t;throw t.history_epoch_incompatible?new g(`pm ${t.executing_version} cannot write item-hash epoch ${t.writer_item_hash_version} into a project pinned to pm ${t.incompatible_project_version}.`,h.CONFLICT,{code:"project_runtime_history_epoch_incompatible",reason:t.incompatible_source,why:`The pinned runtime cannot read item_hash_version ${t.writer_item_hash_version}; allowing the write would break its health and validation gates.`,nextSteps:[`Upgrade the project's ${Dn} pin to ${Mi} or newer before mutating tracker history.`,"For an intentional coordinated migration only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]}):new g(`pm ${t.executing_version} cannot mutate a project pinned to newer pm ${t.project_version}.`,h.CONFLICT,{code:"project_runtime_stale_mutation",reason:t.source,why:"An older runtime can write storage, history, and merge contracts it does not understand.",nextSteps:[`Run this command through the project's installed ${Dn} ${t.project_version}.`,"For an intentional recovery only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]})}export{z_ as a,U_ as b,H_ as c,q_ as d,Fi as e,iT as f,V_ as g,Dr as h,zn as i,sT as j,aT as k,cT as l,zi as m,qi as n,Vi as o,mT as p,pT as q,_T as r,Q_ as s,nd as t,yT as u,ws as v,Bi as w,od as x,Vn as y,Bn as z,ET as A,kT as B,ay as C,OT as D,AT as E,IT as F,sd as G,TT as H,CT as I,RT as J,id as K,ad as L,xT as M,cy as N,cd as O,Gt as P,Gn as Q,Kt as R,Kn as S,DT as T,PT as U,MT as V,Xn as W,Jn as X,$T as Y,jT as Z,LT as _,FT as $,Zn as aa,Mr as ba,Wi as ca,zT as da,ld as ea,UT as fa,HT as ga,qT as ha,VT as ia,py as ja,pd as ka,bd as la,QT as ma,Xi as na,Ay as oa,eC as pa,zy as qa,Uy as ra,tC as sa,rC as ta,uC as ua,nh as va,fC as wa,mC as xa,pC as ya,kd as za,Oe as Aa,_C as Ba,yC as Ca,hC as Da,Ji as Ea,Zi as Fa,eo as Ga,ih as Ha,gC as Ia,sh as Ja,ah as Ka,bC as La,wC as Ma,ch as Na,vC as Oa,R as Pa,W as Qa,ro as Ra,bh as Sa,Od as Ta,Qi as Ua,Eh as Va,kh as Wa,no as Xa,Id as Ya,Oh as Za,Th as _a,CC as $a,RC as ab,Nh as bb,Dh as cb,Ph as db,MC as eb,$C as fb,Mh as gb,oo as hb,jC as ib,LC as jb,$h as kb,jh as lb,Lh as mb,Cd as nb,Yt as ob,Fh as pb,FC as qb,zC as rb,UC as sb,HC as tb,qC as ub,VC as vb,BC as wb,io as xb,so as yb,Xt as zb,F as Ab,ao as Bb,XC as Cb,co as Db,Rd as Eb,es as Fb,Gh as Gb,Kh as Hb,zr as Ib,ts as Jb,rs as Kb,ns as Lb,os as Mb,is as Nb,ss as Ob,As as Pb,Xh as Qb,Jh as Rb,tg as Sb,rg as Tb,jd as Ub,ng as Vb,cs as Wb,lR as Xb,Fd as Yb,zd as Zb,lo as _b,mR as $b,Hd as ac,pR as bc,wl as cc,jl as dc,Ll as ec,cg as fc,ds as gc,lg as hc,ls as ic,us as jc,fs as kc,ms as lc,ps as mc,_s as nc,hs as oc,gs as pc,bs as qc,Zg as rc,eb as sc,tb as tc,db as uc,Kx as vc,Yx as wc,Xx as xc,eN as yc,rN as zc,Tb as Ac,Cb as Bc,Ds as Cc,Nb as Dc,Db as Ec,lN as Fc,bo as Gc,uN as Hc,fN as Ic,mN as Jc,pN as Kc,_N as Lc,yN as Mc,hN as Nc,tu as Oc,gN as Pc,bN as Qc,ru as Rc,wN as Sc,wo as Tc,vN as Uc,EN as Vc,kN as Wc,SN as Xc,ON as Yc,vo as Zc,AN as _c,nr as $c,IN as ad,TN as bd,CN as cd,RN as dd,xN as ed,or as fd,jN as gd,LN as hd,sn as id,HN as jd,Eo as kd,Lb as ld,Fb as md,qN as nd,Ae as od,VN as pd,Vb as qd,Gb as rd,ew as sd,du as td,fu as ud,tw as vd,rw as wd,nw as xd,ko as yd,GN as zd,lu as Ad,uu as Bd,ir as Cd,JN as Dd,pu as Ed,Oo as Fd,aw as Gd,Ge as Hd,sr as Id,rn as Jd,Ao as Kd,nn as Ld,_u as Md,QN as Nd,on as Od,Hs as Pd,an as Qd,kw as Rd,mD as Sd,Ou as Td,Sw as Ud,Dw as Vd,Mw as Wd,Au as Xd,$w as Yd,jw as Zd,Iu as _d,Et as $d,Tu as ae,pD as be,_D as ce,vD as de,Fs as ee,zs as fe,Ro as ge,Nu as he,Us as ie,Du as je,cn as ke,kD as le,kt as me,zD as ne,UD as oe,Zw as pe,lr as qe,HD as re,Bu as se,iv as te,qD as ue,Yu as ve,Ks as we,rf as xe,nf as ye,of as ze,sf as Ae,No as Be,Ys as Ce,un as De,oP as Ee,iP as Fe,fn as Ge,Xs as He,Qs as Ie,sP as Je,Dv as Ke,aP as Le,cP as Me,Do as Ne,$v as Oe,jv as Pe,mP as Qe,pP as Re,Ie as Se,je as Te,_n as Ue,ur as Ve,oe as We,wP as Xe,vP as Ye,ia as Ze,EE as _e,Lo as $e,TE as af,le as bf,RE as cf,Le as df,Y as ef,XP as ff,pr as gf,UE as hf,JP as if,ZP as jf,HE as kf,QP as lf,e1 as mf,t1 as nf,zf as of,WE as pf,m1 as qf,KE as rf,Hf as sf,p1 as tf,Vf as uf,XE as vf,e0 as wf,Bf as xf,Kf as yf,Yf as zf,g1 as Af,v1 as Bf,Bo as Cf,E1 as Df,k1 as Ef,S1 as Ff,O1 as Gf,A1 as Hf,I1 as If,Jf,C0 as Kf,bn as Lf,Wo as Mf,H1 as Nf,q1 as Of,om as Pf,X0 as Qf,rM as Rf,im as Sf,sm as Tf,Oa as Uf,am as Vf,oM as Wf,cm as Xf,iM as Yf,dm as Zf,cM as _f,ek as $f,lm as ag,Tt as bg,tt as cg,um as dg,rt as eg,ie as fg,Ta as gg,Te as hg,ue as ig,vM as jg,EM as kg,wm as lg,vm as mg,Ca as ng,Em as og,km as pg,kM as qg,Am as rg,En as sg,RM as tg,xM as ug,xa as vg,Na as wg,DM as xg,Da as yg,Tm as zg,Hk as Ag,PM as Bg,ei as Cg,Vk as Dg,LM as Eg,ti as Fg,$S as Gg,oi as Hg,tO as Ig,n$ as Jg,o$ as Kg,vr as Lg,Um as Mg,Rt as Ng,Ga as Og,c$ as Pg,d$ as Qg,Xa as Rg,Wm as Sg,Za as Tg,g$ as Ug,b$ as Vg,w$ as Wg,v$ as Xg,E$ as Yg,k$ as Zg,ac as _g,cc as $g,ep as ah,D$ as bh,P$ as ch,M$ as dh,$$ as eh,j$ as fh,L$ as gh,fc as hh,ip as ih,F$ as jh,z$ as kh,U$ as lh,zO as mh,H$ as nh,cp as oh,UO as ph,Fe as qh,X$ as rh,HO as sh,qO as th,Sr as uh,lp as vh,sA as wh,fj as xh,mj as yh,pj as zh,bA as Ah,hi as Bh,jt as Ch,Tn as Dh,EA as Eh,kA as Fh,Lp as Gh,Ar as Hh,Lj as Ih,Ac as Jh,wi as Kh,Fp as Lh,Ic as Mh,Fj as Nh,Up as Oh,Hp as Ph,zj as Qh,Cn as Rh,Rn as Sh,Vp as Th,$A as Uh,vi as Vh,Jj as Wh,Tc as Xh,Ei as Yh,Zj as Zh,Qj as _h,Kp as $h,ki as ai,Jp as bi,Ft as ci,BA as di,eL as ei,tL as fi,ct as gi,zt as hi,pL as ii,_L as ji,yL as ki,t_ as li,hL as mi,gL as ni,bL as oi,Dc as pi,IL as qi,qt as ri,KL as si,_I as ti,p_ as ui,YL as vi,Ri as wi,WI as xi,N_ as yi,XL as zi,JL as Ai,Mi as Bi,ut as Ci,Ni as Di,$_ as Ei,oF as Fi,nT as Gi,oT as Hi,iF as Ii};
|
|
113
|
-
//# sourceMappingURL=chunk-OUDR2HWR.js.map
|